Whamcloud - gitweb
LU-13070 mdd: try old format for orphan names during recovery
[fs/lustre-release.git] / lustre / utils / lfs.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2011, 2017, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  * Lustre is a trademark of Sun Microsystems, Inc.
31  *
32  * lustre/utils/lfs.c
33  *
34  * Author: Peter J. Braam <braam@clusterfs.com>
35  * Author: Phil Schwan <phil@clusterfs.com>
36  * Author: Robert Read <rread@clusterfs.com>
37  */
38
39 /* for O_DIRECTORY */
40 #ifndef _GNU_SOURCE
41 #define _GNU_SOURCE
42 #endif
43
44 #include <stdlib.h>
45 #include <stdio.h>
46 #include <inttypes.h>
47 #include <getopt.h>
48 #include <string.h>
49 #include <mntent.h>
50 #include <unistd.h>
51 #include <errno.h>
52 #include <err.h>
53 #include <pwd.h>
54 #include <grp.h>
55 #include <sys/ioctl.h>
56 #include <sys/quota.h>
57 #include <sys/time.h>
58 #include <sys/types.h>
59 #include <sys/stat.h>
60 #include <sys/param.h>
61 #include <sys/xattr.h>
62 #include <fcntl.h>
63 #include <dirent.h>
64 #include <time.h>
65 #include <ctype.h>
66 #include <zlib.h>
67 #include <libgen.h>
68 #include <asm/byteorder.h>
69 #include "lfs_project.h"
70
71 #include <libcfs/util/string.h>
72 #include <libcfs/util/ioctl.h>
73 #include <libcfs/util/parser.h>
74 #include <lustre/lustreapi.h>
75 #include <linux/lustre/lustre_ver.h>
76 #include <linux/lustre/lustre_param.h>
77 #include <linux/lnet/nidstr.h>
78 #include <cyaml.h>
79
80 #ifndef ARRAY_SIZE
81 # define ARRAY_SIZE(a) ((sizeof(a)) / (sizeof((a)[0])))
82 #endif /* !ARRAY_SIZE */
83
84 /* all functions */
85 static int lfs_find(int argc, char **argv);
86 static int lfs_getstripe(int argc, char **argv);
87 static int lfs_getdirstripe(int argc, char **argv);
88 static int lfs_setdirstripe(int argc, char **argv);
89 static int lfs_rmentry(int argc, char **argv);
90 static int lfs_osts(int argc, char **argv);
91 static int lfs_mdts(int argc, char **argv);
92 static int lfs_df(int argc, char **argv);
93 static int lfs_getname(int argc, char **argv);
94 static int lfs_check(int argc, char **argv);
95 #ifdef HAVE_SYS_QUOTA_H
96 static int lfs_setquota(int argc, char **argv);
97 static int lfs_quota(int argc, char **argv);
98 static int lfs_project(int argc, char **argv);
99 #endif
100 static int lfs_flushctx(int argc, char **argv);
101 static int lfs_poollist(int argc, char **argv);
102 static int lfs_changelog(int argc, char **argv);
103 static int lfs_changelog_clear(int argc, char **argv);
104 static int lfs_fid2path(int argc, char **argv);
105 static int lfs_path2fid(int argc, char **argv);
106 static int lfs_rmfid(int argc, char **argv);
107 static int lfs_data_version(int argc, char **argv);
108 static int lfs_hsm_state(int argc, char **argv);
109 static int lfs_hsm_set(int argc, char **argv);
110 static int lfs_hsm_clear(int argc, char **argv);
111 static int lfs_hsm_action(int argc, char **argv);
112 static int lfs_hsm_archive(int argc, char **argv);
113 static int lfs_hsm_restore(int argc, char **argv);
114 static int lfs_hsm_release(int argc, char **argv);
115 static int lfs_hsm_remove(int argc, char **argv);
116 static int lfs_hsm_cancel(int argc, char **argv);
117 static int lfs_swap_layouts(int argc, char **argv);
118 static int lfs_mv(int argc, char **argv);
119 static int lfs_ladvise(int argc, char **argv);
120 static int lfs_getsom(int argc, char **argv);
121 static int lfs_mirror(int argc, char **argv);
122 static int lfs_mirror_list_commands(int argc, char **argv);
123 static int lfs_list_commands(int argc, char **argv);
124 static inline int lfs_mirror_resync(int argc, char **argv);
125 static inline int lfs_mirror_verify(int argc, char **argv);
126 static inline int lfs_mirror_read(int argc, char **argv);
127 static inline int lfs_mirror_write(int argc, char **argv);
128 static inline int lfs_mirror_copy(int argc, char **argv);
129
130 enum setstripe_origin {
131         SO_SETSTRIPE,
132         SO_MIGRATE,
133         SO_MIGRATE_MDT,
134         SO_MIRROR_CREATE,
135         SO_MIRROR_EXTEND,
136         SO_MIRROR_SPLIT,
137 };
138 static int lfs_setstripe_internal(int argc, char **argv,
139                                   enum setstripe_origin opc);
140
141 static inline int lfs_setstripe(int argc, char **argv)
142 {
143         return lfs_setstripe_internal(argc, argv, SO_SETSTRIPE);
144 }
145 static inline int lfs_setstripe_migrate(int argc, char **argv)
146 {
147         return lfs_setstripe_internal(argc, argv, SO_MIGRATE);
148 }
149 static inline int lfs_mirror_create(int argc, char **argv)
150 {
151         return lfs_setstripe_internal(argc, argv, SO_MIRROR_CREATE);
152 }
153 static inline int lfs_mirror_extend(int argc, char **argv)
154 {
155         return lfs_setstripe_internal(argc, argv, SO_MIRROR_EXTEND);
156 }
157 static inline int lfs_mirror_split(int argc, char **argv)
158 {
159         return lfs_setstripe_internal(argc, argv, SO_MIRROR_SPLIT);
160 }
161
162 /* Setstripe and migrate share mostly the same parameters */
163 #define SSM_CMD_COMMON(cmd) \
164         "usage: "cmd" [--component-end|-E <comp_end>]\n"                \
165         "                 [--stripe-count|-c <stripe_count>]\n"         \
166         "                 [--stripe-index|-i <start_ost_idx>]\n"        \
167         "                 [--stripe-size|-S <stripe_size>]\n"           \
168         "                 [--layout|-L <pattern>]\n"                    \
169         "                 [--pool|-p <pool_name>]\n"                    \
170         "                 [--ost|-o <ost_indices>]\n"                   \
171         "                 [--yaml|-y <yaml_template_file>]\n"           \
172         "                 [--copy=<lustre_src>]\n"
173
174 #define SSM_HELP_COMMON \
175         "\tstripe_count: Number of OSTs to stripe over (0=fs default, -1 all)\n" \
176         "\tstart_ost_idx: OST index of first stripe (-1=default round robin)\n"\
177         "\tstripe_size:  Number of bytes on each OST (0=fs default)\n" \
178         "\t              Can be specified with K, M or G (for KB, MB, GB\n" \
179         "\t              respectively)\n"                               \
180         "\tpool_name:    Name of OST pool to use (default none)\n"      \
181         "\tlayout:       stripe pattern type: raid0, mdt (default raid0)\n"\
182         "\tost_indices:  List of OST indices, can be repeated multiple times\n"\
183         "\t              Indices be specified in a format of:\n"        \
184         "\t                -o <ost_1>,<ost_i>-<ost_j>,<ost_n>\n"        \
185         "\t              Or:\n"                                         \
186         "\t                -o <ost_1> -o <ost_i>-<ost_j> -o <ost_n>\n"  \
187         "\t              If --pool is set with --ost, then the OSTs\n"  \
188         "\t              must be the members of the pool.\n"            \
189         "\tcomp_end:     Extent end of component, start after previous end.\n"\
190         "\t              Can be specified with K, M or G (for KB, MB, GB\n" \
191         "\t              respectively, -1 for EOF). Must be a multiple of\n"\
192         "\t              stripe_size.\n"                                      \
193         "\tyaml_template_file:\n"                                             \
194         "\t              YAML layout template file, can't be used with -c,\n" \
195         "\t              -i, -S, -p, -o, or -E arguments.\n"                  \
196         "\tlustre_src:   Lustre file/dir whose layout info is used to set\n"  \
197         "\t              another lustre file or directory, can't used with\n" \
198         "\t              -c, -i, -S, -p, -o, or -E arguments.\n"
199
200 #define MIRROR_CREATE_HELP                                                     \
201         "\tmirror_count: Number of mirrors to be created with the upcoming\n"  \
202         "\t              setstripe layout options\n"                           \
203         "\t              It defaults to 1 if not specified; if specified,\n"   \
204         "\t              it must follow the option without a space.\n"         \
205         "\t              The option can also be repeated multiple times to\n"  \
206         "\t              separate mirrors that have different layouts.\n"      \
207         "\tsetstripe options: Mirror layout\n"                                 \
208         "\t              It can be a plain layout or a composite layout.\n"    \
209         "\t              If not specified, the stripe options inherited\n"     \
210         "\t              from the previous component will be used.\n"          \
211         "\tflags:        set flags to the component of the current mirror.\n"  \
212         "\t              Only \"prefer\" flag is supported so far.\n"
213
214 #define MIRROR_EXTEND_HELP                                                     \
215         MIRROR_CREATE_HELP                                                     \
216         "\tvictim_file:  The layout of victim_file will be split and used\n"   \
217         "\t              as a mirror added to the mirrored file.\n"            \
218         "\tno-verify:    This option indicates not to verify the mirror(s)\n"  \
219         "\t              from victim file(s) in case the victim file(s)\n"     \
220         "\t              contains the same data as the original mirrored\n"    \
221         "\t              file.\n"
222
223 #define MIRROR_EXTEND_USAGE                                                    \
224         "                 <--mirror-count|-N[mirror_count]>\n"                 \
225         "                 [setstripe options|-f <victim_file>]\n"              \
226         "                 [--no-verify]\n"
227
228 #define SETSTRIPE_USAGE                                                 \
229         SSM_CMD_COMMON("setstripe")                                     \
230         MIRROR_EXTEND_USAGE                                             \
231         "                 <directory|filename>\n"                       \
232         SSM_HELP_COMMON                                                 \
233         MIRROR_EXTEND_HELP
234
235 #define MIGRATE_USAGE                                                   \
236         SSM_CMD_COMMON("migrate  ")                                     \
237         "                 [--block|-b]\n"                               \
238         "                 [--non-block|-n]\n"                           \
239         "                 [--non-direct|-D]\n"                          \
240         "                 <filename>\n"                                 \
241         SSM_HELP_COMMON                                                 \
242         "\n"                                                            \
243         "\tblock:        Block file access during data migration (default)\n" \
244         "\tnon-block:    Abort migrations if concurrent access is detected\n" \
245         "\tnon-direct:   Do not use direct I/O to copy file contents\n" \
246
247 #define SETDIRSTRIPE_USAGE                                              \
248         "               [--mdt-count|-c stripe_count>\n"                \
249         "               [--mdt-index|-i mdt_index[,mdt_index,...]\n"    \
250         "               [--mdt-hash|-H mdt_hash]\n"                     \
251         "               [--default|-D] [--mode|-m mode] <dir>\n"        \
252         "\tstripe_count: stripe count of the striped directory\n"       \
253         "\tmdt_index: MDT index of first stripe\n"                      \
254         "\tmdt_hash:  hash type of the striped directory. mdt types:\n" \
255         "       fnv_1a_64 FNV-1a hash algorithm (default)\n"            \
256         "       all_char  sum of characters % MDT_COUNT (not recommended)\n" \
257         "\tdefault_stripe: set default dirstripe of the directory\n"    \
258         "\tmode: the mode of the directory\n"
259
260 /**
261  * command_t mirror_cmdlist - lfs mirror commands.
262  */
263 command_t mirror_cmdlist[] = {
264         { .pc_name = "create", .pc_func = lfs_mirror_create,
265           .pc_help = "Create a mirrored file.\n"
266                 "usage: lfs mirror create "
267                 "<--mirror-count|-N[mirror_count]> "
268                 "[setstripe options] ... <filename|directory>\n"
269           MIRROR_CREATE_HELP },
270         { .pc_name = "extend", .pc_func = lfs_mirror_extend,
271           .pc_help = "Extend a mirrored file.\n"
272                 "usage: lfs mirror extend "
273                 "<--mirror-count|-N[mirror_count]> [--no-verify] "
274                 "[setstripe options|-f <victim_file>] ... <filename>\n"
275           MIRROR_EXTEND_HELP },
276         { .pc_name = "split", .pc_func = lfs_mirror_split,
277           .pc_help = "Split a mirrored file.\n"
278         "usage: lfs mirror split <--mirror-id <mirror_id> |\n"
279         "\t             <--component-id|-I <comp_id>|-p <pool>> [--destroy|-d]\n"
280         "\t             [-f <new_file>] <mirrored file>\n"
281         "\tmirror_id:   The numerical unique identifier for a mirror. It\n"
282         "\t             can be fetched by lfs getstripe command.\n"
283         "\tcomp_id:     Unique component ID within a mirror.\n"
284         "\tpool:        Components on specified pool.\n"
285         "\tnew_file:    This option indicates the layout of the split\n"
286         "\t             mirror will be stored into. If not specified,\n"
287         "\t             a new file named <mirrored_file>.mirror~<mirror_id>\n"
288         "\t             will be used.\n" },
289         { .pc_name = "read", .pc_func = lfs_mirror_read,
290           .pc_help = "Read the content of a specified mirror of a file.\n"
291                 "usage: lfs mirror read <--mirror-id|-N <mirror_id> "
292                 "[--outfile|-o <output_file>] <mirrored_file>\n" },
293         { .pc_name = "write", .pc_func = lfs_mirror_write,
294           .pc_help = "Write to a specified mirror of a file.\n"
295                 "usage: lfs mirror write <--mirror-id|-N <mirror_id> "
296                 "[--inputfile|-i <input_file>] <mirrored_file>\n" },
297         { .pc_name = "copy", .pc_func = lfs_mirror_copy,
298           .pc_help = "Copy a specified mirror to other mirror(s) of a file.\n"
299                 "usage: lfs mirror copy <--read-mirror|-i <id0>> "
300                 "<--write-mirror|-o <id1,id2>> <mirrored_file>\n" },
301         { .pc_name = "resync", .pc_func = lfs_mirror_resync,
302           .pc_help = "Resynchronizes out-of-sync mirrored file(s).\n"
303                 "usage: lfs mirror resync [--only <mirror_id[,...]>] "
304                 "<mirrored file> [<mirrored file2>...]\n"},
305         { .pc_name = "verify", .pc_func = lfs_mirror_verify,
306           .pc_help = "Verify mirrored file(s).\n"
307                 "usage: lfs mirror verify "
308                 "[--only <mirror_id,mirror_id2[,...]>] "
309                 "[--verbose|-v] <mirrored_file> [<mirrored_file2> ...]\n"},
310         { .pc_name = "list-commands", .pc_func = lfs_mirror_list_commands,
311           .pc_help = "list commands supported by lfs mirror"},
312         { .pc_name = "help", .pc_func = Parser_help, .pc_help = "help" },
313         { .pc_name = "exit", .pc_func = Parser_quit, .pc_help = "quit" },
314         { .pc_name = "quit", .pc_func = Parser_quit, .pc_help = "quit" },
315         { .pc_help = NULL }
316 };
317
318 /* all available commands */
319 command_t cmdlist[] = {
320         {"setstripe", lfs_setstripe, 0,
321          "To create a file with specified striping/composite layout, or\n"
322          "create/replace the default layout on an existing directory:\n"
323          SSM_CMD_COMMON("setstripe")
324          "                 <directory|filename>\n"
325          " or\n"
326          "To add component(s) to an existing composite file:\n"
327          SSM_CMD_COMMON("setstripe --component-add")
328          SSM_HELP_COMMON
329          "To totally delete the default striping from an existing directory:\n"
330          "usage: setstripe -d <directory>\n"
331          " or\n"
332          "To create a mirrored file or set s default mirror layout on a directory:\n"
333          "usage: setstripe -N[mirror_count] [STRIPE_OPTIONS] <directory|filename>\n"
334          " or\n"
335          "To delete the last component(s) from an existing composite file\n"
336          "(note that this will also delete any data in those components):\n"
337          "usage: setstripe --component-del [--component-id|-I <comp_id>]\n"
338          "                               [--component-flags|-F <comp_flags>]\n"
339          "                               <filename>\n"
340          "\tcomp_id:     Unique component ID to delete\n"
341          "\tcomp_flags:  'init' indicating all instantiated components\n"
342          "\t             '^init' indicating all uninstantiated components\n"
343          "\t-I and -F cannot be specified at the same time\n"},
344         {"getstripe", lfs_getstripe, 0,
345          "To list the layout pattern for a given file or files in a\n"
346          "directory or recursively for all files in a directory tree.\n"
347          "usage: getstripe [--ost|-O <uuid>] [--quiet|-q] [--verbose|-v]\n"
348          "                 [--stripe-count|-c] [--stripe-index|-i] [--fid|-F]\n"
349          "                 [--pool|-p] [--stripe-size|-S] [--directory|-d]\n"
350          "                 [--mdt-index|-m] [--recursive|-r] [--raw|-R]\n"
351          "                 [--layout|-L] [--generation|-g] [--yaml|-y]\n"
352          "                 [--component-id[=comp_id]|-I[comp_id]]\n"
353          "                 [--component-flags[=comp_flags]]\n"
354          "                 [--component-count]\n"
355          "                 [--component-start[=[+-]comp_start]]\n"
356          "                 [--component-end[=[+-]comp_end]|-E[[+-]comp_end]]\n"
357          "                 [[!] --mirror-index=[+-]<index> |\n"
358          "                  [!] --mirror-id=[+-]<id>]\n"
359          "                 <directory|filename> ..."},
360         {"setdirstripe", lfs_setdirstripe, 0,
361          "To create a striped directory on a specified MDT. This can only\n"
362          "be done on MDT0 with the right of administrator.\n"
363          "usage: setdirstripe [OPTION] <directory>\n"
364          SETDIRSTRIPE_USAGE},
365         {"getdirstripe", lfs_getdirstripe, 0,
366          "To list the layout pattern info for a given directory\n"
367          "or recursively for all directories in a directory tree.\n"
368          "usage: getdirstripe [--mdt-count|-c] [--mdt-index|-m|-i]\n"
369          "                    [--mdt-hash|-H] [--obd|-O <uuid>]\n"
370          "                    [--recursive|-r] [--yaml|-y]\n"
371          "                    [--default|-D] <dir> ..."},
372         {"mkdir", lfs_setdirstripe, 0,
373          "To create a striped directory on a specified MDT. This can only\n"
374          "be done on MDT0 with the right of administrator.\n"
375          "usage: mkdir [OPTION] <directory>\n"
376          SETDIRSTRIPE_USAGE},
377         {"rm_entry", lfs_rmentry, 0,
378          "To remove the name entry of the remote directory. Note: This\n"
379          "command will only delete the name entry, i.e. the remote directory\n"
380          "will become inaccessable after this command. This can only be done\n"
381          "by the administrator\n"
382          "usage: rm_entry <dir>\n"},
383         {"pool_list", lfs_poollist, 0,
384          "List pools or pool OSTs\n"
385          "usage: pool_list <fsname>[.<pool>] | <pathname>\n"},
386         {"find", lfs_find, 0,
387          "find files matching given attributes recursively in directory tree.\n"
388          "usage: find <directory|filename> ...\n"
389          "     [[!] --atime|-A [+-]N] [[!] --ctime|-C [+-]N]\n"
390          "     [[!] --mtime|-M [+-]N] [--maxdepth|-D N] [[!] --blocks|-b N]\n"
391          "     [[!] --mdt-index|--mdt|-m <uuid|index,...>]\n"
392          "     [[!] --name|-n <pattern>] [[!] --ost|-O <uuid|index,...>]\n"
393          "     [--print|-P] [--print0|-0] [[!] --size|-s [+-]N[bkMGTPE]]\n"
394          "     [[!] --stripe-count|-c [+-]<stripes>]\n"
395          "     [[!] --stripe-index|-i <index,...>]\n"
396          "     [[!] --stripe-size|-S [+-]N[kMGT]] [[!] --type|-t <filetype>]\n"
397          "     [[!] --gid|-g|--group|-G <gid>|<gname>]\n"
398          "     [[!] --uid|-u|--user|-U <uid>|<uname>] [[!] --pool <pool>]\n"
399          "     [[!] --projid <projid>]\n"
400          "     [[!] --layout|-L released,raid0,mdt]\n"
401          "     [[!] --component-count [+-]<comp_cnt>]\n"
402          "     [[!] --component-start [+-]N[kMGTPE]]\n"
403          "     [[!] --component-end|-E [+-]N[kMGTPE]]\n"
404          "     [[!] --component-flags <comp_flags>]\n"
405          "     [[!] --mirror-count|-N [+-]<n>]\n"
406          "     [[!] --mirror-state <[^]state>]\n"
407          "     [[!] --mdt-count|-T [+-]<stripes>]\n"
408          "     [[!] --mdt-hash|-H <hashtype>\n"
409          "\t !: used before an option indicates 'NOT' requested attribute\n"
410          "\t -: used before a value indicates less than requested value\n"
411          "\t +: used before a value indicates more than requested value\n"
412          "\thashtype:   hash type of the striped directory.\n"
413          "\t            fnv_1a_64 FNV-1a hash algorithm\n"
414          "\t            all_char  sum of characters % MDT_COUNT\n"},
415         {"check", lfs_check, 0,
416          "Display the status of MDS or OSTs (as specified in the command)\n"
417          "or all the servers (MDS and OSTs).\n"
418          "usage: check <osts|mds|servers>"},
419         {"osts", lfs_osts, 0, "list OSTs connected to client "
420          "[for specified path only]\n" "usage: osts [path]"},
421         {"mdts", lfs_mdts, 0, "list MDTs connected to client "
422          "[for specified path only]\n" "usage: mdts [path]"},
423         {"df", lfs_df, 0,
424          "report filesystem disk space usage or inodes usage"
425          "of each MDS and all OSDs or a batch belonging to a specific pool .\n"
426          "Usage: df [-i] [-h] [--lazy|-l] [--pool|-p <fsname>[.<pool>] [path]"},
427         {"getname", lfs_getname, 0, "list instances and specified mount points "
428          "[for specified path only]\n"
429          "Usage: getname [-h]|[path ...] "},
430 #ifdef HAVE_SYS_QUOTA_H
431         {"setquota", lfs_setquota, 0, "Set filesystem quotas.\n"
432          "usage: setquota <-u|-g|-p> <uname>|<uid>|<gname>|<gid>|<projid>\n"
433          "                -b <block-softlimit> -B <block-hardlimit>\n"
434          "                -i <inode-softlimit> -I <inode-hardlimit> <filesystem>\n"
435          "       setquota <-u|--user|-g|--group|-p|--projid> <uname>|<uid>|<gname>|<gid>|<projid>\n"
436          "                [--block-softlimit <block-softlimit>]\n"
437          "                [--block-hardlimit <block-hardlimit>]\n"
438          "                [--inode-softlimit <inode-softlimit>]\n"
439          "                [--inode-hardlimit <inode-hardlimit>] <filesystem>\n"
440          "       setquota [-t] <-u|--user|-g|--group|-p|--projid>\n"
441          "                [--block-grace <block-grace>]\n"
442          "                [--inode-grace <inode-grace>] <filesystem>\n"
443          "       setquota <-U|-G|-P>\n"
444          "                -b <block-softlimit> -B <block-hardlimit>\n"
445          "                -i <inode-softlimit> -I <inode-hardlimit> <filesystem>\n"
446          "       setquota <-U|--default-usr|-G|--default-grp|-P|--default-prj>\n"
447          "                [--block-softlimit <block-softlimit>]\n"
448          "                [--block-hardlimit <block-hardlimit>]\n"
449          "                [--inode-softlimit <inode-softlimit>]\n"
450          "                [--inode-hardlimit <inode-hardlimit>] <filesystem>\n"
451          "       setquota <-u|-g|-p> <uname>|<uid>|<gname>|<gid>|<projid>\n"
452          "                <-d|--default>\n"
453          "       -b can be used instead of --block-softlimit/--block-grace\n"
454          "       -B can be used instead of --block-hardlimit\n"
455          "       -i can be used instead of --inode-softlimit/--inode-grace\n"
456          "       -I can be used instead of --inode-hardlimit\n"
457          "       -d can be used instead of --default\n\n"
458          "Note: The total quota space will be split into many qunits and\n"
459          "      balanced over all server targets, the minimal qunit size is\n"
460          "      1M bytes for block space and 1K inodes for inode space.\n\n"
461          "      The maximum quota grace time is 2^48 - 1 seconds.\n\n"
462          "      Quota space rebalancing process will stop when this mininum\n"
463          "      value is reached. As a result, quota exceeded can be returned\n"
464          "      while many targets still have 1MB or 1K inodes of spare\n"
465          "      quota space."},
466         {"quota", lfs_quota, 0, "Display disk usage and limits.\n"
467          "usage: quota [-q] [-v] [-h] [-o <obd_uuid>|-i <mdt_idx>|-I "
468                        "<ost_idx>]\n"
469          "             [<-u|-g|-p> <uname>|<uid>|<gname>|<gid>|<projid>] <filesystem>\n"
470          "       quota [-o <obd_uuid>|-i <mdt_idx>|-I <ost_idx>] -t <-u|-g|-p> <filesystem>\n"
471         "        quota [-q] [-v] [h] <-U|-G|-P> <filesystem>"},
472         {"project", lfs_project, 0,
473          "Change or list project attribute for specified file or directory.\n"
474          "usage: project [-d|-r] <file|directory...>\n"
475          "         list project ID and flags on file(s) or directories\n"
476          "       project [-p id] [-s] [-r] <file|directory...>\n"
477          "         set project ID and/or inherit flag for specified file(s) or directories\n"
478          "       project -c [-d|-r [-p id] [-0]] <file|directory...>\n"
479          "         check project ID and flags on file(s) or directories, print outliers\n"
480          "       project -C [-r] [-k] <file|directory...>\n"
481          "         clear the project inherit flag and ID on the file or directory\n"
482         },
483 #endif
484         {"flushctx", lfs_flushctx, 0, "Flush security context for current user.\n"
485          "usage: flushctx [-k] [mountpoint...]"},
486         {"changelog", lfs_changelog, 0,
487          "Show the metadata changes on an MDT."
488          "\nusage: changelog <mdtname> [startrec [endrec]]"},
489         {"changelog_clear", lfs_changelog_clear, 0,
490          "Indicate that old changelog records up to <endrec> are no longer of "
491          "interest to consumer <id>, allowing the system to free up space.\n"
492          "An <endrec> of 0 means all records.\n"
493          "usage: changelog_clear <mdtname> <id> <endrec>"},
494         {"fid2path", lfs_fid2path, 0,
495          "Resolve the full path(s) for given FID(s). For a specific hardlink "
496          "specify link number <linkno>.\n"
497         /* "For a historical link name, specify changelog record <recno>.\n" */
498          "usage: fid2path [--link <linkno>] <fsname|rootpath> <fid> ..."
499                 /* [ --rec <recno> ] */ },
500         {"path2fid", lfs_path2fid, 0, "Display the fid(s) for a given path(s).\n"
501          "usage: path2fid [--parents] <path> ..."},
502         {"rmfid", lfs_rmfid, 0, "Remove file(s) by FID(s)\n"
503          "usage: rmfid <fsname|rootpath> <fid> ..."},
504         {"data_version", lfs_data_version, 0, "Display file data version for "
505          "a given path.\n" "usage: data_version -[n|r|w] <path>"},
506         {"hsm_state", lfs_hsm_state, 0, "Display the HSM information (states, "
507          "undergoing actions) for given files.\n usage: hsm_state <file> ..."},
508         {"hsm_set", lfs_hsm_set, 0, "Set HSM user flag on specified files.\n"
509          "usage: hsm_set [--norelease] [--noarchive] [--dirty] [--exists] "
510          "[--archived] [--lost] [--archive-id NUM] <file> ..."},
511         {"hsm_clear", lfs_hsm_clear, 0, "Clear HSM user flag on specified "
512          "files.\n"
513          "usage: hsm_clear [--norelease] [--noarchive] [--dirty] [--exists] "
514          "[--archived] [--lost] <file> ..."},
515         {"hsm_action", lfs_hsm_action, 0, "Display current HSM request for "
516          "given files.\n" "usage: hsm_action <file> ..."},
517         {"hsm_archive", lfs_hsm_archive, 0,
518          "Archive file to external storage.\n"
519          "usage: hsm_archive [--filelist FILELIST] [--data DATA] [--archive NUM] "
520          "<file> ..."},
521         {"hsm_restore", lfs_hsm_restore, 0,
522          "Restore file from external storage.\n"
523          "usage: hsm_restore [--filelist FILELIST] [--data DATA] <file> ..."},
524         {"hsm_release", lfs_hsm_release, 0,
525          "Release files from Lustre.\n"
526          "usage: hsm_release [--filelist FILELIST] [--data DATA] <file> ..."},
527         {"hsm_remove", lfs_hsm_remove, 0,
528          "Remove file copy from external storage.\n"
529          "usage: hsm_remove [--filelist FILELIST] [--data DATA] "
530          "[--archive NUM]\n"
531          "                  (FILE [FILE ...] | "
532          "--mntpath MOUNTPATH FID [FID ...])\n"
533          "\n"
534          "Note: To remove an archived copy of a file already deleted from a "
535          "Lustre FS, the\n"
536          "--mntpath option and a list of FIDs must be specified"
537         },
538         {"hsm_cancel", lfs_hsm_cancel, 0,
539          "Cancel requests related to specified files.\n"
540          "usage: hsm_cancel [--filelist FILELIST] [--data DATA] <file> ..."},
541         {"swap_layouts", lfs_swap_layouts, 0, "Swap layouts between 2 files.\n"
542          "usage: swap_layouts <path1> <path2>"},
543         {"migrate", lfs_setstripe_migrate, 0,
544          "migrate a directory between MDTs.\n"
545          "usage: migrate [--mdt|-m] <start_mdt_index>\n"
546          "               [--mdt-count|-c] <stripe_count>\n"
547          "               [--mdt-hash|-H] <hash_type>\n"
548          "               [--verbose|-v]\n"
549          "               <directory>\n"
550          "\tmdt:        MDTs to stripe over, if only one MDT is specified\n"
551          "                      it's the MDT index of first stripe\n"
552          "\tmdt_count:  number of MDTs to stripe a directory over\n"
553          "\tmdt_hash:   hash type of the striped directory. mdt types:\n"
554          "                      fnv_1a_64 FNV-1a hash algorithm (default)\n"
555          "                      all_char  sum of characters % MDT_COUNT\n"
556          "\n"
557          "migrate file objects from one OST "
558          "layout\nto another (may be not safe with concurent writes).\n"
559          "usage: migrate  "
560          "[--stripe-count|-c] <stripe_count>\n"
561          "              [--stripe-index|-i] <start_ost_index>\n"
562          "              [--stripe-size|-S] <stripe_size>\n"
563          "              [--pool|-p] <pool_name>\n"
564          "              [--ost|-o] <ost_indices>\n"
565          "              [--block|-b]\n"
566          "              [--non-block|-n]\n"
567          "              [--non-direct|-D]\n"
568          "              <file|directory>\n"
569          "\tstripe_count:     number of OSTs to stripe a file over\n"
570          "\tstripe_ost_index: index of the first OST to stripe a file over\n"
571          "\tstripe_size:      number of bytes to store before moving to the next OST\n"
572          "\tpool_name:        name of the predefined pool of OSTs\n"
573          "\tost_indices:      OSTs to stripe over, in order\n"
574          "\tblock:            wait for the operation to return before continuing\n"
575          "\tnon-block:        do not wait for the operation to return\n"
576          "\tnon-direct:       do not use direct I/O to copy file contents.\n"},
577         {"mv", lfs_mv, 0,
578          "To move directories between MDTs. This command is deprecated, "
579          "use \"migrate\" instead.\n"
580          "usage: mv <directory|filename> [--mdt-index|-m] <mdt_index> "
581          "[--verbose|-v]\n"},
582         {"ladvise", lfs_ladvise, 0,
583          "Provide servers with advice about access patterns for a file.\n"
584          "usage: ladvise [--advice|-a ADVICE] [--start|-s START[kMGT]]\n"
585          "               [--background|-b] [--unset|-u]\n\n"
586          "               {[--end|-e END[kMGT]] | [--length|-l LENGTH[kMGT]]}\n"
587          "               {[--mode|-m [READ,WRITE]}\n"
588          "               <file> ...\n"},
589         {"mirror", lfs_mirror, mirror_cmdlist,
590          "lfs commands used to manage files with mirrored components:\n"
591          "lfs mirror create - create a mirrored file or directory\n"
592          "lfs mirror extend - add mirror(s) to an existing file\n"
593          "lfs mirror split  - split a mirror from an existing mirrored file\n"
594          "lfs mirror resync - resynchronize out-of-sync mirrored file(s)\n"
595          "lfs mirror read   - read a mirror content of a mirrored file\n"
596          "lfs mirror write  - write to a mirror of a mirrored file\n"
597          "lfs mirror copy   - copy a mirror to other mirror(s) of a file\n"
598          "lfs mirror verify - verify mirrored file(s)\n"},
599         {"getsom", lfs_getsom, 0, "To list the SOM info for a given file.\n"
600          "usage: getsom [-s] [-b] [-f] <path>\n"
601          "\t-s: Only show the size value of the SOM data for a given file\n"
602          "\t-b: Only show the blocks value of the SOM data for a given file\n"
603          "\t-f: Only show the flags value of the SOM data for a given file\n"},
604         {"help", Parser_help, 0, "help"},
605         {"exit", Parser_quit, 0, "quit"},
606         {"quit", Parser_quit, 0, "quit"},
607         {"--version", Parser_version, 0,
608          "output build version of the utility and exit"},
609         {"--list-commands", lfs_list_commands, 0,
610          "list commands supported by the utility and exit"},
611         { 0, 0, 0, NULL }
612 };
613
614
615 static int check_hashtype(const char *hashtype)
616 {
617         int i;
618
619         for (i = LMV_HASH_TYPE_ALL_CHARS; i < LMV_HASH_TYPE_MAX; i++)
620                 if (strcmp(hashtype, mdt_hash_name[i]) == 0)
621                         return i;
622
623         return 0;
624 }
625
626
627 static const char *error_loc = "syserror";
628
629 enum {
630         MIGRATION_NONBLOCK      = 1 << 0,
631         MIGRATION_MIRROR        = 1 << 1,
632         MIGRATION_NONDIRECT     = 1 << 2,
633 };
634
635 static int lfs_component_create(char *fname, int open_flags, mode_t open_mode,
636                                 struct llapi_layout *layout);
637
638 static int
639 migrate_open_files(const char *name, __u64 migration_flags,
640                    const struct llapi_stripe_param *param,
641                    struct llapi_layout *layout, int *fd_src, int *fd_tgt)
642 {
643         int                      fd = -1;
644         int                      fdv = -1;
645         int                      rflags;
646         int                      mdt_index;
647         int                      random_value;
648         char                     parent[PATH_MAX];
649         char                     volatile_file[PATH_MAX];
650         char                    *ptr;
651         int                      rc;
652         struct stat              st;
653         struct stat              stv;
654
655         if (param == NULL && layout == NULL) {
656                 error_loc = "layout information";
657                 return -EINVAL;
658         }
659
660         /* search for file directory pathname */
661         if (strlen(name) > sizeof(parent) - 1) {
662                 error_loc = "source file name";
663                 return -ERANGE;
664         }
665
666         strncpy(parent, name, sizeof(parent));
667         ptr = strrchr(parent, '/');
668         if (ptr == NULL) {
669                 if (getcwd(parent, sizeof(parent)) == NULL) {
670                         error_loc = "getcwd";
671                         return -errno;
672                 }
673         } else {
674                 if (ptr == parent) /* leading '/' */
675                         ptr = parent + 1;
676                 *ptr = '\0';
677         }
678
679         /* open file, direct io */
680         /* even if the file is only read, WR mode is nedeed to allow
681          * layout swap on fd */
682         rflags = O_RDWR;
683         if (!(migration_flags & MIGRATION_NONDIRECT))
684                 rflags |= O_DIRECT;
685         fd = open(name, rflags);
686         if (fd < 0) {
687                 rc = -errno;
688                 error_loc = "cannot open source file";
689                 return rc;
690         }
691
692         rc = llapi_file_fget_mdtidx(fd, &mdt_index);
693         if (rc < 0) {
694                 error_loc = "cannot get MDT index";
695                 goto out;
696         }
697
698         do {
699                 int open_flags = O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW;
700                 mode_t open_mode = S_IRUSR | S_IWUSR;
701
702                 random_value = random();
703                 rc = snprintf(volatile_file, sizeof(volatile_file),
704                               "%s/%s:%.4X:%.4X", parent, LUSTRE_VOLATILE_HDR,
705                               mdt_index, random_value);
706                 if (rc >= sizeof(volatile_file)) {
707                         rc = -ENAMETOOLONG;
708                         break;
709                 }
710
711                 /* create, open a volatile file, use caching (ie no directio) */
712                 if (param != NULL)
713                         fdv = llapi_file_open_param(volatile_file, open_flags,
714                                                     open_mode, param);
715                 else
716                         fdv = lfs_component_create(volatile_file, open_flags,
717                                                    open_mode, layout);
718         } while (fdv < 0 && (rc = fdv) == -EEXIST);
719
720         if (rc < 0) {
721                 error_loc = "cannot create volatile file";
722                 goto out;
723         }
724
725         /* In case the MDT does not support creation of volatile files
726          * we should try to unlink it. */
727         (void)unlink(volatile_file);
728
729         /* Not-owner (root?) special case.
730          * Need to set owner/group of volatile file like original.
731          * This will allow to pass related check during layout_swap.
732          */
733         rc = fstat(fd, &st);
734         if (rc != 0) {
735                 rc = -errno;
736                 error_loc = "cannot stat source file";
737                 goto out;
738         }
739
740         rc = fstat(fdv, &stv);
741         if (rc != 0) {
742                 rc = -errno;
743                 error_loc = "cannot stat volatile";
744                 goto out;
745         }
746
747         if (st.st_uid != stv.st_uid || st.st_gid != stv.st_gid) {
748                 rc = fchown(fdv, st.st_uid, st.st_gid);
749                 if (rc != 0) {
750                         rc = -errno;
751                         error_loc = "cannot change ownwership of volatile";
752                         goto out;
753                 }
754         }
755
756 out:
757         if (rc < 0) {
758                 if (fd > 0)
759                         close(fd);
760                 if (fdv > 0)
761                         close(fdv);
762         } else {
763                 *fd_src = fd;
764                 *fd_tgt = fdv;
765                 error_loc = NULL;
766         }
767         return rc;
768 }
769
770 static int migrate_copy_data(int fd_src, int fd_dst, int (*check_file)(int))
771 {
772         struct llapi_layout *layout;
773         size_t   buf_size = 4 * 1024 * 1024;
774         void    *buf = NULL;
775         ssize_t  rsize = -1;
776         ssize_t  wsize = 0;
777         size_t   rpos = 0;
778         size_t   wpos = 0;
779         off_t    bufoff = 0;
780         int      rc;
781
782         layout = llapi_layout_get_by_fd(fd_src, 0);
783         if (layout != NULL) {
784                 uint64_t stripe_size;
785
786                 rc = llapi_layout_stripe_size_get(layout, &stripe_size);
787                 if (rc == 0)
788                         buf_size = stripe_size;
789
790                 llapi_layout_free(layout);
791         }
792
793         /* Use a page-aligned buffer for direct I/O */
794         rc = posix_memalign(&buf, getpagesize(), buf_size);
795         if (rc != 0)
796                 return -rc;
797
798         while (1) {
799                 /* read new data only if we have written all
800                  * previously read data */
801                 if (wpos == rpos) {
802                         if (check_file) {
803                                 rc = check_file(fd_src);
804                                 if (rc < 0)
805                                         break;
806                         }
807
808                         rsize = read(fd_src, buf, buf_size);
809                         if (rsize < 0) {
810                                 rc = -errno;
811                                 break;
812                         }
813                         rpos += rsize;
814                         bufoff = 0;
815                 }
816                 /* eof ? */
817                 if (rsize == 0)
818                         break;
819
820                 wsize = write(fd_dst, buf + bufoff, rpos - wpos);
821                 if (wsize < 0) {
822                         rc = -errno;
823                         break;
824                 }
825                 wpos += wsize;
826                 bufoff += wsize;
827         }
828
829         if (rc == 0) {
830                 rc = fsync(fd_dst);
831                 if (rc < 0)
832                         rc = -errno;
833         }
834
835         free(buf);
836         return rc;
837 }
838
839 static int migrate_copy_timestamps(int fd, int fdv)
840 {
841         struct stat st;
842
843         if (fstat(fd, &st) == 0) {
844                 struct timeval tv[2] = {
845                         {.tv_sec = st.st_atime},
846                         {.tv_sec = st.st_mtime}
847                 };
848
849                 return futimes(fdv, tv);
850         }
851
852         return -errno;
853 }
854
855 static int migrate_block(int fd, int fdv)
856 {
857         __u64   dv1;
858         int     gid;
859         int     rc;
860         int     rc2;
861
862         rc = llapi_get_data_version(fd, &dv1, LL_DV_RD_FLUSH);
863         if (rc < 0) {
864                 error_loc = "cannot get dataversion";
865                 return rc;
866         }
867
868         do
869                 gid = random();
870         while (gid == 0);
871
872         /* The grouplock blocks all concurrent accesses to the file.
873          * It has to be taken after llapi_get_data_version as it would
874          * block it too. */
875         rc = llapi_group_lock(fd, gid);
876         if (rc < 0) {
877                 error_loc = "cannot get group lock";
878                 return rc;
879         }
880
881         rc = migrate_copy_data(fd, fdv, NULL);
882         if (rc < 0) {
883                 error_loc = "data copy failed";
884                 goto out_unlock;
885         }
886
887         /* Make sure we keep original atime/mtime values */
888         rc = migrate_copy_timestamps(fd, fdv);
889         if (rc < 0) {
890                 error_loc = "timestamp copy failed";
891                 goto out_unlock;
892         }
893
894         /* swap layouts
895          * for a migration we need to check data version on file did
896          * not change.
897          *
898          * Pass in gid=0 since we already own grouplock. */
899         rc = llapi_fswap_layouts_grouplock(fd, fdv, dv1, 0, 0,
900                                            SWAP_LAYOUTS_CHECK_DV1);
901         if (rc == -EAGAIN) {
902                 error_loc = "file changed";
903                 goto out_unlock;
904         } else if (rc < 0) {
905                 error_loc = "cannot swap layout";
906                 goto out_unlock;
907         }
908
909 out_unlock:
910         rc2 = llapi_group_unlock(fd, gid);
911         if (rc2 < 0 && rc == 0) {
912                 error_loc = "unlock group lock";
913                 rc = rc2;
914         }
915
916         return rc;
917 }
918
919 /**
920  * Internal helper for migrate_copy_data(). Check lease and report error if
921  * need be.
922  *
923  * \param[in]  fd           File descriptor on which to check the lease.
924  *
925  * \retval 0       Migration can keep on going.
926  * \retval -errno  Error occurred, abort migration.
927  */
928 static int check_lease(int fd)
929 {
930         int rc;
931
932         rc = llapi_lease_check(fd);
933         if (rc > 0)
934                 return 0; /* llapi_check_lease returns > 0 on success. */
935
936         return -EBUSY;
937 }
938
939 static int migrate_nonblock(int fd, int fdv)
940 {
941         __u64   dv1;
942         __u64   dv2;
943         int     rc;
944
945         rc = llapi_get_data_version(fd, &dv1, LL_DV_RD_FLUSH);
946         if (rc < 0) {
947                 error_loc = "cannot get data version";
948                 return rc;
949         }
950
951         rc = migrate_copy_data(fd, fdv, check_lease);
952         if (rc < 0) {
953                 error_loc = "data copy failed";
954                 return rc;
955         }
956
957         rc = llapi_get_data_version(fd, &dv2, LL_DV_RD_FLUSH);
958         if (rc != 0) {
959                 error_loc = "cannot get data version";
960                 return rc;
961         }
962
963         if (dv1 != dv2) {
964                 rc = -EAGAIN;
965                 error_loc = "source file changed";
966                 return rc;
967         }
968
969         /* Make sure we keep original atime/mtime values */
970         rc = migrate_copy_timestamps(fd, fdv);
971         if (rc < 0) {
972                 error_loc = "timestamp copy failed";
973                 return rc;
974         }
975
976         return 0;
977 }
978
979 static int lfs_component_set(char *fname, int comp_id,
980                              __u32 flags, __u32 neg_flags)
981 {
982         __u32 ids[2];
983         __u32 flags_array[2];
984         size_t count = 0;
985         int rc;
986
987         if (flags) {
988                 ids[count] = comp_id;
989                 flags_array[count] = flags;
990                 ++count;
991         }
992
993         if (neg_flags) {
994                 ids[count] = comp_id;
995                 flags_array[count] = neg_flags | LCME_FL_NEG;
996                 ++count;
997         }
998
999         rc = llapi_layout_file_comp_set(fname, ids, flags_array, count);
1000         if (rc) {
1001                 if (errno == EUCLEAN) {
1002                         rc = -errno;
1003                         fprintf(stderr,
1004                                 "%s: cannot set 'stale' flag on component '%#x' of the last non-stale mirror of '%s'\n",
1005                                 progname, comp_id, fname);
1006                 } else {
1007                         fprintf(stderr,
1008                                 "%s: cannot change the flags of component '%#x' of file '%s': %x / ^(%x)\n",
1009                                 progname, comp_id, fname, flags, neg_flags);
1010                 }
1011         }
1012
1013         return rc;
1014 }
1015
1016 static int lfs_component_del(char *fname, __u32 comp_id,
1017                              __u32 flags, __u32 neg_flags)
1018 {
1019         int     rc = 0;
1020
1021         if (flags && neg_flags)
1022                 return -EINVAL;
1023
1024         if (!flags && neg_flags)
1025                 flags = neg_flags | LCME_FL_NEG;
1026
1027         if ((flags && comp_id) || (!flags && !comp_id))
1028                 return -EINVAL;
1029
1030         /* LCME_FL_INIT is the only supported flag in PFL */
1031         if (flags) {
1032                 if (flags & ~LCME_KNOWN_FLAGS) {
1033                         fprintf(stderr,
1034                                 "%s setstripe: unknown flags %#x\n",
1035                                 progname, flags);
1036                         return -EINVAL;
1037                 }
1038         } else if (comp_id > LCME_ID_MAX) {
1039                 fprintf(stderr, "%s setstripe: invalid component id %u\n",
1040                         progname, comp_id);
1041                 return -EINVAL;
1042         }
1043
1044         rc = llapi_layout_file_comp_del(fname, comp_id, flags);
1045         if (rc)
1046                 fprintf(stderr,
1047                         "%s setstripe: cannot delete component %#x from '%s': %s\n",
1048                         progname, comp_id, fname, strerror(errno));
1049         return rc;
1050 }
1051
1052 static int lfs_component_add(char *fname, struct llapi_layout *layout)
1053 {
1054         int     rc;
1055
1056         if (layout == NULL)
1057                 return -EINVAL;
1058
1059         rc = llapi_layout_file_comp_add(fname, layout);
1060         if (rc)
1061                 fprintf(stderr, "Add layout component(s) to %s failed. %s\n",
1062                         fname, strerror(errno));
1063         return rc;
1064 }
1065
1066 static int lfs_component_create(char *fname, int open_flags, mode_t open_mode,
1067                                 struct llapi_layout *layout)
1068 {
1069         struct stat     st;
1070         int     fd;
1071
1072         if (layout == NULL)
1073                 return -EINVAL;
1074
1075         fd = lstat(fname, &st);
1076         if (fd == 0 && S_ISDIR(st.st_mode))
1077                 open_flags = O_DIRECTORY | O_RDONLY;
1078
1079         fd = llapi_layout_file_open(fname, open_flags, open_mode, layout);
1080         if (fd < 0)
1081                 fprintf(stderr, "%s: cannot %s '%s': %s\n", progname,
1082                         S_ISDIR(st.st_mode) ?
1083                                 "set default composite layout for" :
1084                                 "create composite file",
1085                         fname, strerror(errno));
1086         return fd;
1087 }
1088
1089 static int lfs_migrate(char *name, __u64 migration_flags,
1090                        struct llapi_stripe_param *param,
1091                        struct llapi_layout *layout)
1092 {
1093         int fd = -1;
1094         int fdv = -1;
1095         int rc;
1096
1097         rc = migrate_open_files(name, migration_flags, param, layout,
1098                                 &fd, &fdv);
1099         if (rc < 0)
1100                 goto out;
1101
1102         if (!(migration_flags & MIGRATION_NONBLOCK)) {
1103                 /* Blocking mode (forced if servers do not support file lease).
1104                  * It is also the default mode, since we cannot distinguish
1105                  * between a broken lease and a server that does not support
1106                  * atomic swap/close (LU-6785) */
1107                 rc = migrate_block(fd, fdv);
1108                 goto out;
1109         }
1110
1111         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
1112         if (rc < 0) {
1113                 error_loc = "cannot get lease";
1114                 goto out;
1115         }
1116
1117         rc = migrate_nonblock(fd, fdv);
1118         if (rc < 0) {
1119                 llapi_lease_release(fd);
1120                 goto out;
1121         }
1122
1123         /* Atomically put lease, swap layouts and close.
1124          * for a migration we need to check data version on file did
1125          * not change. */
1126         rc = llapi_fswap_layouts(fd, fdv, 0, 0, SWAP_LAYOUTS_CLOSE);
1127         if (rc < 0) {
1128                 error_loc = "cannot swap layout";
1129                 goto out;
1130         }
1131
1132 out:
1133         if (fd >= 0)
1134                 close(fd);
1135
1136         if (fdv >= 0)
1137                 close(fdv);
1138
1139         if (rc < 0)
1140                 fprintf(stderr, "error: %s: %s: %s: %s\n",
1141                         progname, name, error_loc, strerror(-rc));
1142         return rc;
1143 }
1144
1145 static int comp_str2flags(char *string, __u32 *flags, __u32 *neg_flags)
1146 {
1147         char *name;
1148
1149         if (string == NULL)
1150                 return -EINVAL;
1151
1152         *flags = 0;
1153         *neg_flags = 0;
1154         for (name = strtok(string, ","); name; name = strtok(NULL, ",")) {
1155                 bool found = false;
1156                 int i;
1157
1158                 for (i = 0; i < ARRAY_SIZE(comp_flags_table); i++) {
1159                         __u32 comp_flag = comp_flags_table[i].cfn_flag;
1160                         const char *comp_name = comp_flags_table[i].cfn_name;
1161
1162                         if (strcmp(name, comp_name) == 0) {
1163                                 *flags |= comp_flag;
1164                                 found = true;
1165                         } else if (strncmp(name, "^", 1) == 0 &&
1166                                    strcmp(name + 1, comp_name) == 0) {
1167                                 *neg_flags |= comp_flag;
1168                                 found = true;
1169                         }
1170                 }
1171                 if (!found) {
1172                         llapi_printf(LLAPI_MSG_ERROR,
1173                                      "%s: component flag '%s' not supported\n",
1174                                      progname, name);
1175                         return -EINVAL;
1176                 }
1177         }
1178
1179         if (!*flags && !*neg_flags)
1180                 return -EINVAL;
1181
1182         /* don't allow to set and exclude the same flag */
1183         if (*flags & *neg_flags)
1184                 return -EINVAL;
1185
1186         return 0;
1187 }
1188
1189 static int mirror_str2state(char *string, __u16 *state, __u16 *neg_state)
1190 {
1191         if (string == NULL)
1192                 return -EINVAL;
1193
1194         *state = 0;
1195         *neg_state = 0;
1196
1197         if (strncmp(string, "^", 1) == 0) {
1198                 *neg_state = llapi_layout_string_flags(string + 1);
1199                 if (*neg_state != 0)
1200                         return 0;
1201         } else {
1202                 *state = llapi_layout_string_flags(string);
1203                 if (*state != 0)
1204                         return 0;
1205         }
1206
1207         llapi_printf(LLAPI_MSG_ERROR,
1208                      "%s: mirrored file state '%s' not supported\n",
1209                      progname, string);
1210         return -EINVAL;
1211 }
1212
1213 /**
1214  * struct mirror_args - Command-line arguments for mirror(s).
1215  * @m_count:  Number of mirrors to be created with this layout.
1216  * @m_flags:  Mirror level flags, only 'prefer' is supported.
1217  * @m_layout: Mirror layout.
1218  * @m_file:   A victim file. Its layout will be split and used as a mirror.
1219  * @m_next:   Point to the next node of the list.
1220  *
1221  * Command-line arguments for mirror(s) will be parsed and stored in
1222  * a linked list that consists of this structure.
1223  */
1224 struct mirror_args {
1225         __u32                   m_count;
1226         __u32                   m_flags;
1227         struct llapi_layout     *m_layout;
1228         const char              *m_file;
1229         struct mirror_args      *m_next;
1230 };
1231
1232 static int mirror_sanity_check_flags(struct llapi_layout *layout, void *unused)
1233 {
1234         uint32_t flags;
1235         int rc;
1236
1237         rc = llapi_layout_comp_flags_get(layout, &flags);
1238         if (rc)
1239                 return -errno;
1240
1241         if (flags & LCME_FL_NEG) {
1242                 fprintf(stderr, "error: %s: negative flags are not supported\n",
1243                         progname);
1244                 return -EINVAL;
1245         }
1246
1247         if (flags & LCME_FL_STALE) {
1248                 fprintf(stderr, "error: %s: setting '%s' is not supported\n",
1249                         progname, comp_flags_table[LCME_FL_STALE].cfn_name);
1250                 return -EINVAL;
1251         }
1252
1253         return LLAPI_LAYOUT_ITER_CONT;
1254 }
1255
1256 static inline int mirror_sanity_check_one(struct llapi_layout *layout)
1257 {
1258         uint64_t start, end;
1259         uint64_t pattern;
1260         int rc;
1261
1262         /* LU-10112: do not support dom+flr in phase 1 */
1263         rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_FIRST);
1264         if (rc)
1265                 return -errno;
1266
1267         rc = llapi_layout_pattern_get(layout, &pattern);
1268         if (rc)
1269                 return -errno;
1270
1271         if (pattern == LOV_PATTERN_MDT || pattern == LLAPI_LAYOUT_MDT) {
1272                 fprintf(stderr, "error: %s: doesn't support dom+flr for now\n",
1273                         progname);
1274                 return -ENOTSUP;
1275         }
1276
1277         rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_LAST);
1278         if (rc)
1279                 return -errno;
1280
1281         rc = llapi_layout_comp_extent_get(layout, &start, &end);
1282         if (rc)
1283                 return -errno;
1284
1285         if (end != LUSTRE_EOF) {
1286                 fprintf(stderr, "error: %s: mirror layout doesn't reach eof\n",
1287                         progname);
1288                 return -EINVAL;
1289         }
1290
1291         rc = llapi_layout_comp_iterate(layout, mirror_sanity_check_flags, NULL);
1292         return rc;
1293 }
1294
1295 /**
1296  * enum mirror_flags - Flags for extending a mirrored file.
1297  * @MF_NO_VERIFY: Indicates not to verify the mirror(s) from victim file(s)
1298  *             in case the victim file(s) contains the same data as the
1299  *             original mirrored file.
1300  * @MF_DESTROY: Indicates to delete the mirror from the mirrored file.
1301  * @MF_COMP_ID: specified component id instead of mirror id
1302  *
1303  * Flags for extending a mirrored file.
1304  */
1305 enum mirror_flags {
1306         MF_NO_VERIFY    = 0x1,
1307         MF_DESTROY      = 0x2,
1308         MF_COMP_ID      = 0x4,
1309         MF_COMP_POOL    = 0x8,
1310 };
1311
1312 /**
1313  * mirror_create_sanity_check() - Check mirror list.
1314  * @list:  A linked list that stores the mirror arguments.
1315  *
1316  * This function does a sanity check on @list for creating
1317  * a mirrored file.
1318  *
1319  * Return: 0 on success or a negative error code on failure.
1320  */
1321 static int mirror_create_sanity_check(const char *fname,
1322                                       struct mirror_args *list)
1323 {
1324         int rc = 0;
1325         bool has_m_file = false;
1326         bool has_m_layout = false;
1327
1328         if (list == NULL)
1329                 return -EINVAL;
1330
1331         if (fname) {
1332                 struct llapi_layout *layout;
1333
1334                 layout = llapi_layout_get_by_path(fname, 0);
1335                 if (!layout) {
1336                         fprintf(stderr,
1337                                 "error: %s: file '%s' couldn't get layout\n",
1338                                 progname, fname);
1339                         return -ENODATA;
1340                 }
1341
1342                 rc = mirror_sanity_check_one(layout);
1343                 llapi_layout_free(layout);
1344
1345                 if (rc)
1346                         return rc;
1347         }
1348
1349         while (list != NULL) {
1350                 if (list->m_file != NULL) {
1351                         has_m_file = true;
1352                         llapi_layout_free(list->m_layout);
1353
1354                         list->m_layout =
1355                                 llapi_layout_get_by_path(list->m_file, 0);
1356                         if (list->m_layout == NULL) {
1357                                 fprintf(stderr,
1358                                         "error: %s: file '%s' has no layout\n",
1359                                         progname, list->m_file);
1360                                 return -ENODATA;
1361                         }
1362                 } else {
1363                         has_m_layout = true;
1364                         if (list->m_layout == NULL) {
1365                                 fprintf(stderr, "error: %s: no mirror layout\n",
1366                                         progname);
1367                                 return -EINVAL;
1368                         }
1369                 }
1370
1371                 rc = mirror_sanity_check_one(list->m_layout);
1372                 if (rc)
1373                         return rc;
1374
1375                 list = list->m_next;
1376         }
1377
1378         if (has_m_file && has_m_layout) {
1379                 fprintf(stderr,
1380                         "error: %s: -f <victim_file> option should not be specified with setstripe options\n",
1381                         progname);
1382                 return -EINVAL;
1383         }
1384
1385         return 0;
1386 }
1387
1388 static int mirror_set_flags(struct llapi_layout *layout, void *cbdata)
1389 {
1390         __u32 mirror_flags = *(__u32 *)cbdata;
1391         uint32_t flags;
1392         int rc;
1393
1394         rc = llapi_layout_comp_flags_get(layout, &flags);
1395         if (rc < 0)
1396                 return rc;
1397
1398         if (!flags) {
1399                 rc = llapi_layout_comp_flags_set(layout, mirror_flags);
1400                 if (rc)
1401                         return rc;
1402         }
1403
1404         return LLAPI_LAYOUT_ITER_CONT;
1405 }
1406
1407 /**
1408  * mirror_create() - Create a mirrored file.
1409  * @fname:        The file to be created.
1410  * @mirror_list:  A linked list that stores the mirror arguments.
1411  *
1412  * This function creates a mirrored file @fname with the mirror(s)
1413  * from @mirror_list.
1414  *
1415  * Return: 0 on success or a negative error code on failure.
1416  */
1417 static int mirror_create(char *fname, struct mirror_args *mirror_list)
1418 {
1419         struct llapi_layout *layout = NULL;
1420         struct mirror_args *cur_mirror = NULL;
1421         uint16_t mirror_count = 0;
1422         int i = 0;
1423         int rc = 0;
1424
1425         rc = mirror_create_sanity_check(NULL, mirror_list);
1426         if (rc)
1427                 return rc;
1428
1429         cur_mirror = mirror_list;
1430         while (cur_mirror != NULL) {
1431                 rc = llapi_layout_comp_iterate(cur_mirror->m_layout,
1432                                                mirror_set_flags,
1433                                                &cur_mirror->m_flags);
1434                 if (rc) {
1435                         rc = -errno;
1436                         fprintf(stderr, "%s: failed to set mirror flags\n",
1437                                 progname);
1438                         goto error;
1439                 }
1440
1441                 for (i = 0; i < cur_mirror->m_count; i++) {
1442                         rc = llapi_layout_merge(&layout, cur_mirror->m_layout);
1443                         if (rc) {
1444                                 rc = -errno;
1445                                 fprintf(stderr, "error: %s: "
1446                                         "merge layout failed: %s\n",
1447                                         progname, strerror(errno));
1448                                 goto error;
1449                         }
1450                 }
1451                 mirror_count += cur_mirror->m_count;
1452                 cur_mirror = cur_mirror->m_next;
1453         }
1454
1455         if (layout == NULL) {
1456                 fprintf(stderr, "error: %s: layout is NULL\n", progname);
1457                 return -EINVAL;
1458         }
1459
1460         rc = llapi_layout_mirror_count_set(layout, mirror_count);
1461         if (rc) {
1462                 rc = -errno;
1463                 fprintf(stderr, "error: %s: set mirror count failed: %s\n",
1464                         progname, strerror(errno));
1465                 goto error;
1466         }
1467
1468         rc = lfs_component_create(fname, O_CREAT | O_WRONLY, 0666,
1469                                   layout);
1470         if (rc >= 0) {
1471                 close(rc);
1472                 rc = 0;
1473         }
1474
1475 error:
1476         llapi_layout_free(layout);
1477         return rc;
1478 }
1479
1480 /**
1481  * Compare files and check lease on @fd.
1482  *
1483  * \retval bytes number of bytes are the same
1484  */
1485 static ssize_t mirror_file_compare(int fd, int fdv)
1486 {
1487         const size_t buflen = 4 * 1024 * 1024; /* 4M */
1488         void *buf;
1489         ssize_t bytes_done = 0;
1490         ssize_t bytes_read = 0;
1491
1492         buf = malloc(buflen * 2);
1493         if (!buf)
1494                 return -ENOMEM;
1495
1496         while (1) {
1497                 if (!llapi_lease_check(fd)) {
1498                         bytes_done = -EBUSY;
1499                         break;
1500                 }
1501
1502                 bytes_read = read(fd, buf, buflen);
1503                 if (bytes_read <= 0)
1504                         break;
1505
1506                 if (bytes_read != read(fdv, buf + buflen, buflen))
1507                         break;
1508
1509                 /* XXX: should compute the checksum on each buffer and then
1510                  * compare checksum to avoid cache collision */
1511                 if (memcmp(buf, buf + buflen, bytes_read))
1512                         break;
1513
1514                 bytes_done += bytes_read;
1515         }
1516
1517         free(buf);
1518
1519         return bytes_done;
1520 }
1521
1522 static int mirror_extend_file(const char *fname, const char *victim_file,
1523                               enum mirror_flags mirror_flags)
1524 {
1525         int fd = -1;
1526         int fdv = -1;
1527         struct stat stbuf;
1528         struct stat stbuf_v;
1529         struct ll_ioc_lease *data = NULL;
1530         int rc;
1531
1532         fd = open(fname, O_RDWR);
1533         if (fd < 0) {
1534                 error_loc = "open source file";
1535                 rc = -errno;
1536                 goto out;
1537         }
1538
1539         fdv = open(victim_file, O_RDWR);
1540         if (fdv < 0) {
1541                 error_loc = "open target file";
1542                 rc = -errno;
1543                 goto out;
1544         }
1545
1546         if (fstat(fd, &stbuf) || fstat(fdv, &stbuf_v)) {
1547                 error_loc = "stat source or target file";
1548                 rc = -errno;
1549                 goto out;
1550         }
1551
1552         if (stbuf.st_dev != stbuf_v.st_dev) {
1553                 error_loc = "stat source and target file";
1554                 rc = -EXDEV;
1555                 goto out;
1556         }
1557
1558         /* mirrors should be of the same size */
1559         if (stbuf.st_size != stbuf_v.st_size) {
1560                 error_loc = "file sizes don't match";
1561                 rc = -EINVAL;
1562                 goto out;
1563         }
1564
1565         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
1566         if (rc < 0) {
1567                 error_loc = "cannot get lease";
1568                 goto out;
1569         }
1570
1571         if (!(mirror_flags & MF_NO_VERIFY)) {
1572                 ssize_t ret;
1573                 /* mirrors should have the same contents */
1574                 ret = mirror_file_compare(fd, fdv);
1575                 if (ret != stbuf.st_size) {
1576                         error_loc = "file busy or contents don't match";
1577                         rc = ret < 0 ? ret : -EINVAL;
1578                         goto out;
1579                 }
1580         }
1581
1582         /* Get rid of caching pages from clients */
1583         rc = llapi_file_flush(fd);
1584         if (rc < 0) {
1585                 error_loc = "cannot get data version";
1586                 goto out;
1587         }
1588
1589         rc = llapi_file_flush(fdv);
1590         if (rc < 0) {
1591                 error_loc = "cannot get data version";
1592                 goto out;
1593
1594         }
1595
1596         /* Make sure we keep original atime/mtime values */
1597         rc = migrate_copy_timestamps(fd, fdv);
1598         if (rc < 0) {
1599                 error_loc = "cannot copy timestamp";
1600                 goto out;
1601         }
1602
1603         /* Atomically put lease, merge layouts and close. */
1604         data = calloc(1, offsetof(typeof(*data), lil_ids[1]));
1605         if (!data) {
1606                 error_loc = "memory allocation";
1607                 goto out;
1608         }
1609         data->lil_mode = LL_LEASE_UNLCK;
1610         data->lil_flags = LL_LEASE_LAYOUT_MERGE;
1611         data->lil_count = 1;
1612         data->lil_ids[0] = fdv;
1613         rc = llapi_lease_set(fd, data);
1614         if (rc < 0) {
1615                 error_loc = "cannot merge layout";
1616                 goto out;
1617         } else if (rc == 0) {
1618                 rc = -EBUSY;
1619                 error_loc = "lost lease lock";
1620                 goto out;
1621         }
1622         rc = 0;
1623
1624 out:
1625         if (data)
1626                 free(data);
1627         if (fd >= 0)
1628                 close(fd);
1629         if (fdv >= 0)
1630                 close(fdv);
1631         if (!rc)
1632                 (void) unlink(victim_file);
1633         if (rc < 0)
1634                 fprintf(stderr, "error: %s: %s: %s: %s\n",
1635                         progname, fname, error_loc, strerror(-rc));
1636         return rc;
1637 }
1638
1639 static int mirror_extend_layout(char *name, struct llapi_layout *layout)
1640 {
1641         struct ll_ioc_lease *data = NULL;
1642         int fd = -1;
1643         int fdv = -1;
1644         int rc;
1645
1646         rc = migrate_open_files(name, 0, NULL, layout, &fd, &fdv);
1647         if (rc < 0)
1648                 goto out;
1649
1650         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
1651         if (rc < 0) {
1652                 error_loc = "cannot get lease";
1653                 goto out;
1654         }
1655
1656         rc = migrate_nonblock(fd, fdv);
1657         if (rc < 0) {
1658                 llapi_lease_release(fd);
1659                 goto out;
1660         }
1661
1662         /* Atomically put lease, merge layouts and close. */
1663         data = calloc(1, offsetof(typeof(*data), lil_ids[1]));
1664         if (!data) {
1665                 error_loc = "memory allocation";
1666                 goto out;
1667         }
1668         data->lil_mode = LL_LEASE_UNLCK;
1669         data->lil_flags = LL_LEASE_LAYOUT_MERGE;
1670         data->lil_count = 1;
1671         data->lil_ids[0] = fdv;
1672         rc = llapi_lease_set(fd, data);
1673         if (rc < 0) {
1674                 error_loc = "cannot merge layout";
1675                 goto out;
1676         } else if (rc == 0) {
1677                 rc = -EBUSY;
1678                 error_loc = "lost lease lock";
1679                 goto out;
1680         }
1681         rc = 0;
1682
1683 out:
1684         if (data)
1685                 free(data);
1686         if (fd >= 0)
1687                 close(fd);
1688         if (fdv >= 0)
1689                 close(fdv);
1690         if (rc < 0)
1691                 fprintf(stderr, "error: %s: %s: %s: %s\n",
1692                         progname, name, error_loc, strerror(-rc));
1693         return rc;
1694 }
1695
1696 static int mirror_extend(char *fname, struct mirror_args *mirror_list,
1697                          enum mirror_flags mirror_flags)
1698 {
1699         int rc;
1700
1701         rc = mirror_create_sanity_check(fname, mirror_list);
1702         if (rc)
1703                 return rc;
1704
1705         while (mirror_list) {
1706                 if (mirror_list->m_file != NULL) {
1707                         rc = mirror_extend_file(fname, mirror_list->m_file,
1708                                                 mirror_flags);
1709                 } else {
1710                         __u32 mirror_count = mirror_list->m_count;
1711
1712                         while (mirror_count > 0) {
1713                                 rc = mirror_extend_layout(fname,
1714                                                         mirror_list->m_layout);
1715                                 if (rc)
1716                                         break;
1717
1718                                 --mirror_count;
1719                         }
1720                 }
1721                 if (rc)
1722                         break;
1723
1724                 mirror_list = mirror_list->m_next;
1725         }
1726
1727         return rc;
1728 }
1729
1730 static int find_mirror_id(struct llapi_layout *layout, void *cbdata)
1731 {
1732         uint32_t id;
1733         int rc;
1734
1735         rc = llapi_layout_mirror_id_get(layout, &id);
1736         if (rc < 0)
1737                 return rc;
1738
1739         if ((__u16)id == *(__u16 *)cbdata)
1740                 return LLAPI_LAYOUT_ITER_STOP;
1741
1742         return LLAPI_LAYOUT_ITER_CONT;
1743 }
1744
1745 static int find_comp_id(struct llapi_layout *layout, void *cbdata)
1746 {
1747         uint32_t id;
1748         int rc;
1749
1750         rc = llapi_layout_comp_id_get(layout, &id);
1751         if (rc < 0)
1752                 return rc;
1753
1754         if (id == *(__u32 *)cbdata)
1755                 return LLAPI_LAYOUT_ITER_STOP;
1756
1757         return LLAPI_LAYOUT_ITER_CONT;
1758 }
1759
1760 struct pool_to_id_cbdata {
1761         const char *pool;
1762         __u32 id;
1763 };
1764 static int find_comp_id_by_pool(struct llapi_layout *layout, void *cbdata)
1765 {
1766         char buf[LOV_MAXPOOLNAME + 1];
1767         struct pool_to_id_cbdata *d = (void *)cbdata;
1768         uint32_t id;
1769         int rc;
1770
1771         rc = llapi_layout_pool_name_get(layout, buf, sizeof(buf));
1772         if (rc < 0)
1773                 return rc;
1774         if (strcmp(d->pool, buf))
1775                 return LLAPI_LAYOUT_ITER_CONT;
1776
1777         rc = llapi_layout_mirror_id_get(layout, &id);
1778         if (rc < 0)
1779                 return rc;
1780         d->id = id;
1781
1782         return LLAPI_LAYOUT_ITER_STOP;
1783 }
1784
1785 struct collect_ids_data {
1786         __u16   *cid_ids;
1787         int     cid_count;
1788         __u16   cid_exclude;
1789 };
1790
1791 static int collect_mirror_id(struct llapi_layout *layout, void *cbdata)
1792 {
1793         struct collect_ids_data *cid = cbdata;
1794         uint32_t id;
1795         int rc;
1796
1797         rc = llapi_layout_mirror_id_get(layout, &id);
1798         if (rc < 0)
1799                 return rc;
1800
1801         if ((__u16)id != cid->cid_exclude) {
1802                 int i;
1803
1804                 for (i = 0; i < cid->cid_count; i++) {
1805                         /* already collected the mirror id */
1806                         if (id == cid->cid_ids[i])
1807                                 return LLAPI_LAYOUT_ITER_CONT;
1808                 }
1809                 cid->cid_ids[cid->cid_count] = id;
1810                 cid->cid_count++;
1811         }
1812
1813         return LLAPI_LAYOUT_ITER_CONT;
1814 }
1815
1816 /**
1817  * last_non_stale_mirror() - Check if a mirror is the last non-stale mirror.
1818  * @mirror_id: Mirror id to be checked.
1819  * @layout:    Mirror component list.
1820  *
1821  * This function checks if a mirror with specified @mirror_id is the last
1822  * non-stale mirror of a layout @layout.
1823  *
1824  * Return: true or false.
1825  */
1826 static inline
1827 bool last_non_stale_mirror(__u16 mirror_id, struct llapi_layout *layout)
1828 {
1829         __u16 mirror_ids[128] = { 0 };
1830         struct collect_ids_data cid = { .cid_ids = mirror_ids,
1831                                         .cid_count = 0,
1832                                         .cid_exclude = mirror_id, };
1833         int i;
1834
1835         llapi_layout_comp_iterate(layout, collect_mirror_id, &cid);
1836
1837         for (i = 0; i < cid.cid_count; i++) {
1838                 struct llapi_resync_comp comp_array[1024] = { { 0 } };
1839                 int comp_size = 0;
1840
1841                 comp_size = llapi_mirror_find_stale(layout, comp_array,
1842                                                     ARRAY_SIZE(comp_array),
1843                                                     &mirror_ids[i], 1);
1844                 if (comp_size == 0)
1845                         return false;
1846         }
1847
1848         return true;
1849 }
1850
1851 static int mirror_split(const char *fname, __u32 id, const char *pool,
1852                         enum mirror_flags mflags, const char *victim_file)
1853 {
1854         struct llapi_layout *layout;
1855         char parent[PATH_MAX];
1856         char victim[PATH_MAX];
1857         int flags = O_CREAT | O_EXCL | O_LOV_DELAY_CREATE | O_NOFOLLOW;
1858         char *ptr;
1859         struct ll_ioc_lease *data;
1860         uint16_t mirror_count;
1861         int mdt_index;
1862         int fd, fdv;
1863         int rc;
1864
1865         /* check fname contains mirror with mirror_id/comp_id */
1866         layout = llapi_layout_get_by_path(fname, 0);
1867         if (!layout) {
1868                 fprintf(stderr,
1869                         "error %s: file '%s' couldn't get layout\n",
1870                         progname, fname);
1871                 return -EINVAL;
1872         }
1873
1874         rc = mirror_sanity_check_one(layout);
1875         if (rc)
1876                 goto free_layout;
1877
1878         rc = llapi_layout_mirror_count_get(layout, &mirror_count);
1879         if (rc) {
1880                 fprintf(stderr,
1881                         "error %s: file '%s' couldn't get mirror count\n",
1882                         progname, fname);
1883                 goto free_layout;
1884         }
1885         if (mirror_count < 2) {
1886                 fprintf(stderr,
1887                         "error %s: file '%s' has %d component, cannot split\n",
1888                         progname, fname, mirror_count);
1889                 goto free_layout;
1890         }
1891
1892         if (mflags & MF_COMP_POOL) {
1893                 struct pool_to_id_cbdata data = { .pool = pool };
1894
1895                 rc = llapi_layout_comp_iterate(layout, find_comp_id_by_pool,
1896                                                &data);
1897                 id = data.id;
1898         } else if (mflags & MF_COMP_ID) {
1899                 rc = llapi_layout_comp_iterate(layout, find_comp_id, &id);
1900                 id = mirror_id_of(id);
1901         } else {
1902                 rc = llapi_layout_comp_iterate(layout, find_mirror_id, &id);
1903         }
1904         if (rc < 0) {
1905                 fprintf(stderr, "error %s: failed to iterate layout of '%s'\n",
1906                         progname, fname);
1907                 goto free_layout;
1908         } else if (rc == LLAPI_LAYOUT_ITER_CONT) {
1909                 fprintf(stderr,
1910                      "error %s: file '%s' does not contain mirror with id %u\n",
1911                         progname, fname, id);
1912                 goto free_layout;
1913         }
1914
1915         fd = open(fname, O_RDWR);
1916         if (fd < 0) {
1917                 fprintf(stderr,
1918                         "error %s: open file '%s' failed: %s\n",
1919                         progname, fname, strerror(errno));
1920                 goto free_layout;
1921         }
1922
1923         /* get victim file directory pathname */
1924         if (strlen(fname) > sizeof(parent) - 1) {
1925                 fprintf(stderr, "error %s: file name of '%s' too long\n",
1926                         progname, fname);
1927                 rc = -ERANGE;
1928                 goto close_fd;
1929         }
1930         strncpy(parent, fname, sizeof(parent));
1931         ptr = strrchr(parent, '/');
1932         if (ptr == NULL) {
1933                 if (getcwd(parent, sizeof(parent)) == NULL) {
1934                         fprintf(stderr, "error %s: getcwd failed: %s\n",
1935                                 progname, strerror(errno));
1936                         rc = -errno;
1937                         goto close_fd;
1938                 }
1939         } else {
1940                 if (ptr == parent)
1941                         ptr = parent + 1;
1942                 *ptr = '\0';
1943         }
1944
1945         rc = llapi_file_fget_mdtidx(fd, &mdt_index);
1946         if (rc < 0) {
1947                 fprintf(stderr, "%s: cannot get MDT index of '%s'\n",
1948                         progname, fname);
1949                 goto close_fd;
1950         }
1951
1952         if (victim_file == NULL) {
1953                 /* use a temp file to store the splitted layout */
1954                 if (mflags & MF_DESTROY) {
1955                         if (last_non_stale_mirror(id, layout)) {
1956                                 rc = -EUCLEAN;
1957                                 fprintf(stderr,
1958                                         "%s: cannot destroy the last non-stale mirror of file '%s'\n",
1959                                         progname, fname);
1960                                 goto close_fd;
1961                         }
1962
1963                         fdv = llapi_create_volatile_idx(parent, mdt_index,
1964                                                         O_LOV_DELAY_CREATE);
1965                 } else {
1966                         snprintf(victim, sizeof(victim), "%s.mirror~%u",
1967                                  fname, id);
1968                         fdv = open(victim, flags, S_IRUSR | S_IWUSR);
1969                 }
1970         } else {
1971                 /* user specified victim file */
1972                 fdv = open(victim_file, flags, S_IRUSR | S_IWUSR);
1973         }
1974
1975         if (fdv < 0) {
1976                 fprintf(stderr,
1977                         "error %s: create victim file failed: %s\n",
1978                         progname, strerror(errno));
1979                 goto close_fd;
1980         }
1981
1982         /* get lease lock of fname */
1983         rc = llapi_lease_acquire(fd, LL_LEASE_WRLCK);
1984         if (rc < 0) {
1985                 fprintf(stderr,
1986                         "error %s: cannot get lease of file '%s': %d\n",
1987                         progname, fname, rc);
1988                 goto close_victim;
1989         }
1990
1991         /* Atomatically put lease, split layouts and close. */
1992         data = malloc(offsetof(typeof(*data), lil_ids[2]));
1993         if (!data) {
1994                 rc = -ENOMEM;
1995                 goto close_victim;
1996         }
1997
1998         data->lil_mode = LL_LEASE_UNLCK;
1999         data->lil_flags = LL_LEASE_LAYOUT_SPLIT;
2000         data->lil_count = 2;
2001         data->lil_ids[0] = fdv;
2002         data->lil_ids[1] = id;
2003         rc = llapi_lease_set(fd, data);
2004         if (rc <= 0) {
2005                 if (rc == 0) /* lost lease lock */
2006                         rc = -EBUSY;
2007                 fprintf(stderr,
2008                         "error %s: cannot split '%s': %s\n",
2009                         progname, fname, strerror(-rc));
2010         } else {
2011                 rc = 0;
2012         }
2013         free(data);
2014
2015 close_victim:
2016         close(fdv);
2017 close_fd:
2018         close(fd);
2019 free_layout:
2020         llapi_layout_free(layout);
2021         return rc;
2022 }
2023
2024 /**
2025  * Parse a string containing an target index list into an array of integers.
2026  *
2027  * The input string contains a comma delimited list of individual
2028  * indices and ranges, for example "1,2-4,7". Add the indices into the
2029  * \a tgts array and remove duplicates.
2030  *
2031  * \param[out] tgts    array to store indices in
2032  * \param[in] size     size of \a tgts array
2033  * \param[in] offset   starting index in \a tgts
2034  * \param[in] arg      string containing OST index list
2035  *
2036  * \retval positive    number of indices in \a tgts
2037  * \retval -EINVAL     unable to parse \a arg
2038  */
2039 static int parse_targets(__u32 *tgts, int size, int offset, char *arg)
2040 {
2041         int rc;
2042         int nr = offset;
2043         int slots = size - offset;
2044         char *ptr = NULL;
2045         bool end_of_loop;
2046
2047         if (arg == NULL)
2048                 return -EINVAL;
2049
2050         end_of_loop = false;
2051         while (!end_of_loop) {
2052                 int start_index;
2053                 int end_index;
2054                 int i;
2055                 char *endptr = NULL;
2056
2057                 rc = -EINVAL;
2058
2059                 ptr = strchrnul(arg, ',');
2060
2061                 end_of_loop = *ptr == '\0';
2062                 *ptr = '\0';
2063
2064                 start_index = strtol(arg, &endptr, 0);
2065                 if (endptr == arg) /* no data at all */
2066                         break;
2067                 if (*endptr != '-' && *endptr != '\0') /* has invalid data */
2068                         break;
2069
2070                 end_index = start_index;
2071                 if (*endptr == '-') {
2072                         end_index = strtol(endptr + 1, &endptr, 0);
2073                         if (*endptr != '\0')
2074                                 break;
2075                         if (end_index < start_index)
2076                                 break;
2077                 }
2078
2079                 for (i = start_index; i <= end_index && slots > 0; i++) {
2080                         int j;
2081
2082                         /* remove duplicate */
2083                         for (j = 0; j < offset; j++) {
2084                                 if (tgts[j] == i)
2085                                         break;
2086                         }
2087                         if (j == offset) { /* no duplicate */
2088                                 tgts[nr++] = i;
2089                                 --slots;
2090                         }
2091                 }
2092                 if (slots == 0 && i < end_index)
2093                         break;
2094
2095                 *ptr = ',';
2096                 arg = ++ptr;
2097                 offset = nr;
2098                 rc = 0;
2099         }
2100         if (!end_of_loop && ptr != NULL)
2101                 *ptr = ',';
2102
2103         return rc < 0 ? rc : nr;
2104 }
2105
2106 struct lfs_setstripe_args {
2107         unsigned long long       lsa_comp_end;
2108         unsigned long long       lsa_stripe_size;
2109         long long                lsa_stripe_count;
2110         long long                lsa_stripe_off;
2111         __u32                    lsa_comp_flags;
2112         __u32                    lsa_comp_neg_flags;
2113         unsigned long long       lsa_pattern;
2114         unsigned int             lsa_mirror_count;
2115         int                      lsa_nr_tgts;
2116         bool                     lsa_first_comp;
2117         __u32                   *lsa_tgts;
2118         char                    *lsa_pool_name;
2119 };
2120
2121 static inline void setstripe_args_init(struct lfs_setstripe_args *lsa)
2122 {
2123         unsigned int mirror_count = lsa->lsa_mirror_count;
2124         bool first_comp = lsa->lsa_first_comp;
2125
2126         memset(lsa, 0, sizeof(*lsa));
2127
2128         lsa->lsa_stripe_size = LLAPI_LAYOUT_DEFAULT;
2129         lsa->lsa_stripe_count = LLAPI_LAYOUT_DEFAULT;
2130         lsa->lsa_stripe_off = LLAPI_LAYOUT_DEFAULT;
2131         lsa->lsa_pattern = LLAPI_LAYOUT_RAID0;
2132         lsa->lsa_pool_name = NULL;
2133
2134         lsa->lsa_mirror_count = mirror_count;
2135         lsa->lsa_first_comp = first_comp;
2136 }
2137
2138 /**
2139  * setstripe_args_init_inherit() - Initialize and inherit stripe options.
2140  * @lsa: Stripe options to be initialized and inherited.
2141  *
2142  * This function initializes stripe options in @lsa and inherit
2143  * stripe_size, stripe_count and OST pool_name options.
2144  *
2145  * Return: void.
2146  */
2147 static inline void setstripe_args_init_inherit(struct lfs_setstripe_args *lsa)
2148 {
2149         unsigned long long stripe_size;
2150         long long stripe_count;
2151         char *pool_name = NULL;
2152
2153         stripe_size = lsa->lsa_stripe_size;
2154         stripe_count = lsa->lsa_stripe_count;
2155         pool_name = lsa->lsa_pool_name;
2156
2157         setstripe_args_init(lsa);
2158
2159         lsa->lsa_stripe_size = stripe_size;
2160         lsa->lsa_stripe_count = stripe_count;
2161         lsa->lsa_pool_name = pool_name;
2162 }
2163
2164 static inline bool setstripe_args_specified(struct lfs_setstripe_args *lsa)
2165 {
2166         return (lsa->lsa_stripe_size != LLAPI_LAYOUT_DEFAULT ||
2167                 lsa->lsa_stripe_count != LLAPI_LAYOUT_DEFAULT ||
2168                 lsa->lsa_stripe_off != LLAPI_LAYOUT_DEFAULT ||
2169                 lsa->lsa_pattern != LLAPI_LAYOUT_RAID0 ||
2170                 lsa->lsa_comp_end != 0);
2171 }
2172
2173 /**
2174  * comp_args_to_layout() - Create or extend a composite layout.
2175  * @composite:       Pointer to the composite layout.
2176  * @lsa:             Stripe options for the new component.
2177  *
2178  * This function creates or extends a composite layout by adding a new
2179  * component with stripe options from @lsa.
2180  *
2181  * Return: 0 on success or an error code on failure.
2182  */
2183 static int comp_args_to_layout(struct llapi_layout **composite,
2184                                struct lfs_setstripe_args *lsa,
2185                                bool set_extent)
2186 {
2187         struct llapi_layout *layout = *composite;
2188         uint64_t prev_end = 0;
2189         int i = 0, rc;
2190
2191         if (layout == NULL) {
2192                 layout = llapi_layout_alloc();
2193                 if (layout == NULL) {
2194                         fprintf(stderr, "Alloc llapi_layout failed. %s\n",
2195                                 strerror(errno));
2196                         return -ENOMEM;
2197                 }
2198                 *composite = layout;
2199         } else {
2200                 uint64_t start;
2201
2202                 /* Get current component extent, current component
2203                  * must be the tail component. */
2204                 rc = llapi_layout_comp_extent_get(layout, &start, &prev_end);
2205                 if (rc) {
2206                         fprintf(stderr, "Get comp extent failed. %s\n",
2207                                 strerror(errno));
2208                         return rc;
2209                 }
2210
2211                 if (lsa->lsa_first_comp)
2212                         prev_end = 0;
2213
2214                 if (lsa->lsa_first_comp)
2215                         rc = llapi_layout_add_first_comp(layout);
2216                 else
2217                         rc = llapi_layout_comp_add(layout);
2218                 if (rc) {
2219                         fprintf(stderr, "Add component failed. %s\n",
2220                                 strerror(errno));
2221                         return rc;
2222                 }
2223         }
2224         /* reset lsa_first_comp */
2225         lsa->lsa_first_comp = false;
2226
2227         if (set_extent) {
2228                 rc = llapi_layout_comp_extent_set(layout, prev_end,
2229                                                   lsa->lsa_comp_end);
2230                 if (rc) {
2231                         fprintf(stderr, "Set extent [%lu, %llu) failed. %s\n",
2232                                 prev_end, lsa->lsa_comp_end, strerror(errno));
2233                         return rc;
2234                 }
2235         }
2236
2237         /* Data-on-MDT component setting */
2238         if (lsa->lsa_pattern == LLAPI_LAYOUT_MDT) {
2239                 /* In case of Data-on-MDT patterns the only extra option
2240                  * applicable is stripe size option. */
2241                 if (lsa->lsa_stripe_count != LLAPI_LAYOUT_DEFAULT) {
2242                         fprintf(stderr, "Option 'stripe-count' can't be "
2243                                 "specified with Data-on-MDT component: %lld\n",
2244                                 lsa->lsa_stripe_count);
2245                         return -EINVAL;
2246                 }
2247                 if (lsa->lsa_stripe_size != LLAPI_LAYOUT_DEFAULT) {
2248                         fprintf(stderr, "Option 'stripe-size' can't be "
2249                                 "specified with Data-on-MDT component: %llu\n",
2250                                 lsa->lsa_stripe_size);
2251                         return -EINVAL;
2252                 }
2253                 if (lsa->lsa_nr_tgts != 0) {
2254                         fprintf(stderr, "Option 'ost-list' can't be specified "
2255                                 "with Data-on-MDT component: '%i'\n",
2256                                 lsa->lsa_nr_tgts);
2257                         return -EINVAL;
2258                 }
2259                 if (lsa->lsa_stripe_off != LLAPI_LAYOUT_DEFAULT) {
2260                         fprintf(stderr, "Option 'stripe-offset' can't be "
2261                                 "specified with Data-on-MDT component: %lld\n",
2262                                 lsa->lsa_stripe_off);
2263                         return -EINVAL;
2264                 }
2265                 if (lsa->lsa_pool_name != 0) {
2266                         fprintf(stderr, "Option 'pool' can't be specified "
2267                                 "with Data-on-MDT component: '%s'\n",
2268                                 lsa->lsa_pool_name);
2269                         return -EINVAL;
2270                 }
2271
2272                 rc = llapi_layout_pattern_set(layout, lsa->lsa_pattern);
2273                 if (rc) {
2274                         fprintf(stderr, "Set stripe pattern %#llx failed. %s\n",
2275                                 lsa->lsa_pattern,
2276                                 strerror(errno));
2277                         return rc;
2278                 }
2279                 /* Data-on-MDT component has always single stripe up to end */
2280                 lsa->lsa_stripe_size = lsa->lsa_comp_end;
2281         }
2282
2283         rc = llapi_layout_stripe_size_set(layout, lsa->lsa_stripe_size);
2284         if (rc) {
2285                 fprintf(stderr, "Set stripe size %llu failed: %s\n",
2286                         lsa->lsa_stripe_size, strerror(errno));
2287                 return rc;
2288         }
2289
2290         rc = llapi_layout_stripe_count_set(layout, lsa->lsa_stripe_count);
2291         if (rc) {
2292                 fprintf(stderr, "Set stripe count %lld failed: %s\n",
2293                         lsa->lsa_stripe_count, strerror(errno));
2294                 return rc;
2295         }
2296
2297         rc = llapi_layout_comp_flags_set(layout, lsa->lsa_comp_flags);
2298         if (rc) {
2299                 fprintf(stderr, "Set flags 0x%x failed: %s\n",
2300                         lsa->lsa_comp_flags, strerror(errno));
2301                 return rc;
2302         }
2303
2304         if (lsa->lsa_pool_name != NULL) {
2305                 rc = llapi_layout_pool_name_set(layout, lsa->lsa_pool_name);
2306                 if (rc) {
2307                         fprintf(stderr, "Set pool name: %s failed. %s\n",
2308                                 lsa->lsa_pool_name, strerror(errno));
2309                         return rc;
2310                 }
2311         } else {
2312                 rc = llapi_layout_pool_name_set(layout, "");
2313                 if (rc) {
2314                         fprintf(stderr, "Clear pool name failed: %s\n",
2315                                 strerror(errno));
2316                         return rc;
2317                 }
2318         }
2319
2320         if (lsa->lsa_nr_tgts > 0) {
2321                 if (lsa->lsa_stripe_count > 0 &&
2322                     lsa->lsa_stripe_count != LLAPI_LAYOUT_DEFAULT &&
2323                     lsa->lsa_stripe_count != LLAPI_LAYOUT_WIDE &&
2324                     lsa->lsa_nr_tgts != lsa->lsa_stripe_count) {
2325                         fprintf(stderr, "stripe_count(%lld) != nr_tgts(%d)\n",
2326                                 lsa->lsa_stripe_count,
2327                                 lsa->lsa_nr_tgts);
2328                         return -EINVAL;
2329                 }
2330                 for (i = 0; i < lsa->lsa_nr_tgts; i++) {
2331                         rc = llapi_layout_ost_index_set(layout, i,
2332                                                         lsa->lsa_tgts[i]);
2333                         if (rc)
2334                                 break;
2335                 }
2336         } else if (lsa->lsa_stripe_off != LLAPI_LAYOUT_DEFAULT &&
2337                    lsa->lsa_stripe_off != -1) {
2338                 rc = llapi_layout_ost_index_set(layout, 0, lsa->lsa_stripe_off);
2339         }
2340         if (rc) {
2341                 fprintf(stderr, "Set ost index %d failed. %s\n",
2342                         i, strerror(errno));
2343                 return rc;
2344         }
2345
2346         return 0;
2347 }
2348
2349 static int build_component(struct llapi_layout **layout,
2350                            struct lfs_setstripe_args *lsa, bool set_extent)
2351 {
2352         int rc;
2353
2354         rc = comp_args_to_layout(layout, lsa, set_extent);
2355         if (rc)
2356                 return rc;
2357
2358         if (lsa->lsa_mirror_count > 0) {
2359                 rc = llapi_layout_mirror_count_set(*layout,
2360                                                    lsa->lsa_mirror_count);
2361                 if (rc)
2362                         return rc;
2363
2364                 rc = llapi_layout_flags_set(*layout, LCM_FL_RDONLY);
2365                 if (rc)
2366                         return rc;
2367                 lsa->lsa_mirror_count = 0;
2368         }
2369
2370         return rc;
2371 }
2372
2373 static int build_layout_from_yaml_node(struct cYAML *node,
2374                                        struct llapi_layout **layout,
2375                                        struct lfs_setstripe_args *lsa,
2376                                        __u32 *osts)
2377 {
2378         char *string;
2379         int rc = 0;
2380
2381         while (node) {
2382                 if (node->cy_type == CYAML_TYPE_OBJECT) {
2383                         /* go deep to sub blocks */
2384                         rc = build_layout_from_yaml_node(node->cy_child, layout,
2385                                                          lsa, osts);
2386                         if (rc)
2387                                 return rc;
2388                 } else {
2389                         if (node->cy_string == NULL)
2390                                 return -EINVAL;
2391
2392                         string = node->cy_string;
2393                         /* skip leading lmm_ if present, to simplify parsing */
2394                         if (strncmp(string, "lmm_", 4) == 0)
2395                                 string += 4;
2396
2397                         if (node->cy_type == CYAML_TYPE_STRING) {
2398                                 if (!strcmp(string, "lcme_extent.e_end")) {
2399                                         if (!strcmp(node->cy_valuestring, "EOF") ||
2400                                             !strcmp(node->cy_valuestring, "eof"))
2401                                                 lsa->lsa_comp_end = LUSTRE_EOF;
2402                                 } else if (!strcmp(string, "pool")) {
2403                                         lsa->lsa_pool_name = node->cy_valuestring;
2404                                 } else if (!strcmp(string, "pattern")) {
2405                                         if (!strcmp(node->cy_valuestring, "mdt"))
2406                                                 lsa->lsa_pattern = LLAPI_LAYOUT_MDT;
2407                                 } else if (!strcmp(string, "lcme_flags")) {
2408                                         rc = comp_str2flags(node->cy_valuestring,
2409                                                             &lsa->lsa_comp_flags,
2410                                                             &lsa->lsa_comp_neg_flags);
2411                                         if (rc)
2412                                                 return rc;
2413                                         /* Only template flags have meaning in
2414                                          * the layout for a new file
2415                                          */
2416                                         lsa->lsa_comp_flags &= LCME_TEMPLATE_FLAGS;
2417                                 }
2418                         } else if (node->cy_type == CYAML_TYPE_NUMBER) {
2419                                 if (!strcmp(string, "lcm_mirror_count")) {
2420                                         lsa->lsa_mirror_count = node->cy_valueint;
2421                                 } else if (!strcmp(string, "lcme_extent.e_start")) {
2422                                         if (node->cy_valueint != 0 || *layout != NULL) {
2423                                                 rc = build_component(layout, lsa, true);
2424                                                 if (rc)
2425                                                         return rc;
2426                                         }
2427
2428                                         if (node->cy_valueint == 0)
2429                                                 lsa->lsa_first_comp = true;
2430
2431                                         /* initialize lsa */
2432                                         setstripe_args_init(lsa);
2433                                         lsa->lsa_tgts = osts;
2434                                 } else if (!strcmp(string, "lcme_extent.e_end")) {
2435                                         if (node->cy_valueint == -1)
2436                                                 lsa->lsa_comp_end = LUSTRE_EOF;
2437                                         else
2438                                                 lsa->lsa_comp_end = node->cy_valueint;
2439                                 } else if (!strcmp(string, "stripe_count")) {
2440                                         lsa->lsa_stripe_count = node->cy_valueint;
2441                                 } else if (!strcmp(string, "stripe_size")) {
2442                                         lsa->lsa_stripe_size = node->cy_valueint;
2443                                 } else if (!strcmp(string, "stripe_offset")) {
2444                                         lsa->lsa_stripe_off = node->cy_valueint;
2445                                 } else if (!strcmp(string, "l_ost_idx")) {
2446                                         osts[lsa->lsa_nr_tgts] = node->cy_valueint;
2447                                         lsa->lsa_nr_tgts++;
2448                                 }
2449                         }
2450                 }
2451                 node = node->cy_next;
2452         }
2453
2454         return rc;
2455 }
2456
2457 static int lfs_comp_create_from_yaml(char *template,
2458                                      struct llapi_layout **layout,
2459                                      struct lfs_setstripe_args *lsa,
2460                                      __u32 *osts)
2461 {
2462         struct cYAML *tree = NULL, *err_rc = NULL;
2463         int rc = 0;
2464
2465         tree = cYAML_build_tree(template, NULL, 0, &err_rc, false);
2466         if (!tree) {
2467                 fprintf(stderr, "%s: cannot parse YAML file %s\n",
2468                         progname, template);
2469                 cYAML_build_error(-EINVAL, -1, "yaml", "from comp yaml",
2470                                   "can't parse", &err_rc);
2471                 cYAML_print_tree2file(stderr, err_rc);
2472                 cYAML_free_tree(err_rc);
2473                 rc = -EINVAL;
2474                 goto err;
2475         }
2476
2477         /* initialize lsa for plain file */
2478         setstripe_args_init(lsa);
2479         lsa->lsa_tgts = osts;
2480
2481         rc = build_layout_from_yaml_node(tree, layout, lsa, osts);
2482         if (rc) {
2483                 fprintf(stderr, "%s: cannot build layout from YAML file %s.\n",
2484                         progname, template);
2485                 goto err;
2486         } else {
2487                 rc = build_component(layout, lsa, *layout != NULL);
2488         }
2489         /* clean clean lsa */
2490         setstripe_args_init(lsa);
2491
2492 err:
2493         if (tree)
2494                 cYAML_free_tree(tree);
2495         return rc;
2496 }
2497
2498 /* In 'lfs setstripe --component-add' mode, we need to fetch the extent
2499  * end of the last component in the existing file, and adjust the
2500  * first extent start of the components to be added accordingly. */
2501 static int adjust_first_extent(char *fname, struct llapi_layout *layout)
2502 {
2503         struct llapi_layout *head;
2504         uint64_t start, end, stripe_size, prev_end = 0;
2505         int rc;
2506
2507         if (layout == NULL) {
2508                 fprintf(stderr,
2509                         "%s setstripe: layout must be specified\n",
2510                         progname);
2511                 return -EINVAL;
2512         }
2513
2514         errno = 0;
2515         head = llapi_layout_get_by_path(fname, 0);
2516         if (head == NULL) {
2517                 fprintf(stderr,
2518                         "%s setstripe: cannot read layout from '%s': %s\n",
2519                         progname, fname, strerror(errno));
2520                 return -EINVAL;
2521         } else if (errno == ENODATA) {
2522                 /* file without LOVEA, this component-add will be turned
2523                  * into a component-create. */
2524                 llapi_layout_free(head);
2525                 return -ENODATA;
2526         } else if (!llapi_layout_is_composite(head)) {
2527                 fprintf(stderr, "%s setstripe: '%s' not a composite file\n",
2528                         progname, fname);
2529                 llapi_layout_free(head);
2530                 return -EINVAL;
2531         }
2532
2533         rc = llapi_layout_comp_extent_get(head, &start, &prev_end);
2534         if (rc) {
2535                 fprintf(stderr, "%s setstripe: cannot get prev extent: %s\n",
2536                         progname, strerror(errno));
2537                 llapi_layout_free(head);
2538                 return rc;
2539         }
2540
2541         llapi_layout_free(head);
2542
2543         /* Make sure we use the first component of the layout to be added. */
2544         rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_FIRST);
2545         if (rc < 0) {
2546                 fprintf(stderr,
2547                         "%s setstripe: cannot move component cursor: %s\n",
2548                         progname, strerror(errno));
2549                 return rc;
2550         }
2551
2552         rc = llapi_layout_comp_extent_get(layout, &start, &end);
2553         if (rc) {
2554                 fprintf(stderr, "%s setstripe: cannot get extent: %s\n",
2555                         progname, strerror(errno));
2556                 return rc;
2557         }
2558
2559         if (start > prev_end || end <= prev_end) {
2560                 fprintf(stderr,
2561                         "%s setstripe: first extent [%lu, %lu) not adjacent with extent end %lu\n",
2562                         progname, start, end, prev_end);
2563                 return -EINVAL;
2564         }
2565
2566         rc = llapi_layout_stripe_size_get(layout, &stripe_size);
2567         if (rc) {
2568                 fprintf(stderr, "%s setstripe: cannot get stripe size: %s\n",
2569                         progname, strerror(errno));
2570                 return rc;
2571         }
2572
2573         if (stripe_size != LLAPI_LAYOUT_DEFAULT &&
2574             (prev_end & (stripe_size - 1))) {
2575                 fprintf(stderr,
2576                         "%s setstripe: stripe size %lu not aligned with %lu\n",
2577                         progname, stripe_size, prev_end);
2578                 return -EINVAL;
2579         }
2580
2581         rc = llapi_layout_comp_extent_set(layout, prev_end, end);
2582         if (rc) {
2583                 fprintf(stderr,
2584                         "%s setstripe: cannot set component extent [%lu, %lu): %s\n",
2585                         progname, prev_end, end, strerror(errno));
2586                 return rc;
2587         }
2588
2589         return 0;
2590 }
2591
2592 static inline bool arg_is_eof(char *arg)
2593 {
2594         return !strncmp(arg, "-1", strlen("-1")) ||
2595                !strncmp(arg, "EOF", strlen("EOF")) ||
2596                !strncmp(arg, "eof", strlen("eof"));
2597 }
2598
2599 /**
2600  * lfs_mirror_alloc() - Allocate a mirror argument structure.
2601  *
2602  * Return: Valid mirror_args pointer on success and
2603  *         NULL if memory allocation fails.
2604  */
2605 static struct mirror_args *lfs_mirror_alloc(void)
2606 {
2607         struct mirror_args *mirror = NULL;
2608
2609         while (1) {
2610                 mirror = calloc(1, sizeof(*mirror));
2611                 if (mirror != NULL)
2612                         break;
2613
2614                 sleep(1);
2615         }
2616
2617         return mirror;
2618 }
2619
2620 /**
2621  * lfs_mirror_free() - Free memory allocated for a mirror argument
2622  *                     structure.
2623  * @mirror: Previously allocated mirror argument structure by
2624  *          lfs_mirror_alloc().
2625  *
2626  * Free memory allocated for @mirror.
2627  *
2628  * Return: void.
2629  */
2630 static void lfs_mirror_free(struct mirror_args *mirror)
2631 {
2632         if (mirror->m_layout != NULL)
2633                 llapi_layout_free(mirror->m_layout);
2634         free(mirror);
2635 }
2636
2637 /**
2638  * lfs_mirror_list_free() - Free memory allocated for a mirror list.
2639  * @mirror_list: Previously allocated mirror list.
2640  *
2641  * Free memory allocated for @mirror_list.
2642  *
2643  * Return: void.
2644  */
2645 static void lfs_mirror_list_free(struct mirror_args *mirror_list)
2646 {
2647         struct mirror_args *next_mirror = NULL;
2648
2649         while (mirror_list != NULL) {
2650                 next_mirror = mirror_list->m_next;
2651                 lfs_mirror_free(mirror_list);
2652                 mirror_list = next_mirror;
2653         }
2654 }
2655
2656 enum {
2657         LFS_POOL_OPT = 3,
2658         LFS_COMP_COUNT_OPT,
2659         LFS_COMP_START_OPT,
2660         LFS_COMP_FLAGS_OPT,
2661         LFS_COMP_DEL_OPT,
2662         LFS_COMP_SET_OPT,
2663         LFS_COMP_ADD_OPT,
2664         LFS_COMP_NO_VERIFY_OPT,
2665         LFS_PROJID_OPT,
2666         LFS_MIRROR_FLAGS_OPT,
2667         LFS_MIRROR_ID_OPT,
2668         LFS_MIRROR_STATE_OPT,
2669         LFS_LAYOUT_COPY,
2670         LFS_MIRROR_INDEX_OPT,
2671 };
2672
2673 /* functions */
2674 static int lfs_setstripe_internal(int argc, char **argv,
2675                                   enum setstripe_origin opc)
2676 {
2677         struct lfs_setstripe_args        lsa = { 0 };
2678         struct llapi_stripe_param       *param = NULL;
2679         struct find_param                migrate_mdt_param = {
2680                 .fp_max_depth = -1,
2681                 .fp_mdt_index = -1,
2682         };
2683         char                            *fname;
2684         int                              result = 0;
2685         int                              result2 = 0;
2686         char                            *end;
2687         int                              c;
2688         int                              delete = 0;
2689         unsigned long long               size_units = 1;
2690         bool                             migrate_mode = false;
2691         bool                             migrate_mdt_mode = false;
2692         bool                             migration_block = false;
2693         __u64                            migration_flags = 0;
2694         __u32                            tgts[LOV_MAX_STRIPE_COUNT] = { 0 };
2695         int                              comp_del = 0, comp_set = 0;
2696         int                              comp_add = 0;
2697         __u32                            comp_id = 0;
2698         struct llapi_layout             *layout = NULL;
2699         struct llapi_layout             **lpp = &layout;
2700         bool                             mirror_mode = false;
2701         bool                             has_m_file = false;
2702         __u32                            mirror_count = 0;
2703         enum mirror_flags                mirror_flags = 0;
2704         struct mirror_args              *mirror_list = NULL;
2705         struct mirror_args              *new_mirror = NULL;
2706         struct mirror_args              *last_mirror = NULL;
2707         __u16                            mirror_id = 0;
2708         char                             cmd[PATH_MAX];
2709         bool from_yaml = false;
2710         bool from_copy = false;
2711         char *template = NULL;
2712
2713         struct option long_opts[] = {
2714 /* find { .val = '0',   .name = "null",         .has_arg = no_argument }, */
2715 /* find { .val = 'A',   .name = "atime",        .has_arg = required_argument }*/
2716         /* --block is only valid in migrate mode */
2717         { .val = 'b',   .name = "block",        .has_arg = no_argument },
2718         { .val = LFS_COMP_ADD_OPT,
2719                         .name = "comp-add",     .has_arg = no_argument },
2720         { .val = LFS_COMP_ADD_OPT,
2721                         .name = "component-add", .has_arg = no_argument },
2722         { .val = LFS_COMP_DEL_OPT,
2723                         .name = "comp-del",     .has_arg = no_argument },
2724         { .val = LFS_COMP_DEL_OPT,
2725                         .name = "component-del", .has_arg = no_argument },
2726         { .val = LFS_COMP_FLAGS_OPT,
2727                         .name = "comp-flags",   .has_arg = required_argument },
2728         { .val = LFS_COMP_FLAGS_OPT,
2729                         .name = "component-flags",
2730                                                 .has_arg = required_argument },
2731         { .val = LFS_COMP_SET_OPT,
2732                         .name = "comp-set",     .has_arg = no_argument },
2733         { .val = LFS_COMP_SET_OPT,
2734                         .name = "component-set",
2735                                                 .has_arg = no_argument},
2736         { .val = LFS_COMP_NO_VERIFY_OPT,
2737                         .name = "no-verify",    .has_arg = no_argument},
2738         { .val = LFS_MIRROR_FLAGS_OPT,
2739                         .name = "flags",        .has_arg = required_argument},
2740         { .val = LFS_MIRROR_ID_OPT,
2741                         .name = "mirror-id",    .has_arg = required_argument},
2742         { .val = LFS_LAYOUT_COPY,
2743                         .name = "copy",         .has_arg = required_argument},
2744         { .val = 'c',   .name = "stripe-count", .has_arg = required_argument},
2745         { .val = 'c',   .name = "stripe_count", .has_arg = required_argument},
2746         { .val = 'c',   .name = "mdt-count",    .has_arg = required_argument},
2747 /* find { .val = 'C',   .name = "ctime",        .has_arg = required_argument }*/
2748         { .val = 'd',   .name = "delete",       .has_arg = no_argument},
2749         { .val = 'd',   .name = "destroy",      .has_arg = no_argument},
2750         /* --non-direct is only valid in migrate mode */
2751         { .val = 'D',   .name = "non-direct",   .has_arg = no_argument },
2752         { .val = 'E',   .name = "comp-end",     .has_arg = required_argument},
2753         { .val = 'E',   .name = "component-end",
2754                                                 .has_arg = required_argument},
2755         { .val = 'f',   .name = "file",         .has_arg = required_argument },
2756 /* find { .val = 'F',   .name = "fid",          .has_arg = no_argument }, */
2757 /* find { .val = 'g',   .name = "gid",          .has_arg = no_argument }, */
2758 /* find { .val = 'G',   .name = "group",        .has_arg = required_argument }*/
2759 /* find { .val = 'h',   .name = "help",         .has_arg = no_argument }, */
2760         { .val = 'H',   .name = "mdt-hash",     .has_arg = required_argument},
2761         { .val = 'i',   .name = "stripe-index", .has_arg = required_argument},
2762         { .val = 'i',   .name = "stripe_index", .has_arg = required_argument},
2763         { .val = 'I',   .name = "comp-id",      .has_arg = required_argument},
2764         { .val = 'I',   .name = "component-id", .has_arg = required_argument},
2765 /* find { .val = 'l',   .name = "lazy",         .has_arg = no_argument }, */
2766         { .val = 'L',   .name = "layout",       .has_arg = required_argument },
2767         { .val = 'm',   .name = "mdt",          .has_arg = required_argument},
2768         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument},
2769         { .val = 'm',   .name = "mdt_index",    .has_arg = required_argument},
2770         /* --non-block is only valid in migrate mode */
2771         { .val = 'n',   .name = "non-block",    .has_arg = no_argument },
2772         { .val = 'N',   .name = "mirror-count", .has_arg = optional_argument},
2773         { .val = 'o',   .name = "ost",          .has_arg = required_argument },
2774 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
2775         { .val = 'o',   .name = "ost-list",     .has_arg = required_argument },
2776         { .val = 'o',   .name = "ost_list",     .has_arg = required_argument },
2777 #endif
2778         { .val = 'p',   .name = "pool",         .has_arg = required_argument },
2779 /* find { .val = 'P',   .name = "print",        .has_arg = no_argument }, */
2780 /* getstripe { .val = 'q', .name = "quiet",     .has_arg = no_argument }, */
2781 /* getstripe { .val = 'r', .name = "recursive", .has_arg = no_argument }, */
2782 /* getstripe { .val = 'R', .name = "raw",       .has_arg = no_argument }, */
2783         { .val = 'S',   .name = "stripe-size",  .has_arg = required_argument },
2784         { .val = 'S',   .name = "stripe_size",  .has_arg = required_argument },
2785 /* find { .val = 't',   .name = "type",         .has_arg = required_argument }*/
2786 /* dirstripe { .val = 'T', .name = "mdt-count", .has_arg = required_argument }*/
2787 /* find { .val = 'u',   .name = "uid",          .has_arg = required_argument }*/
2788 /* find { .val = 'U',   .name = "user",         .has_arg = required_argument }*/
2789         /* --verbose is only valid in migrate mode */
2790         { .val = 'v',   .name = "verbose",      .has_arg = no_argument},
2791         { .val = 'y',   .name = "yaml",         .has_arg = required_argument },
2792         { .name = NULL } };
2793
2794         setstripe_args_init(&lsa);
2795
2796         migrate_mode = (opc == SO_MIGRATE);
2797         mirror_mode = (opc == SO_MIRROR_CREATE || opc == SO_MIRROR_EXTEND);
2798
2799         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
2800         progname = cmd;
2801         while ((c = getopt_long(argc, argv,
2802                                 "bc:dDE:f:H:i:I:m:N::no:p:L:s:S:vy:", long_opts,
2803                                 NULL)) >= 0) {
2804                 switch (c) {
2805                 case 0:
2806                         /* Long options. */
2807                         break;
2808                 case LFS_COMP_ADD_OPT:
2809                         comp_add = 1;
2810                         break;
2811                 case LFS_COMP_DEL_OPT:
2812                         comp_del = 1;
2813                         break;
2814                 case LFS_COMP_FLAGS_OPT:
2815                         result = comp_str2flags(optarg, &lsa.lsa_comp_flags,
2816                                                 &lsa.lsa_comp_neg_flags);
2817                         if (result != 0)
2818                                 goto usage_error;
2819                         if (mirror_mode && lsa.lsa_comp_neg_flags) {
2820                                 fprintf(stderr, "%s: inverted flags are not supported\n",
2821                                         progname);
2822                                 goto usage_error;
2823                         }
2824                         if (lsa.lsa_comp_neg_flags & LCME_FL_STALE) {
2825                                 fprintf(stderr,
2826                                         "%s: cannot clear 'stale' flags from component. Please use lfs-mirror-resync(1) instead\n",
2827                                         progname);
2828                                 result = -EINVAL;
2829                                 goto error;
2830                         }
2831
2832                         break;
2833                 case LFS_COMP_SET_OPT:
2834                         comp_set = 1;
2835                         break;
2836                 case LFS_COMP_NO_VERIFY_OPT:
2837                         mirror_flags |= MF_NO_VERIFY;
2838                         break;
2839                 case LFS_MIRROR_ID_OPT:
2840                         mirror_id = strtoul(optarg, &end, 0);
2841                         if (*end != '\0' || mirror_id == 0) {
2842                                 fprintf(stderr,
2843                                         "%s %s: invalid mirror ID '%s'\n",
2844                                         progname, argv[0], optarg);
2845                                 goto usage_error;
2846                         }
2847                         break;
2848                 case LFS_MIRROR_FLAGS_OPT: {
2849                         __u32 flags;
2850
2851                         if (!mirror_mode || !last_mirror) {
2852                                 fprintf(stderr, "error: %s: --flags must be specified with --mirror-count|-N option\n",
2853                                         progname);
2854                                 goto usage_error;
2855                         }
2856
2857                         result = comp_str2flags(optarg, &last_mirror->m_flags,
2858                                                 &flags);
2859                         if (result != 0)
2860                                 goto usage_error;
2861
2862                         if (flags) {
2863                                 fprintf(stderr, "%s: inverted flags are not supported\n",
2864                                         progname);
2865                                 result = -EINVAL;
2866                                 goto usage_error;
2867                         }
2868                         if (last_mirror->m_flags & ~LCME_USER_FLAGS) {
2869                                 fprintf(stderr,
2870                                         "%s: unsupported mirror flags: %s\n",
2871                                         progname, optarg);
2872                                 result = -EINVAL;
2873                                 goto error;
2874                         }
2875                         break;
2876                 }
2877                 case LFS_LAYOUT_COPY:
2878                         from_copy = true;
2879                         template = optarg;
2880                         break;
2881                 case 'b':
2882                         if (!migrate_mode) {
2883                                 fprintf(stderr,
2884                                         "%s %s: -b|--block valid only for migrate command\n",
2885                                         progname, argv[0]);
2886                                 goto usage_error;
2887                         }
2888                         migration_block = true;
2889                         break;
2890                 case 'c':
2891                         lsa.lsa_stripe_count = strtoul(optarg, &end, 0);
2892                         if (*end != '\0') {
2893                                 fprintf(stderr,
2894                                         "%s %s: invalid stripe count '%s'\n",
2895                                         progname, argv[0], optarg);
2896                                 goto usage_error;
2897                         }
2898
2899                         if (lsa.lsa_stripe_count == -1)
2900                                 lsa.lsa_stripe_count = LLAPI_LAYOUT_WIDE;
2901                         break;
2902                 case 'd':
2903                         /* delete the default striping pattern */
2904                         delete = 1;
2905                         if (opc == SO_MIRROR_SPLIT) {
2906                                 if (has_m_file) {
2907                                         fprintf(stderr,
2908                                               "%s %s: -d cannot used with -f\n",
2909                                                 progname, argv[0]);
2910                                         goto usage_error;
2911                                 }
2912                                 mirror_flags |= MF_DESTROY;
2913                         }
2914                         break;
2915                 case 'D':
2916                         if (!migrate_mode) {
2917                                 fprintf(stderr,
2918                                         "%s %s: -D|--non-direct is valid "
2919                                         "only for migrate command\n",
2920                                         progname, argv[0]);
2921                                 goto usage_error;
2922                         }
2923                         migration_flags |= MIGRATION_NONDIRECT;
2924                         break;
2925                 case 'E':
2926                         if (lsa.lsa_comp_end != 0) {
2927                                 result = comp_args_to_layout(lpp, &lsa, true);
2928                                 if (result) {
2929                                         fprintf(stderr,
2930                                                 "%s %s: invalid layout\n",
2931                                                 progname, argv[0]);
2932                                         goto usage_error;
2933                                 }
2934
2935                                 setstripe_args_init_inherit(&lsa);
2936                         }
2937
2938                         if (arg_is_eof(optarg)) {
2939                                 lsa.lsa_comp_end = LUSTRE_EOF;
2940                         } else {
2941                                 result = llapi_parse_size(optarg,
2942                                                         &lsa.lsa_comp_end,
2943                                                         &size_units, 0);
2944                                 if (result) {
2945                                         fprintf(stderr,
2946                                                 "%s %s: invalid component end '%s'\n",
2947                                                 progname, argv[0], optarg);
2948                                         goto usage_error;
2949                                 }
2950                         }
2951                         break;
2952                 case 'H':
2953                         if (!migrate_mode) {
2954                                 fprintf(stderr, "--mdt-hash is valid only for migrate command\n");
2955                                 return CMD_HELP;
2956                         }
2957
2958                         lsa.lsa_pattern = check_hashtype(optarg);
2959                         if (lsa.lsa_pattern == 0) {
2960                                 fprintf(stderr,
2961                                         "%s %s: bad stripe hash type '%s'\n",
2962                                         progname, argv[0], optarg);
2963                                 return CMD_HELP;
2964                         }
2965                         break;
2966                 case 'i':
2967                         lsa.lsa_stripe_off = strtol(optarg, &end, 0);
2968                         if (*end != '\0') {
2969                                 fprintf(stderr,
2970                                         "%s %s: invalid stripe offset '%s'\n",
2971                                         progname, argv[0], optarg);
2972                                 goto usage_error;
2973                         }
2974                         if (lsa.lsa_stripe_off == -1)
2975                                 lsa.lsa_stripe_off = LLAPI_LAYOUT_DEFAULT;
2976                         break;
2977                 case 'I':
2978                         comp_id = strtoul(optarg, &end, 0);
2979                         if (*end != '\0' || comp_id == 0 ||
2980                             comp_id > LCME_ID_MAX) {
2981                                 fprintf(stderr,
2982                                         "%s %s: invalid component ID '%s'\n",
2983                                         progname, argv[0], optarg);
2984                                 goto usage_error;
2985                         }
2986                         break;
2987                 case 'f':
2988                         if (opc != SO_MIRROR_EXTEND && opc != SO_MIRROR_SPLIT) {
2989                                 fprintf(stderr,
2990                                         "error: %s: invalid option: %s\n",
2991                                         progname, argv[optopt + 1]);
2992                                 goto usage_error;
2993                         }
2994                         if (opc == SO_MIRROR_EXTEND) {
2995                                 if (last_mirror == NULL) {
2996                                         fprintf(stderr,
2997                                 "error: %s: '-N' must exist in front of '%s'\n",
2998                                                 progname, argv[optopt + 1]);
2999                                         goto usage_error;
3000                                 }
3001                                 last_mirror->m_file = optarg;
3002                                 last_mirror->m_count = 1;
3003                         } else {
3004                                 /* mirror split */
3005                                 if (mirror_list == NULL)
3006                                         mirror_list = lfs_mirror_alloc();
3007                                 mirror_list->m_file = optarg;
3008                         }
3009                         has_m_file = true;
3010                         break;
3011                 case 'L':
3012                         if (strcmp(argv[optind - 1], "mdt") == 0) {
3013                                 /* Can be only the first component */
3014                                 if (layout != NULL) {
3015                                         result = -EINVAL;
3016                                         fprintf(stderr, "error: 'mdt' layout "
3017                                                 "can be only the first one\n");
3018                                         goto error;
3019                                 }
3020                                 if (lsa.lsa_comp_end > (1ULL << 30)) { /* 1Gb */
3021                                         result = -EFBIG;
3022                                         fprintf(stderr, "error: 'mdt' layout "
3023                                                 "size is too big\n");
3024                                         goto error;
3025                                 }
3026                                 lsa.lsa_pattern = LLAPI_LAYOUT_MDT;
3027                         } else if (strcmp(argv[optind - 1], "raid0") != 0) {
3028                                 result = -EINVAL;
3029                                 fprintf(stderr, "error: layout '%s' is "
3030                                         "unknown, supported layouts are: "
3031                                         "'mdt', 'raid0'\n", argv[optind]);
3032                                 goto error;
3033                         }
3034                         break;
3035                 case 'm':
3036                         if (!migrate_mode) {
3037                                 fprintf(stderr,
3038                                         "%s %s: -m|--mdt is valid only for migrate command\n",
3039                                         progname, argv[0]);
3040                                 goto usage_error;
3041                         }
3042                         migrate_mdt_mode = true;
3043                         lsa.lsa_nr_tgts = parse_targets(tgts,
3044                                                 sizeof(tgts) / sizeof(__u32),
3045                                                 lsa.lsa_nr_tgts, optarg);
3046                         if (lsa.lsa_nr_tgts < 0) {
3047                                 fprintf(stderr,
3048                                         "%s %s: invalid MDT target(s) '%s'\n",
3049                                         progname, argv[0], optarg);
3050                                 return CMD_HELP;
3051                         }
3052
3053                         lsa.lsa_tgts = tgts;
3054                         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
3055                                 lsa.lsa_stripe_off = tgts[0];
3056                         break;
3057                 case 'n':
3058                         if (!migrate_mode) {
3059                                 fprintf(stderr,
3060                                         "%s %s: -n|--non-block valid only for migrate command\n",
3061                                         progname, argv[0]);
3062                                 goto usage_error;
3063                         }
3064                         migration_flags |= MIGRATION_NONBLOCK;
3065                         break;
3066                 case 'N':
3067                         if (opc == SO_SETSTRIPE) {
3068                                 opc = SO_MIRROR_CREATE;
3069                                 mirror_mode = true;
3070                         }
3071                         mirror_count = 1;
3072                         if (optarg != NULL) {
3073                                 mirror_count = strtoul(optarg, &end, 0);
3074                                 if (*end != '\0' || mirror_count == 0) {
3075                                         fprintf(stderr,
3076                                                 "error: %s: bad mirror count: %s\n",
3077                                                 progname, optarg);
3078                                         result = -EINVAL;
3079                                         goto error;
3080                                 }
3081                         }
3082
3083                         new_mirror = lfs_mirror_alloc();
3084                         new_mirror->m_count = mirror_count;
3085
3086                         if (mirror_list == NULL)
3087                                 mirror_list = new_mirror;
3088
3089                         if (last_mirror != NULL) {
3090                                 /* wrap up last mirror */
3091                                 if (lsa.lsa_comp_end == 0)
3092                                         lsa.lsa_comp_end = LUSTRE_EOF;
3093
3094                                 result = comp_args_to_layout(lpp, &lsa, true);
3095                                 if (result) {
3096                                         lfs_mirror_free(new_mirror);
3097                                         goto error;
3098                                 }
3099
3100                                 setstripe_args_init_inherit(&lsa);
3101
3102                                 last_mirror->m_next = new_mirror;
3103                         }
3104
3105                         last_mirror = new_mirror;
3106                         lpp = &last_mirror->m_layout;
3107                         break;
3108                 case 'o':
3109 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
3110                         if (strcmp(argv[optind - 1], "--ost-list") == 0)
3111                                 fprintf(stderr, "warning: '--ost-list' is "
3112                                         "deprecated, use '--ost' instead\n");
3113 #endif
3114                         lsa.lsa_nr_tgts = parse_targets(tgts,
3115                                                 sizeof(tgts) / sizeof(__u32),
3116                                                 lsa.lsa_nr_tgts, optarg);
3117                         if (lsa.lsa_nr_tgts < 0) {
3118                                 fprintf(stderr,
3119                                         "%s %s: invalid OST target(s) '%s'\n",
3120                                         progname, argv[0], optarg);
3121                                 goto usage_error;
3122                         }
3123
3124                         lsa.lsa_tgts = tgts;
3125                         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
3126                                 lsa.lsa_stripe_off = tgts[0];
3127                         break;
3128                 case 'p':
3129                         if (optarg == NULL)
3130                                 goto usage_error;
3131                         lsa.lsa_pool_name = optarg;
3132
3133                         if (strlen(lsa.lsa_pool_name) == 0 ||
3134                             strncmp(lsa.lsa_pool_name, "none",
3135                                     LOV_MAXPOOLNAME) == 0)
3136                                 lsa.lsa_pool_name = NULL;
3137                         break;
3138                 case 'S':
3139                         result = llapi_parse_size(optarg, &lsa.lsa_stripe_size,
3140                                                   &size_units, 0);
3141                         if (result) {
3142                                 fprintf(stderr,
3143                                         "%s %s: invalid stripe size '%s'\n",
3144                                         progname, argv[0], optarg);
3145                                 goto usage_error;
3146                         }
3147                         break;
3148                 case 'v':
3149                         if (!migrate_mode) {
3150                                 fprintf(stderr,
3151                                         "%s %s: -v|--verbose valid only for migrate command\n",
3152                                         progname, argv[0]);
3153                                 goto usage_error;
3154                         }
3155                         migrate_mdt_param.fp_verbose = VERBOSE_DETAIL;
3156                         break;
3157                 case 'y':
3158                         from_yaml = true;
3159                         template = optarg;
3160                         break;
3161                 default:
3162                         fprintf(stderr, "%s %s: unrecognized option '%s'\n",
3163                                 progname, argv[0], argv[optind - 1]);
3164                         goto usage_error;
3165                 }
3166         }
3167
3168         fname = argv[optind];
3169
3170         if (optind == argc) {
3171                 fprintf(stderr, "%s %s: FILE must be specified\n",
3172                         progname, argv[0]);
3173                 goto usage_error;
3174         }
3175
3176         if (mirror_mode && mirror_count == 0) {
3177                 fprintf(stderr,
3178                         "error: %s: --mirror-count|-N option is required\n",
3179                         progname);
3180                 result = -EINVAL;
3181                 goto error;
3182         }
3183
3184         if (mirror_mode) {
3185                 if (lsa.lsa_comp_end == 0)
3186                         lsa.lsa_comp_end = LUSTRE_EOF;
3187         }
3188
3189         if (lsa.lsa_comp_end != 0) {
3190                 result = comp_args_to_layout(lpp, &lsa, true);
3191                 if (result)
3192                         goto error;
3193         }
3194
3195         if (mirror_flags & MF_NO_VERIFY) {
3196                 if (opc != SO_MIRROR_EXTEND) {
3197                         fprintf(stderr,
3198                                 "error: %s: --no-verify is valid only for lfs mirror extend command\n",
3199                                 progname);
3200                         result = -EINVAL;
3201                         goto error;
3202                 } else if (!has_m_file) {
3203                         fprintf(stderr,
3204                                 "error: %s: --no-verify must be specified with -f <victim_file> option\n",
3205                                 progname);
3206                         result = -EINVAL;
3207                         goto error;
3208                 }
3209         }
3210
3211         /* Only LCME_FL_INIT flags is used in PFL, and it shouldn't be
3212          * altered by user space tool, so we don't need to support the
3213          * --component-set for this moment. */
3214         if (comp_set && !comp_id) {
3215                 fprintf(stderr, "%s %s: --component-set doesn't have component-id set\n",
3216                         progname, argv[0]);
3217                 goto usage_error;
3218         }
3219
3220         if ((delete + comp_set + comp_del + comp_add) > 1) {
3221                 fprintf(stderr,
3222                         "%s %s: options --component-set, --component-del, --component-add and -d are mutually exclusive\n",
3223                         progname, argv[0]);
3224                 goto usage_error;
3225         }
3226
3227         if (delete && (setstripe_args_specified(&lsa) || comp_id != 0 ||
3228                        lsa.lsa_comp_flags != 0 || layout != NULL)) {
3229                 fprintf(stderr,
3230                         "%s %s: option -d is mutually exclusive with -s, -c, -o, -p, -I, -F and -E options\n",
3231                         progname, argv[0]);
3232                 goto usage_error;
3233         }
3234
3235         if ((comp_set || comp_del) &&
3236             (setstripe_args_specified(&lsa) || layout != NULL)) {
3237                 fprintf(stderr,
3238                         "%s %s: options --component-del and --component-set are mutually exclusive when used with -c, -E, -o, -p, or -s\n",
3239                         progname, argv[0]);
3240                 goto usage_error;
3241         }
3242
3243         if (comp_del && comp_id != 0 && lsa.lsa_comp_flags != 0) {
3244                 fprintf(stderr,
3245                         "%s %s: options -I and -F are mutually exclusive when used with --component-del\n",
3246                         progname, argv[0]);
3247                 goto usage_error;
3248         }
3249
3250         if (comp_add || comp_del) {
3251                 struct stat st;
3252
3253                 result = lstat(fname, &st);
3254                 if (result == 0 && S_ISDIR(st.st_mode)) {
3255                         fprintf(stderr,
3256                                 "%s setstripe: cannot use --component-add or --component-del for directory\n",
3257                                 progname);
3258                         goto usage_error;
3259                 }
3260
3261                 if (mirror_mode) {
3262                         fprintf(stderr, "error: %s: can't use --component-add "
3263                                 "or --component-del for mirror operation\n",
3264                                 progname);
3265                         goto usage_error;
3266                 }
3267         }
3268
3269         if (comp_add) {
3270                 if (layout == NULL) {
3271                         fprintf(stderr,
3272                                 "%s %s: option -E must be specified with --component-add\n",
3273                                 progname, argv[0]);
3274                         goto usage_error;
3275                 }
3276
3277                 result = adjust_first_extent(fname, layout);
3278                 if (result == -ENODATA)
3279                         comp_add = 0;
3280                 else if (result != 0)
3281                         goto error;
3282         }
3283
3284         if (from_yaml && from_copy) {
3285                 fprintf(stderr,
3286                         "%s: can't specify --yaml and --copy together\n",
3287                         progname);
3288                 goto error;
3289         }
3290
3291         if ((from_yaml || from_copy) &&
3292             (setstripe_args_specified(&lsa) || layout != NULL)) {
3293                 fprintf(stderr, "error: %s: can't specify --yaml with "
3294                         "-c, -S, -i, -o, -p or -E options.\n",
3295                         argv[0]);
3296                 goto error;
3297         }
3298
3299         if ((migration_flags & MIGRATION_NONBLOCK) && migration_block) {
3300                 fprintf(stderr,
3301                         "%s %s: options --non-block and --block are mutually exclusive\n",
3302                         progname, argv[0]);
3303                 goto usage_error;
3304         }
3305
3306         if (!comp_del && !comp_set && (opc != SO_MIRROR_SPLIT) &&
3307             comp_id != 0) {
3308                 fprintf(stderr,
3309                 "%s %s: option -I can only be used with --component-del or --component-set or lfs mirror split\n",
3310                         progname, argv[0]);
3311                 goto usage_error;
3312         }
3313
3314         if (migrate_mdt_mode) {
3315                 struct lmv_user_md *lmu;
3316
3317                 /* initialize migrate mdt parameters */
3318                 lmu = calloc(1, lmv_user_md_size(lsa.lsa_nr_tgts,
3319                                                  LMV_USER_MAGIC_SPECIFIC));
3320                 if (!lmu) {
3321                         fprintf(stderr,
3322                                 "%s %s: cannot allocate memory for lmv_user_md: %s\n",
3323                                 progname, argv[0], strerror(ENOMEM));
3324                         result = -ENOMEM;
3325                         goto error;
3326                 }
3327                 if (lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT)
3328                         lmu->lum_stripe_count = lsa.lsa_stripe_count;
3329                 if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT) {
3330                         fprintf(stderr,
3331                                 "%s %s: migrate should specify MDT index\n",
3332                                 progname, argv[0]);
3333                         free(lmu);
3334                         goto usage_error;
3335                 }
3336                 lmu->lum_stripe_offset = lsa.lsa_stripe_off;
3337                 if (lsa.lsa_pattern != LLAPI_LAYOUT_RAID0)
3338                         lmu->lum_hash_type = lsa.lsa_pattern;
3339                 else
3340                         lmu->lum_hash_type = LMV_HASH_TYPE_FNV_1A_64;
3341                 if (lsa.lsa_pool_name) {
3342                         strncpy(lmu->lum_pool_name, lsa.lsa_pool_name,
3343                                 sizeof(lmu->lum_pool_name) - 1);
3344                         lmu->lum_pool_name[sizeof(lmu->lum_pool_name) - 1] = 0;
3345                 }
3346                 if (lsa.lsa_nr_tgts > 1) {
3347                         int i;
3348
3349                         if (lsa.lsa_stripe_count > 0 &&
3350                             lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT &&
3351                             lsa.lsa_stripe_count != lsa.lsa_nr_tgts) {
3352                                 fprintf(stderr,
3353                                         "error: %s: stripe count %lld doesn't match the number of MDTs: %d\n",
3354                                         progname, lsa.lsa_stripe_count,
3355                                         lsa.lsa_nr_tgts);
3356                                 free(lmu);
3357                                 goto usage_error;
3358                         }
3359
3360                         lmu->lum_magic = LMV_USER_MAGIC_SPECIFIC;
3361                         lmu->lum_stripe_count = lsa.lsa_nr_tgts;
3362                         for (i = 0; i < lsa.lsa_nr_tgts; i++)
3363                                 lmu->lum_objects[i].lum_mds = lsa.lsa_tgts[i];
3364                 } else {
3365                         lmu->lum_magic = LMV_USER_MAGIC;
3366                 }
3367
3368                 migrate_mdt_param.fp_lmv_md = lmu;
3369                 migrate_mdt_param.fp_migrate = 1;
3370         } else if (layout == NULL) {
3371                 /* initialize stripe parameters */
3372                 param = calloc(1, offsetof(typeof(*param),
3373                                lsp_osts[lsa.lsa_nr_tgts]));
3374                 if (param == NULL) {
3375                         fprintf(stderr,
3376                                 "%s %s: cannot allocate memory for parameters: %s\n",
3377                                 progname, argv[0], strerror(ENOMEM));
3378                         result = -ENOMEM;
3379                         goto error;
3380                 }
3381
3382                 if (lsa.lsa_stripe_size != LLAPI_LAYOUT_DEFAULT)
3383                         param->lsp_stripe_size = lsa.lsa_stripe_size;
3384                 if (lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT) {
3385                         if (lsa.lsa_stripe_count == LLAPI_LAYOUT_WIDE)
3386                                 param->lsp_stripe_count = -1;
3387                         else
3388                                 param->lsp_stripe_count = lsa.lsa_stripe_count;
3389                 }
3390                 if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
3391                         param->lsp_stripe_offset = -1;
3392                 else
3393                         param->lsp_stripe_offset = lsa.lsa_stripe_off;
3394                 param->lsp_pool = lsa.lsa_pool_name;
3395                 param->lsp_is_specific = false;
3396                 if (lsa.lsa_nr_tgts > 0) {
3397                         if (lsa.lsa_stripe_count > 0 &&
3398                             lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT &&
3399                             lsa.lsa_stripe_count != LLAPI_LAYOUT_WIDE &&
3400                             lsa.lsa_nr_tgts != lsa.lsa_stripe_count) {
3401                                 fprintf(stderr,
3402                                         "error: %s: stripe count %lld doesn't match the number of OSTs: %d\n",
3403                                         argv[0], lsa.lsa_stripe_count,
3404                                         lsa.lsa_nr_tgts);
3405                                 free(param);
3406                                 goto usage_error;
3407                         }
3408
3409                         param->lsp_is_specific = true;
3410                         param->lsp_stripe_count = lsa.lsa_nr_tgts;
3411                         memcpy(param->lsp_osts, tgts,
3412                                sizeof(*tgts) * lsa.lsa_nr_tgts);
3413                 }
3414         }
3415
3416         if (from_yaml) {
3417                 /* generate a layout from a YAML template */
3418                 result = lfs_comp_create_from_yaml(template, &layout,
3419                                                    &lsa, tgts);
3420                 if (result) {
3421                         fprintf(stderr, "error: %s: can't create composite "
3422                                 "layout from template file %s\n",
3423                                 argv[0], template);
3424                         goto error;
3425                 }
3426         } else if (from_copy) {
3427                 layout = llapi_layout_get_by_path(template, 0);
3428                 if (layout == NULL) {
3429                         fprintf(stderr,
3430                             "%s: can't create composite layout from file %s.\n",
3431                                 progname, template);
3432                         goto error;
3433                 }
3434         }
3435
3436         for (fname = argv[optind]; fname != NULL; fname = argv[++optind]) {
3437                 if (migrate_mdt_mode) {
3438                         result = llapi_migrate_mdt(fname, &migrate_mdt_param);
3439                 } else if (migrate_mode) {
3440                         result = lfs_migrate(fname, migration_flags, param,
3441                                              layout);
3442                 } else if (comp_set != 0) {
3443                         result = lfs_component_set(fname, comp_id,
3444                                                    lsa.lsa_comp_flags,
3445                                                    lsa.lsa_comp_neg_flags);
3446                 } else if (comp_del != 0) {
3447                         result = lfs_component_del(fname, comp_id,
3448                                                    lsa.lsa_comp_flags,
3449                                                    lsa.lsa_comp_neg_flags);
3450                 } else if (comp_add != 0) {
3451                         result = lfs_component_add(fname, layout);
3452                 } else if (opc == SO_MIRROR_CREATE) {
3453                         result = mirror_create(fname, mirror_list);
3454                 } else if (opc == SO_MIRROR_EXTEND) {
3455                         result = mirror_extend(fname, mirror_list,
3456                                                mirror_flags);
3457                 } else if (opc == SO_MIRROR_SPLIT) {
3458                         if (!mirror_id && !comp_id && !lsa.lsa_pool_name) {
3459                                 fprintf(stderr,
3460                         "%s %s: no mirror id or component id or pool name"
3461                         " is specified\n", progname, argv[0]);
3462                                 goto usage_error;
3463                         }
3464                         if (lsa.lsa_pool_name)
3465                                 mirror_flags |= MF_COMP_POOL;
3466                         else if (mirror_id != 0)
3467                                 comp_id = mirror_id;
3468                         else
3469                                 mirror_flags |= MF_COMP_ID;
3470                         result = mirror_split(fname, comp_id, lsa.lsa_pool_name,
3471                                               mirror_flags,
3472                                               has_m_file ? mirror_list->m_file :
3473                                               NULL);
3474                 } else if (layout != NULL) {
3475                         result = lfs_component_create(fname, O_CREAT | O_WRONLY,
3476                                                       0666, layout);
3477                         if (result >= 0) {
3478                                 close(result);
3479                                 result = 0;
3480                         }
3481                 } else {
3482                         result = llapi_file_open_param(fname,
3483                                                        O_CREAT | O_WRONLY,
3484                                                        0666, param);
3485                         if (result >= 0) {
3486                                 close(result);
3487                                 result = 0;
3488                         }
3489                 }
3490                 if (result) {
3491                         /* Save the first error encountered. */
3492                         if (result2 == 0)
3493                                 result2 = result;
3494                         continue;
3495                 }
3496         }
3497
3498         free(param);
3499         free(migrate_mdt_param.fp_lmv_md);
3500         llapi_layout_free(layout);
3501         lfs_mirror_list_free(mirror_list);
3502         return result2;
3503 usage_error:
3504         result = CMD_HELP;
3505 error:
3506         llapi_layout_free(layout);
3507         lfs_mirror_list_free(mirror_list);
3508         return result;
3509 }
3510
3511 static int lfs_poollist(int argc, char **argv)
3512 {
3513         if (argc != 2)
3514                 return CMD_HELP;
3515
3516         return llapi_poollist(argv[1]);
3517 }
3518
3519 static int set_time(time_t *time, time_t *set, char *str)
3520 {
3521         time_t t;
3522         int res = 0;
3523         char *endptr;
3524
3525         if (str[0] == '+')
3526                 res = 1;
3527         else if (str[0] == '-')
3528                 res = -1;
3529
3530         if (res)
3531                 str++;
3532
3533         t = strtol(str, &endptr, 0);
3534         if (*endptr != '\0') {
3535                 fprintf(stderr,
3536                         "%s find: bad time '%s': %s\n",
3537                         progname, str, strerror(EINVAL));
3538                 return INT_MAX;
3539         }
3540         if (*time < t * 24 * 60 * 60) {
3541                 if (res != 0)
3542                         str--;
3543                 fprintf(stderr,
3544                         "%s find: bad time '%s': too large\n",
3545                         progname, str);
3546                 return INT_MAX;
3547         }
3548
3549         *set = *time - t * 24 * 60 * 60;
3550         return res;
3551 }
3552
3553 static int name2uid(unsigned int *id, const char *name)
3554 {
3555         struct passwd *passwd;
3556
3557         passwd = getpwnam(name);
3558         if (passwd == NULL)
3559                 return -ENOENT;
3560         *id = passwd->pw_uid;
3561
3562         return 0;
3563 }
3564
3565 static int name2gid(unsigned int *id, const char *name)
3566 {
3567         struct group *group;
3568
3569         group = getgrnam(name);
3570         if (group == NULL)
3571                 return -ENOENT;
3572         *id = group->gr_gid;
3573
3574         return 0;
3575 }
3576
3577 static inline int name2projid(unsigned int *id, const char *name)
3578 {
3579         return -ENOTSUP;
3580 }
3581
3582 static int uid2name(char **name, unsigned int id)
3583 {
3584         struct passwd *passwd;
3585
3586         passwd = getpwuid(id);
3587         if (passwd == NULL)
3588                 return -ENOENT;
3589         *name = passwd->pw_name;
3590
3591         return 0;
3592 }
3593
3594 static inline int gid2name(char **name, unsigned int id)
3595 {
3596         struct group *group;
3597
3598         group = getgrgid(id);
3599         if (group == NULL)
3600                 return -ENOENT;
3601         *name = group->gr_name;
3602
3603         return 0;
3604 }
3605
3606 static int name2layout(__u32 *layout, char *name)
3607 {
3608         char *ptr, *layout_name;
3609
3610         *layout = 0;
3611         for (ptr = name; ; ptr = NULL) {
3612                 layout_name = strtok(ptr, ",");
3613                 if (layout_name == NULL)
3614                         break;
3615                 if (strcmp(layout_name, "released") == 0)
3616                         *layout |= LOV_PATTERN_F_RELEASED;
3617                 else if (strcmp(layout_name, "raid0") == 0)
3618                         *layout |= LOV_PATTERN_RAID0;
3619                 else if (strcmp(layout_name, "mdt") == 0)
3620                         *layout |= LOV_PATTERN_MDT;
3621                 else
3622                         return -1;
3623         }
3624         return 0;
3625 }
3626
3627 static int lfs_find(int argc, char **argv)
3628 {
3629         int c, rc;
3630         int ret = 0;
3631         time_t t;
3632         struct find_param param = {
3633                 .fp_max_depth = -1,
3634                 .fp_quiet = 1,
3635         };
3636         struct option long_opts[] = {
3637         { .val = 'A',   .name = "atime",        .has_arg = required_argument },
3638         { .val = 'b',   .name = "blocks",       .has_arg = required_argument },
3639         { .val = LFS_COMP_COUNT_OPT,
3640                         .name = "comp-count",   .has_arg = required_argument },
3641         { .val = LFS_COMP_COUNT_OPT,
3642                         .name = "component-count",
3643                                                 .has_arg = required_argument },
3644         { .val = LFS_COMP_FLAGS_OPT,
3645                         .name = "comp-flags",   .has_arg = required_argument },
3646         { .val = LFS_COMP_FLAGS_OPT,
3647                         .name = "component-flags",
3648                                                 .has_arg = required_argument },
3649         { .val = LFS_COMP_START_OPT,
3650                         .name = "comp-start",   .has_arg = required_argument },
3651         { .val = LFS_COMP_START_OPT,
3652                         .name = "component-start",
3653                                                 .has_arg = required_argument },
3654         { .val = LFS_MIRROR_STATE_OPT,
3655                         .name = "mirror-state", .has_arg = required_argument },
3656         { .val = 'c',   .name = "stripe-count", .has_arg = required_argument },
3657         { .val = 'c',   .name = "stripe_count", .has_arg = required_argument },
3658         { .val = 'C',   .name = "ctime",        .has_arg = required_argument },
3659 /* getstripe { .val = 'd', .name = "directory", .has_arg = no_argument }, */
3660         { .val = 'D',   .name = "maxdepth",     .has_arg = required_argument },
3661         { .val = 'E',   .name = "comp-end",     .has_arg = required_argument },
3662         { .val = 'E',   .name = "component-end",
3663                                                 .has_arg = required_argument },
3664 /* find { .val = 'F',   .name = "fid",          .has_arg = no_argument }, */
3665         { .val = 'g',   .name = "gid",          .has_arg = required_argument },
3666         { .val = 'G',   .name = "group",        .has_arg = required_argument },
3667         { .val = 'H',   .name = "mdt-hash",     .has_arg = required_argument },
3668         { .val = 'i',   .name = "stripe-index", .has_arg = required_argument },
3669         { .val = 'i',   .name = "stripe_index", .has_arg = required_argument },
3670 /* getstripe { .val = 'I', .name = "comp-id",   .has_arg = required_argument }*/
3671         { .val = 'l',   .name = "lazy",         .has_arg = no_argument },
3672         { .val = 'L',   .name = "layout",       .has_arg = required_argument },
3673         { .val = 'm',   .name = "mdt",          .has_arg = required_argument },
3674         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument },
3675         { .val = 'm',   .name = "mdt_index",    .has_arg = required_argument },
3676         { .val = 'M',   .name = "mtime",        .has_arg = required_argument },
3677         { .val = 'n',   .name = "name",         .has_arg = required_argument },
3678         { .val = 'N',   .name = "mirror-count", .has_arg = required_argument },
3679 /* find { .val = 'o'    .name = "or", .has_arg = no_argument }, like find(1) */
3680         { .val = 'O',   .name = "obd",          .has_arg = required_argument },
3681         { .val = 'O',   .name = "ost",          .has_arg = required_argument },
3682         /* no short option for pool yet, can be 'p' after 2.18 */
3683         { .val = LFS_POOL_OPT,
3684                         .name = "pool",         .has_arg = required_argument },
3685         { .val = '0',   .name = "print0",       .has_arg = no_argument },
3686         { .val = 'P',   .name = "print",        .has_arg = no_argument },
3687         { .val = LFS_PROJID_OPT,
3688                         .name = "projid",       .has_arg = required_argument },
3689 /* getstripe { .val = 'q', .name = "quiet",     .has_arg = no_argument }, */
3690 /* getstripe { .val = 'r', .name = "recursive", .has_arg = no_argument }, */
3691 /* getstripe { .val = 'R', .name = "raw",       .has_arg = no_argument }, */
3692         { .val = 's',   .name = "size",         .has_arg = required_argument },
3693         { .val = 'S',   .name = "stripe-size",  .has_arg = required_argument },
3694         { .val = 'S',   .name = "stripe_size",  .has_arg = required_argument },
3695         { .val = 't',   .name = "type",         .has_arg = required_argument },
3696         { .val = 'T',   .name = "mdt-count",    .has_arg = required_argument },
3697         { .val = 'u',   .name = "uid",          .has_arg = required_argument },
3698         { .val = 'U',   .name = "user",         .has_arg = required_argument },
3699 /* getstripe { .val = 'v', .name = "verbose",   .has_arg = no_argument }, */
3700 /* getstripe { .val = 'y', .name = "yaml",      .has_arg = no_argument }, */
3701         { .name = NULL } };
3702         int pathstart = -1;
3703         int pathend = -1;
3704         int neg_opt = 0;
3705         time_t *xtime;
3706         int *xsign;
3707         int isoption;
3708         char *endptr;
3709
3710         time(&t);
3711
3712         /* when getopt_long_only() hits '!' it returns 1, puts "!" in optarg */
3713         while ((c = getopt_long_only(argc, argv,
3714                         "-0A:b:c:C:D:E:g:G:H:i:L:m:M:n:N:O:Ppqrs:S:t:T:u:U:v",
3715                         long_opts, NULL)) >= 0) {
3716                 xtime = NULL;
3717                 xsign = NULL;
3718                 if (neg_opt)
3719                         --neg_opt;
3720                 /* '!' is part of option */
3721                 /* when getopt_long_only() finds a string which is not
3722                  * an option nor a known option argument it returns 1
3723                  * in that case if we already have found pathstart and pathend
3724                  * (i.e. we have the list of pathnames),
3725                  * the only supported value is "!"
3726                  */
3727                 isoption = (c != 1) || (strcmp(optarg, "!") == 0);
3728                 if (!isoption && pathend != -1) {
3729                         fprintf(stderr, "err: %s: filename|dirname must either "
3730                                         "precede options or follow options\n",
3731                                         argv[0]);
3732                         ret = CMD_HELP;
3733                         goto err;
3734                 }
3735                 if (!isoption && pathstart == -1)
3736                         pathstart = optind - 1;
3737                 if (isoption && pathstart != -1 && pathend == -1)
3738                         pathend = optind - 2;
3739                 switch (c) {
3740                 case 0:
3741                         /* Long options. */
3742                         break;
3743                 case 1:
3744                         /* unknown; opt is "!" or path component,
3745                          * checking done above.
3746                          */
3747                         if (strcmp(optarg, "!") == 0)
3748                                 neg_opt = 2;
3749                         break;
3750                 case 'A':
3751                         xtime = &param.fp_atime;
3752                         xsign = &param.fp_asign;
3753                         param.fp_exclude_atime = !!neg_opt;
3754                         /* no break, this falls through to 'C' for ctime */
3755                 case 'C':
3756                         if (c == 'C') {
3757                                 xtime = &param.fp_ctime;
3758                                 xsign = &param.fp_csign;
3759                                 param.fp_exclude_ctime = !!neg_opt;
3760                         }
3761                         /* no break, this falls through to 'M' for mtime */
3762                 case 'M':
3763                         if (c == 'M') {
3764                                 xtime = &param.fp_mtime;
3765                                 xsign = &param.fp_msign;
3766                                 param.fp_exclude_mtime = !!neg_opt;
3767                         }
3768                         rc = set_time(&t, xtime, optarg);
3769                         if (rc == INT_MAX) {
3770                                 ret = -1;
3771                                 goto err;
3772                         }
3773                         if (rc)
3774                                 *xsign = rc;
3775                         break;
3776                 case 'b':
3777                         if (optarg[0] == '+') {
3778                                 param.fp_blocks_sign = -1;
3779                                 optarg++;
3780                         } else if (optarg[0] == '-') {
3781                                 param.fp_blocks_sign =  1;
3782                                 optarg++;
3783                         }
3784
3785                         param.fp_blocks_units = 1024;
3786                         ret = llapi_parse_size(optarg, &param.fp_blocks,
3787                                                &param.fp_blocks_units, 0);
3788                         if (ret) {
3789                                 fprintf(stderr, "error: bad blocks '%s'\n",
3790                                         optarg);
3791                                 goto err;
3792                         }
3793                         param.fp_check_blocks = 1;
3794                         param.fp_exclude_blocks = !!neg_opt;
3795                         break;
3796                 case LFS_COMP_COUNT_OPT:
3797                         if (optarg[0] == '+') {
3798                                 param.fp_comp_count_sign = -1;
3799                                 optarg++;
3800                         } else if (optarg[0] == '-') {
3801                                 param.fp_comp_count_sign =  1;
3802                                 optarg++;
3803                         }
3804
3805                         param.fp_comp_count = strtoul(optarg, &endptr, 0);
3806                         if (*endptr != '\0') {
3807                                 fprintf(stderr, "error: bad component count "
3808                                         "'%s'\n", optarg);
3809                                 goto err;
3810                         }
3811                         param.fp_check_comp_count = 1;
3812                         param.fp_exclude_comp_count = !!neg_opt;
3813                         break;
3814                 case LFS_COMP_FLAGS_OPT:
3815                         rc = comp_str2flags(optarg, &param.fp_comp_flags,
3816                                             &param.fp_comp_neg_flags);
3817                         if (rc) {
3818                                 fprintf(stderr, "error: bad component flags "
3819                                         "'%s'\n", optarg);
3820                                 goto err;
3821                         }
3822                         param.fp_check_comp_flags = 1;
3823                         if (neg_opt) {
3824                                 __u32 flags = param.fp_comp_neg_flags;
3825                                 param.fp_comp_neg_flags = param.fp_comp_flags;
3826                                 param.fp_comp_flags = flags;
3827                         }
3828                         break;
3829                 case LFS_COMP_START_OPT:
3830                         if (optarg[0] == '+') {
3831                                 param.fp_comp_start_sign = -1;
3832                                 optarg++;
3833                         } else if (optarg[0] == '-') {
3834                                 param.fp_comp_start_sign =  1;
3835                                 optarg++;
3836                         }
3837
3838                         rc = llapi_parse_size(optarg, &param.fp_comp_start,
3839                                               &param.fp_comp_start_units, 0);
3840                         if (rc) {
3841                                 fprintf(stderr, "error: bad component start "
3842                                         "'%s'\n", optarg);
3843                                 goto err;
3844                         }
3845                         param.fp_check_comp_start = 1;
3846                         param.fp_exclude_comp_start = !!neg_opt;
3847                         break;
3848                 case LFS_MIRROR_STATE_OPT:
3849                         rc = mirror_str2state(optarg, &param.fp_mirror_state,
3850                                               &param.fp_mirror_neg_state);
3851                         if (rc) {
3852                                 fprintf(stderr,
3853                                         "error: bad mirrored file state '%s'\n",
3854                                         optarg);
3855                                 goto err;
3856                         }
3857                         param.fp_check_mirror_state = 1;
3858                         if (neg_opt) {
3859                                 __u16 state = param.fp_mirror_neg_state;
3860                                 param.fp_mirror_neg_state =
3861                                         param.fp_mirror_state;
3862                                 param.fp_mirror_state = state;
3863                         }
3864                         break;
3865                 case 'c':
3866                         if (optarg[0] == '+') {
3867                                 param.fp_stripe_count_sign = -1;
3868                                 optarg++;
3869                         } else if (optarg[0] == '-') {
3870                                 param.fp_stripe_count_sign =  1;
3871                                 optarg++;
3872                         }
3873
3874                         param.fp_stripe_count = strtoul(optarg, &endptr, 0);
3875                         if (*endptr != '\0') {
3876                                 fprintf(stderr,"error: bad stripe_count '%s'\n",
3877                                         optarg);
3878                                 ret = -1;
3879                                 goto err;
3880                         }
3881                         param.fp_check_stripe_count = 1;
3882                         param.fp_exclude_stripe_count = !!neg_opt;
3883                         break;
3884                 case 'D':
3885                         param.fp_max_depth = strtol(optarg, 0, 0);
3886                         break;
3887                 case 'E':
3888                         if (optarg[0] == '+') {
3889                                 param.fp_comp_end_sign = -1;
3890                                 optarg++;
3891                         } else if (optarg[0] == '-') {
3892                                 param.fp_comp_end_sign =  1;
3893                                 optarg++;
3894                         }
3895
3896                         if (arg_is_eof(optarg)) {
3897                                 param.fp_comp_end = LUSTRE_EOF;
3898                                 param.fp_comp_end_units = 1;
3899                                 rc = 0;
3900                         } else {
3901                                 rc = llapi_parse_size(optarg,
3902                                                 &param.fp_comp_end,
3903                                                 &param.fp_comp_end_units, 0);
3904                         }
3905                         if (rc) {
3906                                 fprintf(stderr, "error: bad component end "
3907                                         "'%s'\n", optarg);
3908                                 goto err;
3909                         }
3910                         param.fp_check_comp_end = 1;
3911                         param.fp_exclude_comp_end = !!neg_opt;
3912                         break;
3913                 case 'g':
3914                 case 'G':
3915                         rc = name2gid(&param.fp_gid, optarg);
3916                         if (rc) {
3917                                 param.fp_gid = strtoul(optarg, &endptr, 10);
3918                                 if (*endptr != '\0') {
3919                                         fprintf(stderr, "Group/GID: %s cannot "
3920                                                 "be found.\n", optarg);
3921                                         ret = -1;
3922                                         goto err;
3923                                 }
3924                         }
3925                         param.fp_exclude_gid = !!neg_opt;
3926                         param.fp_check_gid = 1;
3927                         break;
3928                 case 'H':
3929                         param.fp_hash_type = check_hashtype(optarg);
3930                         if (param.fp_hash_type == 0) {
3931                                 fprintf(stderr, "error: bad hash_type '%s'\n",
3932                                         optarg);
3933                                 ret = -1;
3934                                 goto err;
3935                         }
3936                         param.fp_check_hash_type = 1;
3937                         param.fp_exclude_hash_type = !!neg_opt;
3938                         break;
3939                 case 'l':
3940                         param.fp_lazy = 1;
3941                         break;
3942                 case 'L':
3943                         ret = name2layout(&param.fp_layout, optarg);
3944                         if (ret)
3945                                 goto err;
3946                         param.fp_exclude_layout = !!neg_opt;
3947                         param.fp_check_layout = 1;
3948                         break;
3949                 case 'u':
3950                 case 'U':
3951                         rc = name2uid(&param.fp_uid, optarg);
3952                         if (rc) {
3953                                 param.fp_uid = strtoul(optarg, &endptr, 10);
3954                                 if (*endptr != '\0') {
3955                                         fprintf(stderr, "User/UID: %s cannot "
3956                                                 "be found.\n", optarg);
3957                                         ret = -1;
3958                                         goto err;
3959                                 }
3960                         }
3961                         param.fp_exclude_uid = !!neg_opt;
3962                         param.fp_check_uid = 1;
3963                         break;
3964                 case 'n':
3965                         param.fp_pattern = (char *)optarg;
3966                         param.fp_exclude_pattern = !!neg_opt;
3967                         break;
3968                 case 'N':
3969                         if (optarg[0] == '+') {
3970                                 param.fp_mirror_count_sign = -1;
3971                                 optarg++;
3972                         } else if (optarg[0] == '-') {
3973                                 param.fp_mirror_count_sign =  1;
3974                                 optarg++;
3975                         }
3976
3977                         param.fp_mirror_count = strtoul(optarg, &endptr, 0);
3978                         if (*endptr != '\0') {
3979                                 fprintf(stderr,
3980                                         "error: bad mirror count '%s'\n",
3981                                         optarg);
3982                                 goto err;
3983                         }
3984                         param.fp_check_mirror_count = 1;
3985                         param.fp_exclude_mirror_count = !!neg_opt;
3986                         break;
3987                 case 'm':
3988                 case 'i':
3989                 case 'O': {
3990                         char *buf, *token, *next, *p;
3991                         int len = 1;
3992                         void *tmp;
3993
3994                         buf = strdup(optarg);
3995                         if (buf == NULL) {
3996                                 ret = -ENOMEM;
3997                                 goto err;
3998                         }
3999
4000                         param.fp_exclude_obd = !!neg_opt;
4001
4002                         token = buf;
4003                         while (token && *token) {
4004                                 token = strchr(token, ',');
4005                                 if (token) {
4006                                         len++;
4007                                         token++;
4008                                 }
4009                         }
4010                         if (c == 'm') {
4011                                 param.fp_exclude_mdt = !!neg_opt;
4012                                 param.fp_num_alloc_mdts += len;
4013                                 tmp = realloc(param.fp_mdt_uuid,
4014                                               param.fp_num_alloc_mdts *
4015                                               sizeof(*param.fp_mdt_uuid));
4016                                 if (tmp == NULL) {
4017                                         ret = -ENOMEM;
4018                                         goto err_free;
4019                                 }
4020
4021                                 param.fp_mdt_uuid = tmp;
4022                         } else {
4023                                 param.fp_exclude_obd = !!neg_opt;
4024                                 param.fp_num_alloc_obds += len;
4025                                 tmp = realloc(param.fp_obd_uuid,
4026                                               param.fp_num_alloc_obds *
4027                                               sizeof(*param.fp_obd_uuid));
4028                                 if (tmp == NULL) {
4029                                         ret = -ENOMEM;
4030                                         goto err_free;
4031                                 }
4032
4033                                 param.fp_obd_uuid = tmp;
4034                         }
4035                         for (token = buf; token && *token; token = next) {
4036                                 struct obd_uuid *puuid;
4037                                 if (c == 'm') {
4038                                         puuid =
4039                                         &param.fp_mdt_uuid[param.fp_num_mdts++];
4040                                 } else {
4041                                         puuid =
4042                                         &param.fp_obd_uuid[param.fp_num_obds++];
4043                                 }
4044                                 p = strchr(token, ',');
4045                                 next = 0;
4046                                 if (p) {
4047                                         *p = 0;
4048                                         next = p+1;
4049                                 }
4050
4051                                 if (strlen(token) > sizeof(puuid->uuid) - 1) {
4052                                         ret = -E2BIG;
4053                                         goto err_free;
4054                                 }
4055
4056                                 strncpy(puuid->uuid, token,
4057                                         sizeof(puuid->uuid));
4058                         }
4059 err_free:
4060                         if (buf)
4061                                 free(buf);
4062                         break;
4063                 }
4064 #if LUSTRE_VERSION_CODE >= OBD_OCD_VERSION(2, 18, 53, 0)
4065                 case 'p':
4066 #endif
4067                 case LFS_POOL_OPT:
4068                         if (strlen(optarg) > LOV_MAXPOOLNAME) {
4069                                 fprintf(stderr,
4070                                         "Pool name %s is too long (max %d)\n",
4071                                         optarg, LOV_MAXPOOLNAME);
4072                                 ret = -1;
4073                                 goto err;
4074                         }
4075                         /*
4076                          * We do check for empty pool because empty pool
4077                          * is used to find V1 LOV attributes
4078                          */
4079                         strncpy(param.fp_poolname, optarg, LOV_MAXPOOLNAME);
4080                         param.fp_poolname[LOV_MAXPOOLNAME] = '\0';
4081                         param.fp_exclude_pool = !!neg_opt;
4082                         param.fp_check_pool = 1;
4083                         break;
4084 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 14, 53, 0)
4085                 case 'p': /* want this for --pool, to match getstripe/find */
4086                         fprintf(stderr,
4087                                 "warning: -p deprecated, use --print0 or -0\n");
4088 #endif
4089                 case '0':
4090                         param.fp_zero_end = 1;
4091                         break;
4092                 case 'P': /* we always print, this option is a no-op */
4093                         break;
4094                 case LFS_PROJID_OPT:
4095                         rc = name2projid(&param.fp_projid, optarg);
4096                         if (rc) {
4097                                 param.fp_projid = strtoul(optarg, &endptr, 10);
4098                                 if (*endptr != '\0') {
4099                                         fprintf(stderr,
4100                                                 "Invalid project ID: %s",
4101                                                 optarg);
4102                                         ret = -1;
4103                                         goto err;
4104                                 }
4105                         }
4106                         param.fp_exclude_projid = !!neg_opt;
4107                         param.fp_check_projid = 1;
4108                         break;
4109                 case 's':
4110                         if (optarg[0] == '+') {
4111                                 param.fp_size_sign = -1;
4112                                 optarg++;
4113                         } else if (optarg[0] == '-') {
4114                                 param.fp_size_sign =  1;
4115                                 optarg++;
4116                         }
4117
4118                         ret = llapi_parse_size(optarg, &param.fp_size,
4119                                                &param.fp_size_units, 0);
4120                         if (ret) {
4121                                 fprintf(stderr, "error: bad file size '%s'\n",
4122                                         optarg);
4123                                 goto err;
4124                         }
4125                         param.fp_check_size = 1;
4126                         param.fp_exclude_size = !!neg_opt;
4127                         break;
4128                 case 'S':
4129                         if (optarg[0] == '+') {
4130                                 param.fp_stripe_size_sign = -1;
4131                                 optarg++;
4132                         } else if (optarg[0] == '-') {
4133                                 param.fp_stripe_size_sign =  1;
4134                                 optarg++;
4135                         }
4136
4137                         ret = llapi_parse_size(optarg, &param.fp_stripe_size,
4138                                                &param.fp_stripe_size_units, 0);
4139                         if (ret) {
4140                                 fprintf(stderr, "error: bad stripe_size '%s'\n",
4141                                         optarg);
4142                                 goto err;
4143                         }
4144                         param.fp_check_stripe_size = 1;
4145                         param.fp_exclude_stripe_size = !!neg_opt;
4146                         break;
4147                 case 't':
4148                         param.fp_exclude_type = !!neg_opt;
4149                         switch (optarg[0]) {
4150                         case 'b':
4151                                 param.fp_type = S_IFBLK;
4152                                 break;
4153                         case 'c':
4154                                 param.fp_type = S_IFCHR;
4155                                 break;
4156                         case 'd':
4157                                 param.fp_type = S_IFDIR;
4158                                 break;
4159                         case 'f':
4160                                 param.fp_type = S_IFREG;
4161                                 break;
4162                         case 'l':
4163                                 param.fp_type = S_IFLNK;
4164                                 break;
4165                         case 'p':
4166                                 param.fp_type = S_IFIFO;
4167                                 break;
4168                         case 's':
4169                                 param.fp_type = S_IFSOCK;
4170                                 break;
4171                         default:
4172                                 fprintf(stderr, "error: %s: bad type '%s'\n",
4173                                         argv[0], optarg);
4174                                 ret = CMD_HELP;
4175                                 goto err;
4176                         };
4177                         break;
4178                 case 'T':
4179                         if (optarg[0] == '+') {
4180                                 param.fp_mdt_count_sign = -1;
4181                                 optarg++;
4182                         } else if (optarg[0] == '-') {
4183                                 param.fp_mdt_count_sign =  1;
4184                                 optarg++;
4185                         }
4186
4187                         param.fp_mdt_count = strtoul(optarg, &endptr, 0);
4188                         if (*endptr != '\0') {
4189                                 fprintf(stderr, "error: bad mdt_count '%s'\n",
4190                                         optarg);
4191                                 ret = -1;
4192                                 goto err;
4193                         }
4194                         param.fp_check_mdt_count = 1;
4195                         param.fp_exclude_mdt_count = !!neg_opt;
4196                         break;
4197                 default:
4198                         ret = CMD_HELP;
4199                         goto err;
4200                 };
4201         }
4202
4203         if (pathstart == -1) {
4204                 fprintf(stderr, "error: %s: no filename|pathname\n",
4205                         argv[0]);
4206                 ret = CMD_HELP;
4207                 goto err;
4208         } else if (pathend == -1) {
4209                 /* no options */
4210                 pathend = argc;
4211         }
4212
4213         do {
4214                 rc = llapi_find(argv[pathstart], &param);
4215                 if (rc != 0 && ret == 0)
4216                         ret = rc;
4217         } while (++pathstart < pathend);
4218
4219         if (ret)
4220                 fprintf(stderr, "error: %s failed for %s.\n",
4221                         argv[0], argv[optind - 1]);
4222 err:
4223         if (param.fp_obd_uuid && param.fp_num_alloc_obds)
4224                 free(param.fp_obd_uuid);
4225
4226         if (param.fp_mdt_uuid && param.fp_num_alloc_mdts)
4227                 free(param.fp_mdt_uuid);
4228
4229         return ret;
4230 }
4231
4232 static int lfs_getstripe_internal(int argc, char **argv,
4233                                   struct find_param *param)
4234 {
4235         struct option long_opts[] = {
4236 /* find { .val = 'A',   .name = "atime",        .has_arg = required_argument }*/
4237 /* find { .val = 'b',   .name = "blocks",       .has_arg = required_argument }*/
4238         { .val = LFS_COMP_COUNT_OPT,
4239                         .name = "comp-count",   .has_arg = no_argument },
4240         { .val = LFS_COMP_COUNT_OPT,
4241                 .name = "component-count",      .has_arg = no_argument },
4242         { .val = LFS_COMP_FLAGS_OPT,
4243                         .name = "comp-flags",   .has_arg = optional_argument },
4244         { .val = LFS_COMP_FLAGS_OPT,
4245                 .name = "component-flags",      .has_arg = optional_argument },
4246         { .val = LFS_COMP_START_OPT,
4247                         .name = "comp-start",   .has_arg = optional_argument },
4248         { .val = LFS_COMP_START_OPT,
4249                 .name = "component-start",      .has_arg = optional_argument },
4250         { .val = LFS_MIRROR_INDEX_OPT,
4251                 .name = "mirror-index",         .has_arg = required_argument },
4252         { .val = LFS_MIRROR_ID_OPT,
4253                 .name = "mirror-id",            .has_arg = required_argument },
4254         { .val = 'c',   .name = "stripe-count", .has_arg = no_argument },
4255         { .val = 'c',   .name = "stripe_count", .has_arg = no_argument },
4256 /* find { .val = 'C',   .name = "ctime",        .has_arg = required_argument }*/
4257         { .val = 'd',   .name = "directory",    .has_arg = no_argument },
4258         { .val = 'D',   .name = "default",      .has_arg = no_argument },
4259         { .val = 'E',   .name = "comp-end",     .has_arg = optional_argument },
4260         { .val = 'E',   .name = "component-end", .has_arg = optional_argument },
4261         { .val = 'F',   .name = "fid",          .has_arg = no_argument },
4262         { .val = 'g',   .name = "generation",   .has_arg = no_argument },
4263 /* find { .val = 'G',   .name = "group",        .has_arg = required_argument }*/
4264 /* dirstripe { .val = 'H', .name = "mdt-hash",  .has_arg = required_argument }*/
4265         { .val = 'i',   .name = "stripe-index", .has_arg = no_argument },
4266         { .val = 'i',   .name = "stripe_index", .has_arg = no_argument },
4267         { .val = 'I',   .name = "comp-id",      .has_arg = optional_argument },
4268         { .val = 'I',   .name = "component-id", .has_arg = optional_argument },
4269 /* find { .val = 'l',   .name = "lazy",         .has_arg = no_argument }, */
4270         { .val = 'L',   .name = "layout",       .has_arg = no_argument },
4271         { .val = 'm',   .name = "mdt",          .has_arg = no_argument },
4272         { .val = 'm',   .name = "mdt-index",    .has_arg = no_argument },
4273         { .val = 'm',   .name = "mdt_index",    .has_arg = no_argument },
4274 /* find { .val = 'M',   .name = "mtime",        .has_arg = required_argument }*/
4275 /* find { .val = 'n',   .name = "name",         .has_arg = required_argument }*/
4276         { .val = 'N',   .name = "mirror-count", .has_arg = no_argument },
4277         { .val = 'O',   .name = "obd",          .has_arg = required_argument },
4278         { .val = 'O',   .name = "ost",          .has_arg = required_argument },
4279         { .val = 'p',   .name = "pool",         .has_arg = no_argument },
4280 /* find { .val = 'P',   .name = "print",        .has_arg = no_argument }, */
4281         { .val = 'q',   .name = "quiet",        .has_arg = no_argument },
4282         { .val = 'r',   .name = "recursive",    .has_arg = no_argument },
4283         { .val = 'R',   .name = "raw",          .has_arg = no_argument },
4284         { .val = 'S',   .name = "stripe-size",  .has_arg = no_argument },
4285         { .val = 'S',   .name = "stripe_size",  .has_arg = no_argument },
4286 /* find { .val = 't',   .name = "type",         .has_arg = required_argument }*/
4287 /* dirstripe { .val = 'T', .name = "mdt-count", .has_arg = required_argument }*/
4288 /* find { .val = 'u',   .name = "uid",          .has_arg = required_argument }*/
4289 /* find { .val = 'U',   .name = "user",         .has_arg = required_argument }*/
4290         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
4291         { .val = 'y',   .name = "yaml",         .has_arg = no_argument },
4292         { .name = NULL } };
4293         int c, rc;
4294         int neg_opt = 0;
4295         int pathstart = -1, pathend = -1;
4296         int isoption;
4297         char *end, *tmp;
4298
4299         while ((c = getopt_long(argc, argv,
4300                         "-cdDE::FghiI::LmMNoO:pqrRsSvy",
4301                         long_opts, NULL)) != -1) {
4302                 if (neg_opt)
4303                         --neg_opt;
4304
4305                 /* '!' is part of option */
4306                 isoption = (c != 1) || (strcmp(optarg, "!") == 0);
4307                 if (!isoption && pathend != -1) {
4308                         fprintf(stderr,
4309                                 "error: %s: filename|dirname must either precede options or follow options\n",
4310                                 argv[0]);
4311                         return CMD_HELP;
4312                 }
4313                 if (!isoption && pathstart == -1)
4314                         pathstart = optind - 1;
4315                 if (isoption && pathstart != -1 && pathend == -1)
4316                         pathend = optind - 2;
4317
4318                 switch (c) {
4319                 case 1:
4320                         /* unknown: opt is "!" */
4321                         if (strcmp(optarg, "!") == 0)
4322                                 neg_opt = 2;
4323                         break;
4324                 case 'c':
4325                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
4326                                 param->fp_verbose |= VERBOSE_COUNT;
4327                                 param->fp_max_depth = 0;
4328                         }
4329                         break;
4330                 case LFS_COMP_COUNT_OPT:
4331                         param->fp_verbose |= VERBOSE_COMP_COUNT;
4332                         param->fp_max_depth = 0;
4333                         break;
4334                 case LFS_COMP_FLAGS_OPT:
4335                         if (optarg != NULL) {
4336                                 rc = comp_str2flags(optarg,
4337                                                     &param->fp_comp_flags,
4338                                                     &param->fp_comp_neg_flags);
4339                                 if (rc != 0) {
4340                                         fprintf(stderr, "error: %s bad "
4341                                                 "component flags '%s'.\n",
4342                                                 argv[0], optarg);
4343                                         return CMD_HELP;
4344                                 }
4345                                 param->fp_check_comp_flags = 1;
4346                         } else {
4347                                 param->fp_verbose |= VERBOSE_COMP_FLAGS;
4348                                 param->fp_max_depth = 0;
4349                         }
4350                         break;
4351                 case LFS_COMP_START_OPT:
4352                         if (optarg != NULL) {
4353                                 tmp = optarg;
4354                                 if (tmp[0] == '+') {
4355                                         param->fp_comp_start_sign = -1;
4356                                         tmp++;
4357                                 } else if (tmp[0] == '-') {
4358                                         param->fp_comp_start_sign = 1;
4359                                         tmp++;
4360                                 }
4361                                 rc = llapi_parse_size(tmp,
4362                                                 &param->fp_comp_start,
4363                                                 &param->fp_comp_start_units, 0);
4364                                 if (rc != 0) {
4365                                         fprintf(stderr, "error: %s bad "
4366                                                 "component start '%s'.\n",
4367                                                 argv[0], tmp);
4368                                         return CMD_HELP;
4369                                 } else {
4370                                         param->fp_check_comp_start = 1;
4371                                 }
4372                         } else {
4373                                 param->fp_verbose |= VERBOSE_COMP_START;
4374                                 param->fp_max_depth = 0;
4375                         }
4376                         break;
4377                 case LFS_MIRROR_INDEX_OPT:
4378                         if (optarg[0] == '+') {
4379                                 param->fp_mirror_index_sign = -1;
4380                                 optarg++;
4381                         } else if (optarg[0] == '-') {
4382                                 param->fp_mirror_index_sign = 1;
4383                                 optarg++;
4384                         }
4385
4386                         param->fp_mirror_index = strtoul(optarg, &end, 0);
4387                         if (*end != '\0' || (param->fp_mirror_index == 0 &&
4388                             param->fp_mirror_index_sign == 0 && neg_opt == 0)) {
4389                                 fprintf(stderr,
4390                                         "%s %s: invalid mirror index '%s'\n",
4391                                         progname, argv[0], optarg);
4392                                 return CMD_HELP;
4393                         }
4394                         if (param->fp_mirror_id != 0) {
4395                                 fprintf(stderr,
4396                                         "%s %s: can't specify both mirror index and mirror ID\n",
4397                                         progname, argv[0]);
4398                                 return CMD_HELP;
4399                         }
4400                         param->fp_check_mirror_index = 1;
4401                         param->fp_exclude_mirror_index = !!neg_opt;
4402                         break;
4403                 case LFS_MIRROR_ID_OPT:
4404                         if (optarg[0] == '+') {
4405                                 param->fp_mirror_id_sign = -1;
4406                                 optarg++;
4407                         } else if (optarg[0] == '-') {
4408                                 param->fp_mirror_id_sign = 1;
4409                                 optarg++;
4410                         }
4411
4412                         param->fp_mirror_id = strtoul(optarg, &end, 0);
4413                         if (*end != '\0' || (param->fp_mirror_id == 0 &&
4414                             param->fp_mirror_id_sign == 0 && neg_opt == 0)) {
4415                                 fprintf(stderr,
4416                                         "%s %s: invalid mirror ID '%s'\n",
4417                                         progname, argv[0], optarg);
4418                                 return CMD_HELP;
4419                         }
4420                         if (param->fp_mirror_index != 0) {
4421                                 fprintf(stderr,
4422                                         "%s %s: can't specify both mirror index and mirror ID\n",
4423                                         progname, argv[0]);
4424                                 return CMD_HELP;
4425                         }
4426                         param->fp_check_mirror_id = 1;
4427                         param->fp_exclude_mirror_id = !!neg_opt;
4428                         break;
4429                 case 'd':
4430                         param->fp_max_depth = 0;
4431                         break;
4432                 case 'D':
4433                         param->fp_get_default_lmv = 1;
4434                         break;
4435                 case 'E':
4436                         if (optarg != NULL) {
4437                                 tmp = optarg;
4438                                 if (tmp[0] == '+') {
4439                                         param->fp_comp_end_sign = -1;
4440                                         tmp++;
4441                                 } else if (tmp[0] == '-') {
4442                                         param->fp_comp_end_sign = 1;
4443                                         tmp++;
4444                                 }
4445
4446                                 if (arg_is_eof(tmp)) {
4447                                         param->fp_comp_end = LUSTRE_EOF;
4448                                         param->fp_comp_end_units = 1;
4449                                         rc = 0;
4450                                 } else {
4451                                         rc = llapi_parse_size(tmp,
4452                                                 &param->fp_comp_end,
4453                                                 &param->fp_comp_end_units, 0);
4454                                 }
4455                                 if (rc != 0) {
4456                                         fprintf(stderr, "error: %s bad "
4457                                                 "component end '%s'.\n",
4458                                                 argv[0], tmp);
4459                                         return CMD_HELP;
4460                                 }
4461                                 param->fp_check_comp_end = 1;
4462                         } else {
4463                                 param->fp_verbose |= VERBOSE_COMP_END;
4464                                 param->fp_max_depth = 0;
4465                         }
4466                         break;
4467                 case 'F':
4468                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
4469                                 param->fp_verbose |= VERBOSE_DFID;
4470                                 param->fp_max_depth = 0;
4471                         }
4472                         break;
4473                 case 'g':
4474                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
4475                                 param->fp_verbose |= VERBOSE_GENERATION;
4476                                 param->fp_max_depth = 0;
4477                         }
4478                         break;
4479                 case 'i':
4480                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
4481                                 param->fp_verbose |= VERBOSE_STRIPE_OFFSET;
4482                                 param->fp_max_depth = 0;
4483                         }
4484                         break;
4485                 case 'I':
4486                         if (optarg != NULL) {
4487                                 param->fp_comp_id = strtoul(optarg, &end, 0);
4488                                 if (*end != '\0' || param->fp_comp_id == 0 ||
4489                                     param->fp_comp_id > LCME_ID_MAX) {
4490                                         fprintf(stderr, "error: %s bad "
4491                                                 "component id '%s'\n",
4492                                                 argv[0], optarg);
4493                                         return CMD_HELP;
4494                                 } else {
4495                                         param->fp_check_comp_id = 1;
4496                                 }
4497                         } else {
4498                                 param->fp_max_depth = 0;
4499                                 param->fp_verbose |= VERBOSE_COMP_ID;
4500                         }
4501                         break;
4502                 case 'L':
4503                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
4504                                 param->fp_verbose |= VERBOSE_PATTERN;
4505                                 param->fp_max_depth = 0;
4506                         }
4507                         break;
4508 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
4509                 case 'M':
4510                         fprintf(stderr, "warning: '-M' deprecated"
4511                                 ", use '--mdt-index' or '-m' instead\n");
4512 #endif
4513                 case 'm':
4514                         if (!(param->fp_verbose & VERBOSE_DETAIL))
4515                                 param->fp_max_depth = 0;
4516                         param->fp_verbose |= VERBOSE_MDTINDEX;
4517                         break;
4518                 case 'N':
4519                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
4520                                 param->fp_verbose |= VERBOSE_MIRROR_COUNT;
4521                                 param->fp_max_depth = 0;
4522                         }
4523                         break;
4524                 case 'O':
4525                         if (param->fp_obd_uuid) {
4526                                 fprintf(stderr,
4527                                         "error: %s: only one obduuid allowed",
4528                                         argv[0]);
4529                                 return CMD_HELP;
4530                         }
4531                         param->fp_obd_uuid = (struct obd_uuid *)optarg;
4532                         break;
4533                 case 'p':
4534                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
4535                                 param->fp_verbose |= VERBOSE_POOL;
4536                                 param->fp_max_depth = 0;
4537                         }
4538                         break;
4539                 case 'q':
4540                         param->fp_quiet++;
4541                         break;
4542                 case 'r':
4543                         param->fp_recursive = 1;
4544                         break;
4545                 case 'R':
4546                         param->fp_raw = 1;
4547                         break;
4548                 case 'S':
4549                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
4550                                 param->fp_verbose |= VERBOSE_STRIPE_SIZE;
4551                                 param->fp_max_depth = 0;
4552                         }
4553                         break;
4554                 case 'v':
4555                         param->fp_verbose = VERBOSE_DEFAULT | VERBOSE_DETAIL;
4556                         break;
4557                 case 'y':
4558                         param->fp_yaml = 1;
4559                         break;
4560                 default:
4561                         return CMD_HELP;
4562                 }
4563         }
4564
4565         if (pathstart == -1) {
4566                 fprintf(stderr, "error: %s: no filename|pathname\n",
4567                                 argv[0]);
4568                 return CMD_HELP;
4569         } else if (pathend == -1) {
4570                 /* no options */
4571                 pathend = argc;
4572         }
4573
4574         if (pathend > argc)
4575                 return CMD_HELP;
4576
4577         if (param->fp_recursive)
4578                 param->fp_max_depth = -1;
4579         else if (param->fp_verbose & VERBOSE_DETAIL)
4580                 param->fp_max_depth = 1;
4581
4582         if (!param->fp_verbose)
4583                 param->fp_verbose = VERBOSE_DEFAULT;
4584         if (param->fp_quiet)
4585                 param->fp_verbose = VERBOSE_OBJID;
4586
4587         do {
4588                 rc = llapi_getstripe(argv[pathstart], param);
4589         } while (++pathstart < pathend && !rc);
4590
4591         if (rc)
4592                 fprintf(stderr, "error: %s failed for %s.\n",
4593                         argv[0], argv[optind - 1]);
4594         return rc;
4595 }
4596
4597 static int lfs_tgts(int argc, char **argv)
4598 {
4599         char mntdir[PATH_MAX] = {'\0'}, path[PATH_MAX] = {'\0'};
4600         struct find_param param;
4601         int index = 0, rc=0;
4602
4603         if (argc > 2)
4604                 return CMD_HELP;
4605
4606         if (argc == 2 && !realpath(argv[1], path)) {
4607                 rc = -errno;
4608                 fprintf(stderr, "error: invalid path '%s': %s\n",
4609                         argv[1], strerror(-rc));
4610                 return rc;
4611         }
4612
4613         while (!llapi_search_mounts(path, index++, mntdir, NULL)) {
4614                 /* Check if we have a mount point */
4615                 if (mntdir[0] == '\0')
4616                         continue;
4617
4618                 memset(&param, 0, sizeof(param));
4619                 if (!strcmp(argv[0], "mdts"))
4620                         param.fp_get_lmv = 1;
4621
4622                 rc = llapi_ostlist(mntdir, &param);
4623                 if (rc) {
4624                         fprintf(stderr, "error: %s: failed on %s\n",
4625                                 argv[0], mntdir);
4626                 }
4627                 if (path[0] != '\0')
4628                         break;
4629                 memset(mntdir, 0, PATH_MAX);
4630         }
4631
4632         return rc;
4633 }
4634
4635 static int lfs_getstripe(int argc, char **argv)
4636 {
4637         struct find_param param = { 0 };
4638
4639         param.fp_max_depth = 1;
4640         return lfs_getstripe_internal(argc, argv, &param);
4641 }
4642
4643 /* functions */
4644 static int lfs_getdirstripe(int argc, char **argv)
4645 {
4646         struct find_param param = { 0 };
4647         struct option long_opts[] = {
4648         { .val = 'c',   .name = "mdt-count",    .has_arg = no_argument },
4649         { .val = 'D',   .name = "default",      .has_arg = no_argument },
4650         { .val = 'H',   .name = "mdt-hash",     .has_arg = no_argument },
4651         { .val = 'i',   .name = "mdt-index",    .has_arg = no_argument },
4652         { .val = 'm',   .name = "mdt-index",    .has_arg = no_argument },
4653         { .val = 'O',   .name = "obd",          .has_arg = required_argument },
4654         { .val = 'r',   .name = "recursive",    .has_arg = no_argument },
4655         { .val = 'T',   .name = "mdt-count",    .has_arg = no_argument },
4656         { .val = 'y',   .name = "yaml",         .has_arg = no_argument },
4657         { .name = NULL } };
4658         int c, rc;
4659
4660         param.fp_get_lmv = 1;
4661
4662         while ((c = getopt_long(argc, argv,
4663                                 "cDHimO:rtTy", long_opts, NULL)) != -1)
4664         {
4665                 switch (c) {
4666                 case 'c':
4667                 case 'T':
4668                         param.fp_verbose |= VERBOSE_COUNT;
4669                         break;
4670                 case 'D':
4671                         param.fp_get_default_lmv = 1;
4672                         break;
4673                 case 'i':
4674                 case 'm':
4675                         param.fp_verbose |= VERBOSE_STRIPE_OFFSET;
4676                         break;
4677 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
4678                 case 't':
4679                         fprintf(stderr, "warning: '-t' deprecated, "
4680                                 "use '--mdt-hash' or '-H' instead\n");
4681 #endif
4682                 case 'H':
4683                         param.fp_verbose |= VERBOSE_HASH_TYPE;
4684                         break;
4685                 case 'O':
4686                         if (param.fp_obd_uuid) {
4687                                 fprintf(stderr,
4688                                         "error: %s: only one obduuid allowed",
4689                                         argv[0]);
4690                                 return CMD_HELP;
4691                         }
4692                         param.fp_obd_uuid = (struct obd_uuid *)optarg;
4693                         break;
4694                 case 'r':
4695                         param.fp_recursive = 1;
4696                         break;
4697                 case 'y':
4698                         param.fp_yaml = 1;
4699                         break;
4700                 default:
4701                         return CMD_HELP;
4702                 }
4703         }
4704
4705         if (optind >= argc)
4706                 return CMD_HELP;
4707
4708         if (param.fp_recursive)
4709                 param.fp_max_depth = -1;
4710
4711         if (!param.fp_verbose)
4712                 param.fp_verbose = VERBOSE_DEFAULT;
4713
4714         do {
4715                 rc = llapi_getstripe(argv[optind], &param);
4716         } while (++optind < argc && !rc);
4717
4718         if (rc)
4719                 fprintf(stderr, "error: %s failed for %s.\n",
4720                         argv[0], argv[optind - 1]);
4721         return rc;
4722 }
4723
4724 enum mntdf_flags {
4725         MNTDF_INODES    = 0x0001,
4726         MNTDF_COOKED    = 0x0002,
4727         MNTDF_LAZY      = 0x0004,
4728         MNTDF_VERBOSE   = 0x0008,
4729         MNTDF_SHOW      = 0x0010,
4730 };
4731
4732 #define COOK(value)                                             \
4733 ({                                                              \
4734         int radix = 0;                                          \
4735         while (value > 1024) {                                  \
4736                 value /= 1024;                                  \
4737                 radix++;                                        \
4738         }                                                       \
4739         radix;                                                  \
4740 })
4741 #define UUF     "%-20s"
4742 #define CSF     "%11s"
4743 #define CDF     "%11llu"
4744 #define HDF     "%8.1f%c"
4745 #define RSF     "%4s"
4746 #define RDF     "%3d%%"
4747
4748 static inline int obd_statfs_ratio(const struct obd_statfs *st, bool inodes)
4749 {
4750         double avail, used, ratio = 0;
4751
4752         if (inodes) {
4753                 avail = st->os_ffree;
4754                 used = st->os_files - st->os_ffree;
4755         } else {
4756                 avail = st->os_bavail;
4757                 used = st->os_blocks - st->os_bfree;
4758         }
4759         if (avail + used > 0)
4760                 ratio = used / (used + avail) * 100;
4761
4762         /* Round up to match df(1) usage percentage */
4763         return (ratio - (int)ratio) > 0 ? (int)(ratio + 1) : (int)ratio;
4764 }
4765
4766 /* This is to identify various problem states for "lfs df" if .osn_err = true,
4767  * so only show flags reflecting those states by default. Informational states
4768  * are only shown with "-v" and use lower-case names to distinguish them.
4769  * UNUSED[12] were for "EROFS = 30" until 1.6 but are now available for use.
4770  */
4771 static struct obd_statfs_state_names {
4772         enum obd_statfs_state   osn_state;
4773         const char              osn_name;
4774         bool                    osn_err;
4775 } oss_names[] = {
4776         { .osn_state = OS_STATE_DEGRADED,    .osn_name = 'D', .osn_err = true },
4777         { .osn_state = OS_STATE_READONLY,    .osn_name = 'R', .osn_err = true },
4778         { .osn_state = OS_STATE_NOPRECREATE, .osn_name = 'N', .osn_err = true },
4779         { .osn_state = OS_STATE_UNUSED1,     .osn_name = '?', .osn_err = true },
4780         { .osn_state = OS_STATE_UNUSED2,     .osn_name = '?', .osn_err = true },
4781         { .osn_state = OS_STATE_ENOSPC,      .osn_name = 'S', .osn_err = true },
4782         { .osn_state = OS_STATE_ENOINO,      .osn_name = 'I', .osn_err = true },
4783         { .osn_state = OS_STATE_SUM,         .osn_name = 'a', /* aggregate */ },
4784         { .osn_state = OS_STATE_NONROT,      .osn_name = 'f', /* flash */     },
4785 };
4786
4787 static int showdf(char *mntdir, struct obd_statfs *stat,
4788                   char *uuid, enum mntdf_flags flags,
4789                   char *type, int index, int rc)
4790 {
4791         long long avail, used, total;
4792         int ratio = 0;
4793         char *suffix = "KMGTPEZY";
4794         /* Note if we have >2^64 bytes/fs these buffers will need to be grown */
4795         char tbuf[3 * sizeof(__u64)];
4796         char ubuf[3 * sizeof(__u64)];
4797         char abuf[3 * sizeof(__u64)];
4798         char rbuf[3 * sizeof(__u64)];
4799
4800         if (!uuid || !stat)
4801                 return -EINVAL;
4802
4803         switch (rc) {
4804         case 0:
4805                 if (flags & MNTDF_INODES) {
4806                         avail = stat->os_ffree;
4807                         used = stat->os_files - stat->os_ffree;
4808                         total = stat->os_files;
4809                 } else {
4810                         int shift = flags & MNTDF_COOKED ? 0 : 10;
4811
4812                         avail = (stat->os_bavail * stat->os_bsize) >> shift;
4813                         used  = ((stat->os_blocks - stat->os_bfree) *
4814                                  stat->os_bsize) >> shift;
4815                         total = (stat->os_blocks * stat->os_bsize) >> shift;
4816                 }
4817
4818                 ratio = obd_statfs_ratio(stat, flags & MNTDF_INODES);
4819
4820                 if (flags & MNTDF_COOKED) {
4821                         int i;
4822                         double cook_val;
4823
4824                         cook_val = (double)total;
4825                         i = COOK(cook_val);
4826                         if (i > 0)
4827                                 snprintf(tbuf, sizeof(tbuf), HDF, cook_val,
4828                                          suffix[i - 1]);
4829                         else
4830                                 snprintf(tbuf, sizeof(tbuf), CDF, total);
4831
4832                         cook_val = (double)used;
4833                         i = COOK(cook_val);
4834                         if (i > 0)
4835                                 snprintf(ubuf, sizeof(ubuf), HDF, cook_val,
4836                                          suffix[i - 1]);
4837                         else
4838                                 snprintf(ubuf, sizeof(ubuf), CDF, used);
4839
4840                         cook_val = (double)avail;
4841                         i = COOK(cook_val);
4842                         if (i > 0)
4843                                 snprintf(abuf, sizeof(abuf), HDF, cook_val,
4844                                          suffix[i - 1]);
4845                         else
4846                                 snprintf(abuf, sizeof(abuf), CDF, avail);
4847                 } else {
4848                         snprintf(tbuf, sizeof(tbuf), CDF, total);
4849                         snprintf(ubuf, sizeof(tbuf), CDF, used);
4850                         snprintf(abuf, sizeof(tbuf), CDF, avail);
4851                 }
4852
4853                 sprintf(rbuf, RDF, ratio);
4854                 printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s",
4855                        uuid, tbuf, ubuf, abuf, rbuf, mntdir);
4856                 if (type)
4857                         printf("[%s:%d]", type, index);
4858
4859                 if (stat->os_state) {
4860                         uint32_t i;
4861
4862                         printf(" ");
4863                         for (i = 0; i < ARRAY_SIZE(oss_names); i++) {
4864                                 if (oss_names[i].osn_state & stat->os_state &&
4865                                     (oss_names[i].osn_err ||
4866                                      flags & MNTDF_VERBOSE))
4867                                         printf("%c", oss_names[i].osn_name);
4868                         }
4869                 }
4870
4871                 printf("\n");
4872                 break;
4873         case -ENODATA:
4874                 printf(UUF": inactive device\n", uuid);
4875                 break;
4876         default:
4877                 printf(UUF": %s\n", uuid, strerror(-rc));
4878                 break;
4879         }
4880
4881         return 0;
4882 }
4883
4884 struct ll_stat_type {
4885         int   st_op;
4886         char *st_name;
4887 };
4888
4889 #define LL_STATFS_MAX   LOV_MAX_STRIPE_COUNT
4890
4891 struct ll_statfs_data {
4892         int                     sd_index;
4893         struct obd_statfs       sd_st;
4894 };
4895
4896 struct ll_statfs_buf {
4897         int                     sb_count;
4898         struct ll_statfs_data   sb_buf[LL_STATFS_MAX];
4899 };
4900
4901 static int mntdf(char *mntdir, char *fsname, char *pool, enum mntdf_flags flags,
4902                  int ops, struct ll_statfs_buf *lsb)
4903 {
4904         struct obd_statfs stat_buf, sum = { .os_bsize = 1 };
4905         struct obd_uuid uuid_buf;
4906         char *poolname = NULL;
4907         struct ll_stat_type types[] = {
4908                 { .st_op = LL_STATFS_LMV,       .st_name = "MDT" },
4909                 { .st_op = LL_STATFS_LOV,       .st_name = "OST" },
4910                 { .st_name = NULL } };
4911         struct ll_stat_type *tp;
4912         __u64 ost_files = 0;
4913         __u64 ost_ffree = 0;
4914         __u32 index;
4915         __u32 type;
4916         int fd;
4917         int rc = 0;
4918         int rc2;
4919
4920         if (pool) {
4921                 poolname = strchr(pool, '.');
4922                 if (poolname != NULL) {
4923                         if (strncmp(fsname, pool, strlen(fsname))) {
4924                                 fprintf(stderr, "filesystem name incorrect\n");
4925                                 return -ENODEV;
4926                         }
4927                         poolname++;
4928                 } else
4929                         poolname = pool;
4930         }
4931
4932         fd = open(mntdir, O_RDONLY);
4933         if (fd < 0) {
4934                 rc = -errno;
4935                 fprintf(stderr, "%s: cannot open '%s': %s\n", progname, mntdir,
4936                         strerror(errno));
4937                 return rc;
4938         }
4939
4940         if (flags & MNTDF_SHOW) {
4941                 if (flags & MNTDF_INODES)
4942                         printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s\n",
4943                                "UUID", "Inodes", "IUsed", "IFree",
4944                                "IUse%", "Mounted on");
4945                 else
4946                         printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s\n",
4947                                "UUID",
4948                                flags & MNTDF_COOKED ? "bytes" : "1K-blocks",
4949                                "Used", "Available", "Use%", "Mounted on");
4950         }
4951
4952         for (tp = types; tp->st_name != NULL; tp++) {
4953                 bool have_ost = false;
4954
4955                 if (!(tp->st_op & ops))
4956                         continue;
4957
4958                 for (index = 0; ; index++) {
4959                         memset(&stat_buf, 0, sizeof(struct obd_statfs));
4960                         memset(&uuid_buf, 0, sizeof(struct obd_uuid));
4961                         type = flags & MNTDF_LAZY ?
4962                                 tp->st_op | LL_STATFS_NODELAY : tp->st_op;
4963                         rc2 = llapi_obd_fstatfs(fd, type, index,
4964                                                &stat_buf, &uuid_buf);
4965                         if (rc2 == -ENODEV)
4966                                 break;
4967                         if (rc2 == -EAGAIN)
4968                                 continue;
4969                         if (rc2 == -ENODATA) { /* Inactive device, OK. */
4970                                 if (!(flags & MNTDF_VERBOSE))
4971                                         continue;
4972                         } else if (rc2 < 0 && rc == 0) {
4973                                 rc = rc2;
4974                         }
4975
4976                         /* If we have OSTs then don't report MDT block counts.
4977                          * For MDT-only filesystems the expectation is that all
4978                          * layouts have a DoM component.  For filesystems with
4979                          * OSTs, files are not necessarily going to store data
4980                          * on MDTs, and MDT space is limited to a fraction of
4981                          * OST space, so don't include it in the summary.
4982                          */
4983                         if (tp->st_op == LL_STATFS_LOV && !have_ost) {
4984                                 have_ost = true;
4985                                 sum.os_blocks = 0;
4986                                 sum.os_bfree = 0;
4987                                 sum.os_bavail = 0;
4988                         }
4989
4990                         if (poolname && tp->st_op == LL_STATFS_LOV &&
4991                             llapi_search_ost(fsname, poolname,
4992                                              obd_uuid2str(&uuid_buf)) != 1)
4993                                 continue;
4994
4995                         /* the llapi_obd_statfs() call may have returned with
4996                          * an error, but if it filled in uuid_buf we will at
4997                          * lease use that to print out a message for that OBD.
4998                          * If we didn't get anything in the uuid_buf, then fill
4999                          * it in so that we can print an error message. */
5000                         if (uuid_buf.uuid[0] == '\0')
5001                                 snprintf(uuid_buf.uuid, sizeof(uuid_buf.uuid),
5002                                          "%s%04x", tp->st_name, index);
5003                         if (!rc && lsb) {
5004                                 lsb->sb_buf[lsb->sb_count].sd_index = index;
5005                                 lsb->sb_buf[lsb->sb_count].sd_st = stat_buf;
5006                                 lsb->sb_count++;
5007                         }
5008                         if (flags & MNTDF_SHOW)
5009                                 showdf(mntdir, &stat_buf,
5010                                        obd_uuid2str(&uuid_buf), flags,
5011                                        tp->st_name, index, rc2);
5012
5013                         if (rc2)
5014                                 continue;
5015
5016                         if (tp->st_op == LL_STATFS_LMV) {
5017                                 sum.os_ffree += stat_buf.os_ffree;
5018                                 sum.os_files += stat_buf.os_files;
5019                         } else /* if (tp->st_op == LL_STATFS_LOV) */ {
5020                                 ost_files += stat_buf.os_files;
5021                                 ost_ffree += stat_buf.os_ffree;
5022                         }
5023                         sum.os_blocks += stat_buf.os_blocks *
5024                                          stat_buf.os_bsize;
5025                         sum.os_bfree  += stat_buf.os_bfree *
5026                                          stat_buf.os_bsize;
5027                         sum.os_bavail += stat_buf.os_bavail *
5028                                          stat_buf.os_bsize;
5029                 }
5030         }
5031
5032         close(fd);
5033
5034         /* If we have _some_ OSTs, but don't have as many free objects on the
5035          * OST as inodes on the MDTs, reduce the reported number of inodes
5036          * to compensate, so that the "inodes in use" number is correct.
5037          * This should be kept in sync with ll_statfs_internal().
5038          */
5039         if (ost_files && ost_ffree < sum.os_ffree) {
5040                 sum.os_files = (sum.os_files - sum.os_ffree) + ost_ffree;
5041                 sum.os_ffree = ost_ffree;
5042         }
5043         if (flags & MNTDF_SHOW) {
5044                 printf("\n");
5045                 showdf(mntdir, &sum, "filesystem_summary:", flags, NULL, 0, 0);
5046                 printf("\n");
5047         }
5048
5049         return rc;
5050 }
5051
5052 static int ll_statfs_data_comp(const void *sd1, const void *sd2)
5053 {
5054         const struct obd_statfs *st1 = &((const struct ll_statfs_data *)sd1)->
5055                                                 sd_st;
5056         const struct obd_statfs *st2 = &((const struct ll_statfs_data *)sd2)->
5057                                                 sd_st;
5058         int r1 = obd_statfs_ratio(st1, false);
5059         int r2 = obd_statfs_ratio(st2, false);
5060         int64_t result = r1 - r2;
5061
5062         /* if both space usage are above 90, compare free inodes */
5063         if (r1 > 90 && r2 > 90)
5064                 result = st2->os_ffree - st1->os_ffree;
5065
5066         if (result < 0)
5067                 return -1;
5068         else if (result == 0)
5069                 return 0;
5070         else
5071                 return 1;
5072 }
5073
5074 /* functions */
5075 static int lfs_setdirstripe(int argc, char **argv)
5076 {
5077         char                    *dname;
5078         int                     result;
5079         struct lfs_setstripe_args        lsa = { 0 };
5080         struct llapi_stripe_param       *param = NULL;
5081         __u32                   mdts[LMV_MAX_STRIPE_COUNT] = { 0 };
5082         char                    *end;
5083         int                     c;
5084         char                    *mode_opt = NULL;
5085         bool                    default_stripe = false;
5086         mode_t                  mode = S_IRWXU | S_IRWXG | S_IRWXO;
5087         mode_t                  previous_mode = 0;
5088         bool                    delete = false;
5089         struct ll_statfs_buf    *lsb = NULL;
5090         char                    mntdir[PATH_MAX] = "";
5091         bool                    auto_distributed = false;
5092
5093         struct option long_opts[] = {
5094         { .val = 'c',   .name = "count",        .has_arg = required_argument },
5095         { .val = 'c',   .name = "mdt-count",    .has_arg = required_argument },
5096         { .val = 'd',   .name = "delete",       .has_arg = no_argument },
5097         { .val = 'D',   .name = "default",      .has_arg = no_argument },
5098         { .val = 'D',   .name = "default_stripe", .has_arg = no_argument },
5099         { .val = 'H',   .name = "mdt-hash",     .has_arg = required_argument },
5100         { .val = 'i',   .name = "mdt-index",    .has_arg = required_argument },
5101 /* find { .val = 'l',   .name = "lazy",         .has_arg = no_argument }, */
5102 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
5103         { .val = 'i',   .name = "index",        .has_arg = required_argument },
5104 #endif
5105         { .val = 'o',   .name = "mode",         .has_arg = required_argument },
5106 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
5107         { .val = 't',   .name = "hash-type",    .has_arg = required_argument },
5108 #endif
5109         { .val = 'T',   .name = "mdt-count",    .has_arg = required_argument },
5110 /* setstripe { .val = 'y', .name = "yaml",      .has_arg = no_argument }, */
5111         { .name = NULL } };
5112
5113         setstripe_args_init(&lsa);
5114
5115         while ((c = getopt_long(argc, argv, "c:dDi:H:m:o:t:T:", long_opts,
5116                                 NULL)) >= 0) {
5117                 switch (c) {
5118                 case 0:
5119                         /* Long options. */
5120                         break;
5121                 case 'c':
5122                 case 'T':
5123                         lsa.lsa_stripe_count = strtoul(optarg, &end, 0);
5124                         if (*end != '\0') {
5125                                 fprintf(stderr,
5126                                         "%s %s: invalid stripe count '%s'\n",
5127                                         progname, argv[0], optarg);
5128                                 return CMD_HELP;
5129                         }
5130                         break;
5131                 case 'd':
5132                         delete = true;
5133                         default_stripe = true;
5134                         break;
5135                 case 'D':
5136                         default_stripe = true;
5137                         break;
5138 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
5139                 case 't':
5140                         fprintf(stderr, "warning: '--hash-type' and '-t' "
5141                               "deprecated, use '--mdt-hash' or '-H' instead\n");
5142 #endif
5143                 case 'H':
5144                         lsa.lsa_pattern = check_hashtype(optarg);
5145                         if (lsa.lsa_pattern == 0) {
5146                                 fprintf(stderr,
5147                                         "%s %s: bad stripe hash type '%s'\n",
5148                                         progname, argv[0], optarg);
5149                                 return CMD_HELP;
5150                         }
5151                         break;
5152                 case 'i':
5153 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
5154                         if (strcmp(argv[optind - 1], "--index") == 0)
5155                                 fprintf(stderr,
5156                                         "%s %s: warning: '--index' deprecated, use '--mdt-index' instead\n",
5157                                         progname, argv[0]);
5158 #endif
5159                         lsa.lsa_nr_tgts = parse_targets(mdts,
5160                                                 sizeof(mdts) / sizeof(__u32),
5161                                                 lsa.lsa_nr_tgts, optarg);
5162                         if (lsa.lsa_nr_tgts < 0) {
5163                                 fprintf(stderr,
5164                                         "%s %s: invalid MDT target(s) '%s'\n",
5165                                         progname, argv[0], optarg);
5166                                 return CMD_HELP;
5167                         }
5168
5169                         lsa.lsa_tgts = mdts;
5170                         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
5171                                 lsa.lsa_stripe_off = mdts[0];
5172                         break;
5173 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 16, 53, 0)
5174                 case 'm':
5175                         fprintf(stderr, "warning: '-m' is deprecated, "
5176                                 "use '--mode' or '-o' instead\n");
5177 #endif
5178                 case 'o':
5179                         mode_opt = optarg;
5180                         break;
5181                 default:
5182                         fprintf(stderr, "%s %s: unrecognized option '%s'\n",
5183                                 progname, argv[0], argv[optind - 1]);
5184                         return CMD_HELP;
5185                 }
5186         }
5187
5188         if (optind == argc) {
5189                 fprintf(stderr, "%s %s: DIR must be specified\n",
5190                         progname, argv[0]);
5191                 return CMD_HELP;
5192         }
5193
5194         if (!delete && lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT &&
5195             lsa.lsa_stripe_count == LLAPI_LAYOUT_DEFAULT) {
5196                 fprintf(stderr,
5197                         "%s %s: stripe offset and count must be specified\n",
5198                         progname, argv[0]);
5199                 return CMD_HELP;
5200         }
5201
5202         if (delete &&
5203             (lsa.lsa_stripe_off != LLAPI_LAYOUT_DEFAULT ||
5204              lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT)) {
5205                 fprintf(stderr,
5206                         "%s %s: cannot specify -d with -c or -i options\n",
5207                         progname, argv[0]);
5208                 return CMD_HELP;
5209         }
5210
5211         if (mode_opt != NULL) {
5212                 mode = strtoul(mode_opt, &end, 8);
5213                 if (*end != '\0') {
5214                         fprintf(stderr,
5215                                 "%s %s: bad MODE '%s'\n",
5216                                 progname, argv[0], mode_opt);
5217                         return CMD_HELP;
5218                 }
5219                 previous_mode = umask(0);
5220         }
5221
5222         /*
5223          * initialize stripe parameters, in case param is converted to specific,
5224          * i.e, 'lfs mkdir -i -1 -c N', always allocate space for lsp_tgts.
5225          */
5226         param = calloc(1, offsetof(typeof(*param),
5227                        lsp_tgts[lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT ?
5228                                 lsa.lsa_stripe_count : lsa.lsa_nr_tgts]));
5229         if (param == NULL) {
5230                 fprintf(stderr,
5231                         "%s %s: cannot allocate memory for parameters: %s\n",
5232                         progname, argv[0], strerror(ENOMEM));
5233                 return CMD_HELP;
5234         }
5235
5236         if (lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT)
5237                 param->lsp_stripe_count = lsa.lsa_stripe_count;
5238         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
5239                 param->lsp_stripe_offset = -1;
5240         else
5241                 param->lsp_stripe_offset = lsa.lsa_stripe_off;
5242         if (lsa.lsa_pattern != LLAPI_LAYOUT_RAID0)
5243                 param->lsp_stripe_pattern = lsa.lsa_pattern;
5244         else
5245                 param->lsp_stripe_pattern = LMV_HASH_TYPE_FNV_1A_64;
5246         param->lsp_pool = lsa.lsa_pool_name;
5247         param->lsp_is_specific = false;
5248         if (lsa.lsa_nr_tgts > 1) {
5249                 if (lsa.lsa_stripe_count > 0 &&
5250                     lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT &&
5251                     lsa.lsa_stripe_count != lsa.lsa_nr_tgts) {
5252                         fprintf(stderr,
5253                                 "error: %s: stripe count %lld doesn't match the number of MDTs: %d\n",
5254                                 argv[0], lsa.lsa_stripe_count,
5255                                 lsa.lsa_nr_tgts);
5256                         free(param);
5257                         return CMD_HELP;
5258                 }
5259
5260                 param->lsp_is_specific = true;
5261                 param->lsp_stripe_count = lsa.lsa_nr_tgts;
5262                 memcpy(param->lsp_tgts, mdts, sizeof(*mdts) * lsa.lsa_nr_tgts);
5263         }
5264
5265         dname = argv[optind];
5266         do {
5267                 if (default_stripe) {
5268                         result = llapi_dir_set_default_lmv(dname, param);
5269                 } else {
5270                         /* if current \a dname isn't under the same \a mntdir
5271                          * as the last one, and the last one was
5272                          * auto-distributed, restore \a param.
5273                          */
5274                         if (mntdir[0] != '\0' &&
5275                             strncmp(dname, mntdir, strlen(mntdir)) &&
5276                             auto_distributed) {
5277                                 param->lsp_is_specific = false;
5278                                 param->lsp_stripe_offset = -1;
5279                                 auto_distributed = false;
5280                         }
5281
5282                         if (!param->lsp_is_specific &&
5283                             param->lsp_stripe_offset == -1) {
5284                                 char path[PATH_MAX] = "";
5285
5286                                 if (!lsb) {
5287                                         lsb = malloc(sizeof(*lsb));
5288                                         if (!lsb) {
5289                                                 result = -ENOMEM;
5290                                                 break;
5291                                         }
5292                                 }
5293                                 lsb->sb_count = 0;
5294
5295                                 /* use mntdir for dirname() temporarily */
5296                                 strncpy(mntdir, dname, sizeof(mntdir) - 1);
5297                                 if (!realpath(dirname(mntdir), path)) {
5298                                         result = -errno;
5299                                         fprintf(stderr,
5300                                                 "error: invalid path '%s': %s\n",
5301                                                 argv[optind], strerror(errno));
5302                                         break;
5303                                 }
5304                                 mntdir[0] = '\0';
5305
5306                                 result = llapi_search_mounts(path, 0, mntdir,
5307                                                              NULL);
5308                                 if (result < 0 || mntdir[0] == '\0') {
5309                                         fprintf(stderr,
5310                                                 "No suitable Lustre mount found\n");
5311                                         break;
5312                                 }
5313
5314                                 result = mntdf(mntdir, NULL, NULL, 0,
5315                                                LL_STATFS_LMV, lsb);
5316                                 if (result < 0)
5317                                         break;
5318
5319                                 if (param->lsp_stripe_count > lsb->sb_count) {
5320                                         fprintf(stderr,
5321                                                 "error: stripe count %d is too big\n",
5322                                                 param->lsp_stripe_count);
5323                                         result = -ERANGE;
5324                                         break;
5325                                 }
5326
5327                                 qsort(lsb->sb_buf, lsb->sb_count,
5328                                       sizeof(struct ll_statfs_data),
5329                                       ll_statfs_data_comp);
5330
5331                                 auto_distributed = true;
5332                         }
5333
5334                         if (auto_distributed) {
5335                                 int r;
5336                                 int nr = MAX(param->lsp_stripe_count,
5337                                              lsb->sb_count / 2);
5338
5339                                 /* don't use server whose usage is above 90% */
5340                                 while (nr != param->lsp_stripe_count &&
5341                                        obd_statfs_ratio(&lsb->sb_buf[nr].sd_st,
5342                                                         false) > 90)
5343                                         nr = MAX(param->lsp_stripe_count,
5344                                                  nr / 2);
5345
5346                                 /* get \a r between [0, nr) */
5347                                 r = rand() % nr;
5348
5349                                 param->lsp_stripe_offset =
5350                                         lsb->sb_buf[r].sd_index;
5351                                 if (param->lsp_stripe_count > 1) {
5352                                         int i = 0;
5353
5354                                         param->lsp_is_specific = true;
5355                                         for (; i < param->lsp_stripe_count; i++)
5356                                                 param->lsp_tgts[(i + r) % nr] =
5357                                                         lsb->sb_buf[i].sd_index;
5358                                 }
5359                         }
5360
5361                         result = llapi_dir_create(dname, mode, param);
5362                 }
5363
5364                 if (result) {
5365                         fprintf(stderr,
5366                                 "%s setdirstripe: cannot create stripe dir '%s': %s\n",
5367                                 progname, dname, strerror(-result));
5368                         break;
5369                 }
5370                 dname = argv[++optind];
5371         } while (dname != NULL);
5372
5373         if (mode_opt != NULL)
5374                 umask(previous_mode);
5375
5376         free(lsb);
5377         free(param);
5378         return result;
5379 }
5380
5381 /* functions */
5382 static int lfs_rmentry(int argc, char **argv)
5383 {
5384         char *dname;
5385         int   index;
5386         int   result = 0;
5387
5388         if (argc <= 1) {
5389                 fprintf(stderr, "error: %s: missing dirname\n",
5390                         argv[0]);
5391                 return CMD_HELP;
5392         }
5393
5394         index = 1;
5395         dname = argv[index];
5396         while (dname != NULL) {
5397                 result = llapi_direntry_remove(dname);
5398                 if (result) {
5399                         fprintf(stderr, "error: %s: remove dir entry '%s' "
5400                                 "failed\n", argv[0], dname);
5401                         break;
5402                 }
5403                 dname = argv[++index];
5404         }
5405         return result;
5406 }
5407
5408 static int lfs_mv(int argc, char **argv)
5409 {
5410         struct lmv_user_md lmu = { LMV_USER_MAGIC };
5411         struct find_param param = {
5412                 .fp_max_depth = -1,
5413                 .fp_mdt_index = -1,
5414         };
5415         char *end;
5416         int c;
5417         int rc = 0;
5418         struct option long_opts[] = {
5419         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument },
5420         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
5421         { .name = NULL } };
5422
5423         while ((c = getopt_long(argc, argv, "m:M:v", long_opts, NULL)) != -1) {
5424                 switch (c) {
5425 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
5426                 case 'M':
5427                         fprintf(stderr, "warning: '-M' deprecated"
5428                                 ", use '--mdt-index' or '-m' instead\n");
5429 #endif
5430                 case 'm':
5431                         lmu.lum_stripe_offset = strtoul(optarg, &end, 0);
5432                         if (*end != '\0') {
5433                                 fprintf(stderr, "%s mv: bad MDT index '%s'\n",
5434                                         progname, optarg);
5435                                 return CMD_HELP;
5436                         }
5437                         break;
5438                 case 'v':
5439                         param.fp_verbose = VERBOSE_DETAIL;
5440                         break;
5441                 default:
5442                         fprintf(stderr, "%s mv: unrecognized option '%s'\n",
5443                                 progname, argv[optind - 1]);
5444                         return CMD_HELP;
5445                 }
5446         }
5447
5448         if (lmu.lum_stripe_offset == -1) {
5449                 fprintf(stderr, "%s mv: MDT index must be specified\n",
5450                         progname);
5451                 return CMD_HELP;
5452         }
5453
5454         if (optind >= argc) {
5455                 fprintf(stderr, "%s mv: DIR must be specified\n", progname);
5456                 return CMD_HELP;
5457         }
5458
5459
5460         /* initialize migrate mdt parameters */
5461         param.fp_lmv_md = &lmu;
5462         param.fp_migrate = 1;
5463         rc = llapi_migrate_mdt(argv[optind], &param);
5464         if (rc != 0)
5465                 fprintf(stderr, "%s mv: cannot migrate '%s' to MDT%04x: %s\n",
5466                         progname, argv[optind], param.fp_mdt_index,
5467                         strerror(-rc));
5468         return rc;
5469 }
5470
5471 static int lfs_osts(int argc, char **argv)
5472 {
5473         return lfs_tgts(argc, argv);
5474 }
5475
5476 static int lfs_mdts(int argc, char **argv)
5477 {
5478         return lfs_tgts(argc, argv);
5479 }
5480
5481 static int lfs_df(int argc, char **argv)
5482 {
5483         char mntdir[PATH_MAX] = {'\0'}, path[PATH_MAX] = {'\0'};
5484         enum mntdf_flags flags = MNTDF_SHOW;
5485         int ops = LL_STATFS_LMV | LL_STATFS_LOV;
5486         int c, rc = 0, index = 0;
5487         char fsname[PATH_MAX] = "", *pool_name = NULL;
5488         struct option long_opts[] = {
5489         { .val = 'h',   .name = "human-readable",
5490                                                 .has_arg = no_argument },
5491         { .val = 'i',   .name = "inodes",       .has_arg = no_argument },
5492         { .val = 'l',   .name = "lazy",         .has_arg = no_argument },
5493         { .val = 'p',   .name = "pool",         .has_arg = required_argument },
5494         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
5495         { .name = NULL} };
5496
5497         while ((c = getopt_long(argc, argv, "hilp:v", long_opts, NULL)) != -1) {
5498                 switch (c) {
5499                 case 'h':
5500                         flags |= MNTDF_COOKED;
5501                         break;
5502                 case 'i':
5503                         flags |= MNTDF_INODES;
5504                         break;
5505                 case 'l':
5506                         flags |= MNTDF_LAZY;
5507                         break;
5508                 case 'p':
5509                         pool_name = optarg;
5510                         break;
5511                 case 'v':
5512                         flags |= MNTDF_VERBOSE;
5513                         break;
5514                 default:
5515                         return CMD_HELP;
5516                 }
5517         }
5518         if (optind < argc && !realpath(argv[optind], path)) {
5519                 rc = -errno;
5520                 fprintf(stderr, "error: invalid path '%s': %s\n",
5521                         argv[optind], strerror(-rc));
5522                 return rc;
5523         }
5524
5525         while (!llapi_search_mounts(path, index++, mntdir, fsname)) {
5526                 /* Check if we have a mount point */
5527                 if (mntdir[0] == '\0')
5528                         continue;
5529
5530                 rc = mntdf(mntdir, fsname, pool_name, flags, ops, NULL);
5531                 if (rc || path[0] != '\0')
5532                         break;
5533                 fsname[0] = '\0'; /* avoid matching in next loop */
5534                 mntdir[0] = '\0'; /* avoid matching in next loop */
5535         }
5536
5537         return rc;
5538 }
5539
5540 static int lfs_getname(int argc, char **argv)
5541 {
5542         char mntdir[PATH_MAX] = "", path[PATH_MAX] = "", fsname[PATH_MAX] = "";
5543         int rc = 0, index = 0, c;
5544         char buf[sizeof(struct obd_uuid)];
5545
5546         while ((c = getopt(argc, argv, "h")) != -1)
5547                 return CMD_HELP;
5548
5549         if (optind == argc) { /* no paths specified, get all paths. */
5550                 while (!llapi_search_mounts(path, index++, mntdir, fsname)) {
5551                         rc = llapi_getname(mntdir, buf, sizeof(buf));
5552                         if (rc < 0) {
5553                                 fprintf(stderr,
5554                                         "cannot get name for `%s': %s\n",
5555                                         mntdir, strerror(-rc));
5556                                 break;
5557                         }
5558
5559                         printf("%s %s\n", buf, mntdir);
5560
5561                         path[0] = fsname[0] = mntdir[0] = 0;
5562                 }
5563         } else { /* paths specified, only attempt to search these. */
5564                 for (; optind < argc; optind++) {
5565                         rc = llapi_getname(argv[optind], buf, sizeof(buf));
5566                         if (rc < 0) {
5567                                 fprintf(stderr,
5568                                         "cannot get name for `%s': %s\n",
5569                                         argv[optind], strerror(-rc));
5570                                 break;
5571                         }
5572
5573                         printf("%s %s\n", buf, argv[optind]);
5574                 }
5575         }
5576         return rc;
5577 }
5578
5579 static int lfs_check(int argc, char **argv)
5580 {
5581         int rc;
5582         char mntdir[PATH_MAX] = {'\0'};
5583         int num_types = 1;
5584         char *obd_types[2];
5585         char obd_type1[4];
5586         char obd_type2[4];
5587
5588         if (argc != 2) {
5589                 fprintf(stderr, "%s check: server type must be specified\n",
5590                         progname);
5591                 return CMD_HELP;
5592         }
5593
5594         obd_types[0] = obd_type1;
5595         obd_types[1] = obd_type2;
5596
5597         if (strcmp(argv[1], "osts") == 0) {
5598                 strcpy(obd_types[0], "osc");
5599         } else if (strcmp(argv[1], "mds") == 0) {
5600                 strcpy(obd_types[0], "mdc");
5601         } else if (strcmp(argv[1], "servers") == 0) {
5602                 num_types = 2;
5603                 strcpy(obd_types[0], "osc");
5604                 strcpy(obd_types[1], "mdc");
5605         } else {
5606                 fprintf(stderr, "%s check: unrecognized option '%s'\n",
5607                         progname, argv[1]);
5608                 return CMD_HELP;
5609         }
5610
5611         rc = llapi_search_mounts(NULL, 0, mntdir, NULL);
5612         if (rc < 0 || mntdir[0] == '\0') {
5613                 fprintf(stderr,
5614                         "%s check: cannot find mounted Lustre filesystem: %s\n",
5615                         progname, (rc < 0) ? strerror(-rc) : strerror(ENODEV));
5616                 return rc;
5617         }
5618
5619         rc = llapi_target_check(num_types, obd_types, mntdir);
5620         if (rc)
5621                 fprintf(stderr, "%s check: cannot check target '%s': %s\n",
5622                         progname, argv[1], strerror(-rc));
5623
5624         return rc;
5625
5626 }
5627
5628 #ifdef HAVE_SYS_QUOTA_H
5629 #define ARG2INT(nr, str, msg)                                           \
5630 do {                                                                    \
5631         char *endp;                                                     \
5632         nr = strtol(str, &endp, 0);                                     \
5633         if (*endp != '\0') {                                            \
5634                 fprintf(stderr, "%s: bad %s '%s'\n",                    \
5635                         progname, msg, str);                            \
5636                 return CMD_HELP;                                        \
5637         }                                                               \
5638 } while (0)
5639
5640 #define ADD_OVERFLOW(a,b) ((a + b) < a) ? (a = ULONG_MAX) : (a = a + b)
5641
5642 /* Convert format time string "XXwXXdXXhXXmXXs" into seconds value
5643  * returns the value or ULONG_MAX on integer overflow or incorrect format
5644  * Notes:
5645  *        1. the order of specifiers is arbitrary (may be: 5w3s or 3s5w)
5646  *        2. specifiers may be encountered multiple times (2s3s is 5 seconds)
5647  *        3. empty integer value is interpreted as 0
5648  */
5649 static unsigned long str2sec(const char* timestr)
5650 {
5651         const char spec[] = "smhdw";
5652         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
5653         unsigned long val = 0;
5654         char *tail;
5655
5656         if (strpbrk(timestr, spec) == NULL) {
5657                 /* no specifiers inside the time string,
5658                    should treat it as an integer value */
5659                 val = strtoul(timestr, &tail, 10);
5660                 return *tail ? ULONG_MAX : val;
5661         }
5662
5663         /* format string is XXwXXdXXhXXmXXs */
5664         while (*timestr) {
5665                 unsigned long v;
5666                 int ind;
5667                 char* ptr;
5668
5669                 v = strtoul(timestr, &tail, 10);
5670                 if (v == ULONG_MAX || *tail == '\0')
5671                         /* value too large (ULONG_MAX or more)
5672                            or missing specifier */
5673                         goto error;
5674
5675                 ptr = strchr(spec, *tail);
5676                 if (ptr == NULL)
5677                         /* unknown specifier */
5678                         goto error;
5679
5680                 ind = ptr - spec;
5681
5682                 /* check if product will overflow the type */
5683                 if (!(v < ULONG_MAX / mult[ind]))
5684                         goto error;
5685
5686                 ADD_OVERFLOW(val, mult[ind] * v);
5687                 if (val == ULONG_MAX)
5688                         goto error;
5689
5690                 timestr = tail + 1;
5691         }
5692
5693         return val;
5694
5695 error:
5696         return ULONG_MAX;
5697 }
5698
5699 #define ARG2ULL(nr, str, def_units)                                     \
5700 do {                                                                    \
5701         unsigned long long limit, units = def_units;                    \
5702         int rc;                                                         \
5703                                                                         \
5704         rc = llapi_parse_size(str, &limit, &units, 1);                  \
5705         if (rc < 0) {                                                   \
5706                 fprintf(stderr, "%s: invalid limit '%s'\n",             \
5707                         progname, str);                                 \
5708                 return CMD_HELP;                                        \
5709         }                                                               \
5710         nr = limit;                                                     \
5711 } while (0)
5712
5713 static inline int has_times_option(int argc, char **argv)
5714 {
5715         int i;
5716
5717         for (i = 1; i < argc; i++)
5718                 if (!strcmp(argv[i], "-t"))
5719                         return 1;
5720
5721         return 0;
5722 }
5723
5724 int lfs_setquota_times(int argc, char **argv)
5725 {
5726         int c, rc;
5727         struct if_quotactl qctl;
5728         char *mnt, *obd_type = (char *)qctl.obd_type;
5729         struct obd_dqblk *dqb = &qctl.qc_dqblk;
5730         struct obd_dqinfo *dqi = &qctl.qc_dqinfo;
5731         struct option long_opts[] = {
5732         { .val = 'b',   .name = "block-grace",  .has_arg = required_argument },
5733         { .val = 'g',   .name = "group",        .has_arg = no_argument },
5734         { .val = 'i',   .name = "inode-grace",  .has_arg = required_argument },
5735         { .val = 'p',   .name = "projid",       .has_arg = no_argument },
5736         { .val = 't',   .name = "times",        .has_arg = no_argument },
5737         { .val = 'u',   .name = "user",         .has_arg = no_argument },
5738         { .name = NULL } };
5739         int qtype;
5740
5741         memset(&qctl, 0, sizeof(qctl));
5742         qctl.qc_cmd  = LUSTRE_Q_SETINFO;
5743         qctl.qc_type = ALLQUOTA;
5744
5745         while ((c = getopt_long(argc, argv, "b:gi:ptu",
5746                                 long_opts, NULL)) != -1) {
5747                 switch (c) {
5748                 case 'u':
5749                         qtype = USRQUOTA;
5750                         goto quota_type;
5751                 case 'g':
5752                         qtype = GRPQUOTA;
5753                         goto quota_type;
5754                 case 'p':
5755                         qtype = PRJQUOTA;
5756 quota_type:
5757                         if (qctl.qc_type != ALLQUOTA) {
5758                                 fprintf(stderr, "error: -u/g/p can't be used "
5759                                                 "more than once\n");
5760                                 return CMD_HELP;
5761                         }
5762                         qctl.qc_type = qtype;
5763                         break;
5764                 case 'b':
5765                         if ((dqi->dqi_bgrace = str2sec(optarg)) == ULONG_MAX) {
5766                                 fprintf(stderr, "error: bad block-grace: %s\n",
5767                                         optarg);
5768                                 return CMD_HELP;
5769                         }
5770                         dqb->dqb_valid |= QIF_BTIME;
5771                         break;
5772                 case 'i':
5773                         if ((dqi->dqi_igrace = str2sec(optarg)) == ULONG_MAX) {
5774                                 fprintf(stderr, "error: bad inode-grace: %s\n",
5775                                         optarg);
5776                                 return CMD_HELP;
5777                         }
5778                         dqb->dqb_valid |= QIF_ITIME;
5779                         break;
5780                 case 't': /* Yes, of course! */
5781                         break;
5782                 default: /* getopt prints error message for us when opterr != 0 */
5783                         return CMD_HELP;
5784                 }
5785         }
5786
5787         if (qctl.qc_type == ALLQUOTA) {
5788                 fprintf(stderr, "error: neither -u, -g nor -p specified\n");
5789                 return CMD_HELP;
5790         }
5791
5792         if (optind != argc - 1) {
5793                 fprintf(stderr, "error: unexpected parameters encountered\n");
5794                 return CMD_HELP;
5795         }
5796
5797         if ((dqb->dqb_valid | QIF_BTIME && dqi->dqi_bgrace >= UINT_MAX) ||
5798             (dqb->dqb_valid | QIF_ITIME && dqi->dqi_igrace >= UINT_MAX)) {
5799                 fprintf(stderr, "error: grace time is too large\n");
5800                 return CMD_HELP;
5801         }
5802
5803         mnt = argv[optind];
5804         rc = llapi_quotactl(mnt, &qctl);
5805         if (rc) {
5806                 if (*obd_type)
5807                         fprintf(stderr, "%s %s ", obd_type,
5808                                 obd_uuid2str(&qctl.obd_uuid));
5809                 fprintf(stderr, "setquota failed: %s\n", strerror(-rc));
5810                 return rc;
5811         }
5812
5813         return 0;
5814 }
5815
5816 #define BSLIMIT (1 << 0)
5817 #define BHLIMIT (1 << 1)
5818 #define ISLIMIT (1 << 2)
5819 #define IHLIMIT (1 << 3)
5820
5821 int lfs_setquota(int argc, char **argv)
5822 {
5823         int c, rc = 0;
5824         struct if_quotactl qctl;
5825         char *mnt, *obd_type = (char *)qctl.obd_type;
5826         struct obd_dqblk *dqb = &qctl.qc_dqblk;
5827         struct option long_opts[] = {
5828         { .val = 'b',   .name = "block-softlimit",
5829                                                 .has_arg = required_argument },
5830         { .val = 'B',   .name = "block-hardlimit",
5831                                                 .has_arg = required_argument },
5832         { .val = 'd',   .name = "default",      .has_arg = no_argument },
5833         { .val = 'g',   .name = "group",        .has_arg = required_argument },
5834         { .val = 'G',   .name = "default-grp",  .has_arg = no_argument },
5835         { .val = 'i',   .name = "inode-softlimit",
5836                                                 .has_arg = required_argument },
5837         { .val = 'I',   .name = "inode-hardlimit",
5838                                                 .has_arg = required_argument },
5839         { .val = 'p',   .name = "projid",       .has_arg = required_argument },
5840         { .val = 'P',   .name = "default-prj",  .has_arg = no_argument },
5841         { .val = 'u',   .name = "user",         .has_arg = required_argument },
5842         { .val = 'U',   .name = "default-usr",  .has_arg = no_argument },
5843         { .name = NULL } };
5844         unsigned limit_mask = 0;
5845         char *endptr;
5846         bool use_default = false;
5847         int qtype;
5848
5849         if (has_times_option(argc, argv))
5850                 return lfs_setquota_times(argc, argv);
5851
5852         memset(&qctl, 0, sizeof(qctl));
5853         qctl.qc_cmd  = LUSTRE_Q_SETQUOTA;
5854         qctl.qc_type = ALLQUOTA; /* ALLQUOTA makes no sense for setquota,
5855                                   * so it can be used as a marker that qc_type
5856                                   * isn't reinitialized from command line */
5857
5858         while ((c = getopt_long(argc, argv, "b:B:dg:Gi:I:p:Pu:U",
5859                 long_opts, NULL)) != -1) {
5860                 switch (c) {
5861                 case 'U':
5862                         qctl.qc_cmd = LUSTRE_Q_SETDEFAULT;
5863                         qtype = USRQUOTA;
5864                         qctl.qc_id = 0;
5865                         goto quota_type_def;
5866                 case 'u':
5867                         qtype = USRQUOTA;
5868                         rc = name2uid(&qctl.qc_id, optarg);
5869                         goto quota_type;
5870                 case 'G':
5871                         qctl.qc_cmd = LUSTRE_Q_SETDEFAULT;
5872                         qtype = GRPQUOTA;
5873                         qctl.qc_id = 0;
5874                         goto quota_type_def;
5875                 case 'g':
5876                         qtype = GRPQUOTA;
5877                         rc = name2gid(&qctl.qc_id, optarg);
5878                         goto quota_type;
5879                 case 'P':
5880                         qctl.qc_cmd = LUSTRE_Q_SETDEFAULT;
5881                         qtype = PRJQUOTA;
5882                         qctl.qc_id = 0;
5883                         goto quota_type_def;
5884                 case 'p':
5885                         qtype = PRJQUOTA;
5886                         rc = name2projid(&qctl.qc_id, optarg);
5887 quota_type:
5888                         if (rc) {
5889                                 qctl.qc_id = strtoul(optarg, &endptr, 10);
5890                                 if (*endptr != '\0') {
5891                                         fprintf(stderr, "%s setquota: invalid"
5892                                                 " id '%s'\n", progname, optarg);
5893                                         return -1;
5894                                 }
5895                         }
5896
5897                         if (qctl.qc_id == 0) {
5898                                 fprintf(stderr, "%s setquota: can't set quota"
5899                                         " for root usr/group/project.\n",
5900                                         progname);
5901                                 return -1;
5902                         }
5903
5904 quota_type_def:
5905                         if (qctl.qc_type != ALLQUOTA) {
5906                                 fprintf(stderr,
5907                                         "%s setquota: only one of -u, -U, -g,"
5908                                         " -G, -p or -P may be specified\n",
5909                                         progname);
5910                                 return CMD_HELP;
5911                         }
5912                         qctl.qc_type = qtype;
5913                         break;
5914                 case 'd':
5915                         qctl.qc_cmd = LUSTRE_Q_SETDEFAULT;
5916                         use_default = true;
5917                         break;
5918                 case 'b':
5919                         ARG2ULL(dqb->dqb_bsoftlimit, optarg, 1024);
5920                         dqb->dqb_bsoftlimit >>= 10;
5921                         limit_mask |= BSLIMIT;
5922                         if (dqb->dqb_bsoftlimit &&
5923                             dqb->dqb_bsoftlimit <= 1024) /* <= 1M? */
5924                                 fprintf(stderr,
5925                                         "%s setquota: warning: block softlimit '%llu' smaller than minimum qunit size\n"
5926                                         "See '%s help setquota' or Lustre manual for details\n",
5927                                         progname,
5928                                         (unsigned long long)dqb->dqb_bsoftlimit,
5929                                         progname);
5930                         break;
5931                 case 'B':
5932                         ARG2ULL(dqb->dqb_bhardlimit, optarg, 1024);
5933                         dqb->dqb_bhardlimit >>= 10;
5934                         limit_mask |= BHLIMIT;
5935                         if (dqb->dqb_bhardlimit &&
5936                             dqb->dqb_bhardlimit <= 1024) /* <= 1M? */
5937                                 fprintf(stderr,
5938                                         "%s setquota: warning: block hardlimit '%llu' smaller than minimum qunit size\n"
5939                                         "See '%s help setquota' or Lustre manual for details\n",
5940                                         progname,
5941                                         (unsigned long long)dqb->dqb_bhardlimit,
5942                                         progname);
5943                         break;
5944                 case 'i':
5945                         ARG2ULL(dqb->dqb_isoftlimit, optarg, 1);
5946                         limit_mask |= ISLIMIT;
5947                         if (dqb->dqb_isoftlimit &&
5948                             dqb->dqb_isoftlimit <= 1024) /* <= 1K inodes? */
5949                                 fprintf(stderr,
5950                                         "%s setquota: warning: inode softlimit '%llu' smaller than minimum qunit size\n"
5951                                         "See '%s help setquota' or Lustre manual for details\n",
5952                                         progname,
5953                                         (unsigned long long)dqb->dqb_isoftlimit,
5954                                         progname);
5955                         break;
5956                 case 'I':
5957                         ARG2ULL(dqb->dqb_ihardlimit, optarg, 1);
5958                         limit_mask |= IHLIMIT;
5959                         if (dqb->dqb_ihardlimit &&
5960                             dqb->dqb_ihardlimit <= 1024) /* <= 1K inodes? */
5961                                 fprintf(stderr,
5962                                         "%s setquota: warning: inode hardlimit '%llu' smaller than minimum qunit size\n"
5963                                         "See '%s help setquota' or Lustre manual for details\n",
5964                                         progname,
5965                                         (unsigned long long)dqb->dqb_ihardlimit,
5966                                         progname);
5967                         break;
5968                 default:
5969                         fprintf(stderr,
5970                                 "%s setquota: unrecognized option '%s'\n",
5971                                 progname, argv[optind - 1]);
5972                         return CMD_HELP;
5973                 }
5974         }
5975
5976         if (qctl.qc_type == ALLQUOTA) {
5977                 fprintf(stderr,
5978                         "%s setquota: either -u or -g must be specified\n",
5979                         progname);
5980                 return CMD_HELP;
5981         }
5982
5983         if (!use_default && limit_mask == 0) {
5984                 fprintf(stderr,
5985                         "%s setquota: at least one limit must be specified\n",
5986                         progname);
5987                 return CMD_HELP;
5988         }
5989
5990         if (use_default && limit_mask != 0) {
5991                 fprintf(stderr,
5992                         "%s setquota: limits should not be specified when"
5993                         " using default quota\n",
5994                         progname);
5995                 return CMD_HELP;
5996         }
5997
5998         if (use_default && qctl.qc_id == 0) {
5999                 fprintf(stderr,
6000                         "%s setquota: can not set default quota for root"
6001                         " user/group/project\n",
6002                         progname);
6003                 return CMD_HELP;
6004         }
6005
6006         if (optind != argc - 1) {
6007                 fprintf(stderr,
6008                         "%s setquota: filesystem not specified or unexpected argument '%s'\n",
6009                         progname, argv[optind]);
6010                 return CMD_HELP;
6011         }
6012
6013         mnt = argv[optind];
6014
6015         if (use_default) {
6016                 dqb->dqb_bhardlimit = 0;
6017                 dqb->dqb_bsoftlimit = 0;
6018                 dqb->dqb_ihardlimit = 0;
6019                 dqb->dqb_isoftlimit = 0;
6020                 dqb->dqb_itime = 0;
6021                 dqb->dqb_btime = 0;
6022                 dqb->dqb_valid |= QIF_LIMITS | QIF_TIMES;
6023         } else if ((!(limit_mask & BHLIMIT) ^ !(limit_mask & BSLIMIT)) ||
6024                    (!(limit_mask & IHLIMIT) ^ !(limit_mask & ISLIMIT))) {
6025                 /* sigh, we can't just set blimits/ilimits */
6026                 struct if_quotactl tmp_qctl = {.qc_cmd  = LUSTRE_Q_GETQUOTA,
6027                                                .qc_type = qctl.qc_type,
6028                                                .qc_id   = qctl.qc_id};
6029
6030                 rc = llapi_quotactl(mnt, &tmp_qctl);
6031                 if (rc < 0)
6032                         return rc;
6033
6034                 if (!(limit_mask & BHLIMIT))
6035                         dqb->dqb_bhardlimit = tmp_qctl.qc_dqblk.dqb_bhardlimit;
6036                 if (!(limit_mask & BSLIMIT))
6037                         dqb->dqb_bsoftlimit = tmp_qctl.qc_dqblk.dqb_bsoftlimit;
6038                 if (!(limit_mask & IHLIMIT))
6039                         dqb->dqb_ihardlimit = tmp_qctl.qc_dqblk.dqb_ihardlimit;
6040                 if (!(limit_mask & ISLIMIT))
6041                         dqb->dqb_isoftlimit = tmp_qctl.qc_dqblk.dqb_isoftlimit;
6042
6043                 /* Keep grace times if we have got no softlimit arguments */
6044                 if ((limit_mask & BHLIMIT) && !(limit_mask & BSLIMIT)) {
6045                         dqb->dqb_valid |= QIF_BTIME;
6046                         dqb->dqb_btime = tmp_qctl.qc_dqblk.dqb_btime;
6047                 }
6048
6049                 if ((limit_mask & IHLIMIT) && !(limit_mask & ISLIMIT)) {
6050                         dqb->dqb_valid |= QIF_ITIME;
6051                         dqb->dqb_itime = tmp_qctl.qc_dqblk.dqb_itime;
6052                 }
6053         }
6054
6055         dqb->dqb_valid |= (limit_mask & (BHLIMIT | BSLIMIT)) ? QIF_BLIMITS : 0;
6056         dqb->dqb_valid |= (limit_mask & (IHLIMIT | ISLIMIT)) ? QIF_ILIMITS : 0;
6057
6058         rc = llapi_quotactl(mnt, &qctl);
6059         if (rc) {
6060                 if (*obd_type)
6061                         fprintf(stderr,
6062                                 "%s setquota: cannot quotactl '%s' '%s': %s",
6063                                 progname, obd_type,
6064                                 obd_uuid2str(&qctl.obd_uuid), strerror(-rc));
6065                 return rc;
6066         }
6067
6068         return 0;
6069 }
6070
6071 /* Converts seconds value into format string
6072  * result is returned in buf
6073  * Notes:
6074  *        1. result is in descenting order: 1w2d3h4m5s
6075  *        2. zero fields are not filled (except for p. 3): 5d1s
6076  *        3. zero seconds value is presented as "0s"
6077  */
6078 static char * __sec2str(time_t seconds, char *buf)
6079 {
6080         const char spec[] = "smhdw";
6081         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
6082         unsigned long c;
6083         char *tail = buf;
6084         int i;
6085
6086         for (i = sizeof(mult) / sizeof(mult[0]) - 1 ; i >= 0; i--) {
6087                 c = seconds / mult[i];
6088
6089                 if (c > 0 || (i == 0 && buf == tail))
6090                         tail += snprintf(tail, 40-(tail-buf), "%lu%c", c, spec[i]);
6091
6092                 seconds %= mult[i];
6093         }
6094
6095         return tail;
6096 }
6097
6098 static void sec2str(time_t seconds, char *buf, int rc)
6099 {
6100         char *tail = buf;
6101
6102         if (rc)
6103                 *tail++ = '[';
6104
6105         tail = __sec2str(seconds, tail);
6106
6107         if (rc && tail - buf < 39) {
6108                 *tail++ = ']';
6109                 *tail++ = 0;
6110         }
6111 }
6112
6113 static void diff2str(time_t seconds, char *buf, time_t now)
6114 {
6115
6116         buf[0] = 0;
6117         if (!seconds)
6118                 return;
6119         if (seconds <= now) {
6120                 strcpy(buf, "none");
6121                 return;
6122         }
6123         __sec2str(seconds - now, buf);
6124 }
6125
6126 static void print_quota_title(char *name, struct if_quotactl *qctl,
6127                               bool human_readable, bool show_default)
6128 {
6129         if (show_default) {
6130                 printf("Disk default %s quota:\n", qtype_name(qctl->qc_type));
6131                 printf("%15s %8s%8s%8s %8s%8s%8s\n",
6132                        "Filesystem", "bquota", "blimit", "bgrace",
6133                        "iquota", "ilimit", "igrace");
6134         } else {
6135                 printf("Disk quotas for %s %s (%cid %u):\n",
6136                        qtype_name(qctl->qc_type), name,
6137                        *qtype_name(qctl->qc_type), qctl->qc_id);
6138                 printf("%15s%8s %7s%8s%8s%8s %7s%8s%8s\n",
6139                        "Filesystem", human_readable ? "used" : "kbytes",
6140                        "quota", "limit", "grace",
6141                        "files", "quota", "limit", "grace");
6142         }
6143 }
6144
6145 static void kbytes2str(__u64 num, char *buf, int buflen, bool h)
6146 {
6147         if (!h) {
6148                 snprintf(buf, buflen, "%ju", (uintmax_t)num);
6149         } else {
6150                 if (num >> 40)
6151                         snprintf(buf, buflen, "%5.4gP",
6152                                  (double)num / ((__u64)1 << 40));
6153                 else if (num >> 30)
6154                         snprintf(buf, buflen, "%5.4gT",
6155                                  (double)num / (1 << 30));
6156                 else if (num >> 20)
6157                         snprintf(buf, buflen, "%5.4gG",
6158                                  (double)num / (1 << 20));
6159                 else if (num >> 10)
6160                         snprintf(buf, buflen, "%5.4gM",
6161                                  (double)num / (1 << 10));
6162                 else
6163                         snprintf(buf, buflen, "%ju%s", (uintmax_t)num, "k");
6164         }
6165 }
6166
6167 #define STRBUF_LEN      32
6168 static void print_quota(char *mnt, struct if_quotactl *qctl, int type,
6169                         int rc, bool h, bool show_default)
6170 {
6171         time_t now;
6172
6173         time(&now);
6174
6175         if (qctl->qc_cmd == LUSTRE_Q_GETQUOTA || qctl->qc_cmd == Q_GETOQUOTA ||
6176             qctl->qc_cmd == LUSTRE_Q_GETDEFAULT) {
6177                 int bover = 0, iover = 0;
6178                 struct obd_dqblk *dqb = &qctl->qc_dqblk;
6179                 char numbuf[3][STRBUF_LEN];
6180                 char timebuf[40];
6181                 char strbuf[STRBUF_LEN];
6182
6183                 if (dqb->dqb_bhardlimit &&
6184                     lustre_stoqb(dqb->dqb_curspace) >= dqb->dqb_bhardlimit) {
6185                         bover = 1;
6186                 } else if (dqb->dqb_bsoftlimit && dqb->dqb_btime) {
6187                         if (dqb->dqb_btime > now) {
6188                                 bover = 2;
6189                         } else {
6190                                 bover = 3;
6191                         }
6192                 }
6193
6194                 if (dqb->dqb_ihardlimit &&
6195                     dqb->dqb_curinodes >= dqb->dqb_ihardlimit) {
6196                         iover = 1;
6197                 } else if (dqb->dqb_isoftlimit && dqb->dqb_itime) {
6198                         if (dqb->dqb_itime > now) {
6199                                 iover = 2;
6200                         } else {
6201                                 iover = 3;
6202                         }
6203                 }
6204
6205
6206                 if (strlen(mnt) > 15)
6207                         printf("%s\n%15s", mnt, "");
6208                 else
6209                         printf("%15s", mnt);
6210
6211                 if (bover)
6212                         diff2str(dqb->dqb_btime, timebuf, now);
6213                 else if (show_default)
6214                         snprintf(timebuf, sizeof(timebuf), "%llu",
6215                                  (unsigned long long)dqb->dqb_btime);
6216
6217                 kbytes2str(lustre_stoqb(dqb->dqb_curspace),
6218                            strbuf, sizeof(strbuf), h);
6219                 if (rc == -EREMOTEIO)
6220                         sprintf(numbuf[0], "%s*", strbuf);
6221                 else
6222                         sprintf(numbuf[0], (dqb->dqb_valid & QIF_SPACE) ?
6223                                 "%s" : "[%s]", strbuf);
6224
6225                 kbytes2str(dqb->dqb_bsoftlimit, strbuf, sizeof(strbuf), h);
6226                 if (type == QC_GENERAL)
6227                         sprintf(numbuf[1], (dqb->dqb_valid & QIF_BLIMITS) ?
6228                                 "%s" : "[%s]", strbuf);
6229                 else
6230                         sprintf(numbuf[1], "%s", "-");
6231
6232                 kbytes2str(dqb->dqb_bhardlimit, strbuf, sizeof(strbuf), h);
6233                 sprintf(numbuf[2], (dqb->dqb_valid & QIF_BLIMITS) ?
6234                         "%s" : "[%s]", strbuf);
6235
6236                 if (show_default)
6237                         printf(" %6s %7s %7s", numbuf[1], numbuf[2], timebuf);
6238                 else
6239                         printf(" %7s%c %6s %7s %7s",
6240                                numbuf[0], bover ? '*' : ' ', numbuf[1],
6241                                numbuf[2], bover > 1 ? timebuf : "-");
6242
6243
6244                 if (iover)
6245                         diff2str(dqb->dqb_itime, timebuf, now);
6246                 else if (show_default)
6247                         snprintf(timebuf, sizeof(timebuf), "%llu",
6248                                  (unsigned long long)dqb->dqb_itime);
6249
6250                 snprintf(numbuf[0], sizeof(numbuf),
6251                          (dqb->dqb_valid & QIF_INODES) ? "%ju" : "[%ju]",
6252                          (uintmax_t)dqb->dqb_curinodes);
6253
6254                 if (type == QC_GENERAL)
6255                         sprintf(numbuf[1], (dqb->dqb_valid & QIF_ILIMITS) ?
6256                                 "%ju" : "[%ju]",
6257                                 (uintmax_t)dqb->dqb_isoftlimit);
6258                 else
6259                         sprintf(numbuf[1], "%s", "-");
6260
6261                 sprintf(numbuf[2], (dqb->dqb_valid & QIF_ILIMITS) ?
6262                         "%ju" : "[%ju]", (uintmax_t)dqb->dqb_ihardlimit);
6263
6264                 if (show_default)
6265                         printf(" %6s %7s %7s", numbuf[1], numbuf[2], timebuf);
6266                 else if (type != QC_OSTIDX)
6267                         printf(" %7s%c %6s %7s %7s",
6268                                numbuf[0], iover ? '*' : ' ', numbuf[1],
6269                                numbuf[2], iover > 1 ? timebuf : "-");
6270                 else
6271                         printf(" %7s %7s %7s %7s", "-", "-", "-", "-");
6272                 printf("\n");
6273
6274         } else if (qctl->qc_cmd == LUSTRE_Q_GETINFO ||
6275                    qctl->qc_cmd == Q_GETOINFO) {
6276                 char bgtimebuf[40];
6277                 char igtimebuf[40];
6278
6279                 sec2str(qctl->qc_dqinfo.dqi_bgrace, bgtimebuf, rc);
6280                 sec2str(qctl->qc_dqinfo.dqi_igrace, igtimebuf, rc);
6281                 printf("Block grace time: %s; Inode grace time: %s\n",
6282                        bgtimebuf, igtimebuf);
6283         }
6284 }
6285
6286 static int print_obd_quota(char *mnt, struct if_quotactl *qctl, int is_mdt,
6287                            bool h, __u64 *total)
6288 {
6289         int rc = 0, rc1 = 0, count = 0;
6290         __u32 valid = qctl->qc_valid;
6291
6292         rc = llapi_get_obd_count(mnt, &count, is_mdt);
6293         if (rc) {
6294                 fprintf(stderr, "can not get %s count: %s\n",
6295                         is_mdt ? "mdt": "ost", strerror(-rc));
6296                 return rc;
6297         }
6298
6299         for (qctl->qc_idx = 0; qctl->qc_idx < count; qctl->qc_idx++) {
6300                 qctl->qc_valid = is_mdt ? QC_MDTIDX : QC_OSTIDX;
6301                 rc = llapi_quotactl(mnt, qctl);
6302                 if (rc) {
6303                         /* It is remote client case. */
6304                         if (rc == -EOPNOTSUPP) {
6305                                 rc = 0;
6306                                 goto out;
6307                         }
6308
6309                         if (!rc1)
6310                                 rc1 = rc;
6311                         fprintf(stderr, "quotactl %s%d failed.\n",
6312                                 is_mdt ? "mdt": "ost", qctl->qc_idx);
6313                         continue;
6314                 }
6315
6316                 print_quota(obd_uuid2str(&qctl->obd_uuid), qctl,
6317                             qctl->qc_valid, 0, h, false);
6318                 *total += is_mdt ? qctl->qc_dqblk.dqb_ihardlimit :
6319                                    qctl->qc_dqblk.dqb_bhardlimit;
6320         }
6321 out:
6322         qctl->qc_valid = valid;
6323         return rc ? : rc1;
6324 }
6325
6326 static int get_print_quota(char *mnt, char *name, struct if_quotactl *qctl,
6327                            int verbose, int quiet, bool human_readable,
6328                            bool show_default)
6329 {
6330         int rc1 = 0, rc2 = 0, rc3 = 0;
6331         char *obd_type = (char *)qctl->obd_type;
6332         char *obd_uuid = (char *)qctl->obd_uuid.uuid;
6333         __u64 total_ialloc = 0, total_balloc = 0;
6334         bool use_default_for_blk = false;
6335         bool use_default_for_file = false;
6336         int inacc;
6337
6338         rc1 = llapi_quotactl(mnt, qctl);
6339         if (rc1 < 0) {
6340                 switch (rc1) {
6341                 case -ESRCH:
6342                         fprintf(stderr, "%s quotas are not enabled.\n",
6343                                 qtype_name(qctl->qc_type));
6344                         goto out;
6345                 case -EPERM:
6346                         fprintf(stderr, "Permission denied.\n");
6347                 case -ENODEV:
6348                 case -ENOENT:
6349                         /* We already got error message. */
6350                         goto out;
6351                 default:
6352                         fprintf(stderr, "Unexpected quotactl error: %s\n",
6353                                 strerror(-rc1));
6354                 }
6355         }
6356
6357         if (!show_default && qctl->qc_id == 0) {
6358                 qctl->qc_dqblk.dqb_bhardlimit = 0;
6359                 qctl->qc_dqblk.dqb_bsoftlimit = 0;
6360                 qctl->qc_dqblk.dqb_ihardlimit = 0;
6361                 qctl->qc_dqblk.dqb_isoftlimit = 0;
6362                 qctl->qc_dqblk.dqb_btime = 0;
6363                 qctl->qc_dqblk.dqb_itime = 0;
6364                 qctl->qc_dqblk.dqb_valid |= QIF_LIMITS | QIF_TIMES;
6365         }
6366
6367         if (qctl->qc_dqblk.dqb_valid & QIF_BTIME &&
6368             LQUOTA_FLAG(qctl->qc_dqblk.dqb_btime) & LQUOTA_FLAG_DEFAULT) {
6369                 use_default_for_blk = true;
6370                 qctl->qc_dqblk.dqb_btime &= LQUOTA_GRACE_MASK;
6371         }
6372
6373         if (qctl->qc_dqblk.dqb_valid & QIF_ITIME &&
6374             LQUOTA_FLAG(qctl->qc_dqblk.dqb_itime) & LQUOTA_FLAG_DEFAULT) {
6375                 use_default_for_file = true;
6376                 qctl->qc_dqblk.dqb_itime &= LQUOTA_GRACE_MASK;
6377         }
6378
6379         if ((qctl->qc_cmd == LUSTRE_Q_GETQUOTA ||
6380              qctl->qc_cmd == LUSTRE_Q_GETDEFAULT) && !quiet)
6381                 print_quota_title(name, qctl, human_readable, show_default);
6382
6383         if (rc1 && *obd_type)
6384                 fprintf(stderr, "%s %s ", obd_type, obd_uuid);
6385
6386         if (qctl->qc_valid != QC_GENERAL)
6387                 mnt = "";
6388
6389         inacc = (qctl->qc_cmd == LUSTRE_Q_GETQUOTA) &&
6390                 ((qctl->qc_dqblk.dqb_valid & (QIF_LIMITS|QIF_USAGE)) !=
6391                  (QIF_LIMITS|QIF_USAGE));
6392
6393         print_quota(mnt, qctl, QC_GENERAL, rc1, human_readable, show_default);
6394
6395         if (!show_default && verbose &&
6396             qctl->qc_valid == QC_GENERAL && qctl->qc_cmd != LUSTRE_Q_GETINFO) {
6397                 char strbuf[STRBUF_LEN];
6398
6399                 rc2 = print_obd_quota(mnt, qctl, 1, human_readable,
6400                                       &total_ialloc);
6401                 rc3 = print_obd_quota(mnt, qctl, 0, human_readable,
6402                                       &total_balloc);
6403                 kbytes2str(total_balloc, strbuf, sizeof(strbuf),
6404                            human_readable);
6405                 printf("Total allocated inode limit: %ju, total "
6406                        "allocated block limit: %s\n", (uintmax_t)total_ialloc,
6407                        strbuf);
6408         }
6409
6410         if (use_default_for_blk)
6411                 printf("%cid %u is using default block quota setting\n",
6412                        *qtype_name(qctl->qc_type), qctl->qc_id);
6413
6414         if (use_default_for_file)
6415                 printf("%cid %u is using default file quota setting\n",
6416                        *qtype_name(qctl->qc_type), qctl->qc_id);
6417
6418         if (rc1 || rc2 || rc3 || inacc)
6419                 printf("Some errors happened when getting quota info. "
6420                        "Some devices may be not working or deactivated. "
6421                        "The data in \"[]\" is inaccurate.\n");
6422 out:
6423         return rc1;
6424
6425 }
6426
6427 static int lfs_project(int argc, char **argv)
6428 {
6429         int ret = 0, err = 0, c, i;
6430         struct project_handle_control phc = { 0 };
6431         enum lfs_project_ops_t op;
6432
6433         phc.newline = true;
6434         phc.assign_projid = false;
6435         /* default action */
6436         op = LFS_PROJECT_LIST;
6437
6438         while ((c = getopt(argc, argv, "p:cCsdkr0")) != -1) {
6439                 switch (c) {
6440                 case 'c':
6441                         if (op != LFS_PROJECT_LIST) {
6442                                 fprintf(stderr,
6443                                         "%s: cannot specify '-c' '-C' '-s' together\n",
6444                                         progname);
6445                                 return CMD_HELP;
6446                         }
6447
6448                         op = LFS_PROJECT_CHECK;
6449                         break;
6450                 case 'C':
6451                         if (op != LFS_PROJECT_LIST) {
6452                                 fprintf(stderr,
6453                                         "%s: cannot specify '-c' '-C' '-s' together\n",
6454                                         progname);
6455                                 return CMD_HELP;
6456                         }
6457
6458                         op = LFS_PROJECT_CLEAR;
6459                         break;
6460                 case 's':
6461                         if (op != LFS_PROJECT_LIST) {
6462                                 fprintf(stderr,
6463                                         "%s: cannot specify '-c' '-C' '-s' together\n",
6464                                         progname);
6465                                 return CMD_HELP;
6466                         }
6467
6468                         phc.set_inherit = true;
6469                         op = LFS_PROJECT_SET;
6470                         break;
6471                 case 'd':
6472                         phc.dironly = true;
6473                         break;
6474                 case 'k':
6475                         phc.keep_projid = true;
6476                         break;
6477                 case 'r':
6478                         phc.recursive = true;
6479                         break;
6480                 case 'p':
6481                         phc.projid = strtoul(optarg, NULL, 0);
6482                         phc.assign_projid = true;
6483
6484                         break;
6485                 case '0':
6486                         phc.newline = false;
6487                         break;
6488                 default:
6489                         fprintf(stderr, "%s: invalid option '%c'\n",
6490                                 progname, optopt);
6491                         return CMD_HELP;
6492                 }
6493         }
6494
6495         if (phc.assign_projid && op == LFS_PROJECT_LIST) {
6496                 op = LFS_PROJECT_SET;
6497                 phc.set_projid = true;
6498         } else if (phc.assign_projid && op == LFS_PROJECT_SET) {
6499                 phc.set_projid = true;
6500         }
6501
6502         switch (op) {
6503         case LFS_PROJECT_CHECK:
6504                 if (phc.keep_projid) {
6505                         fprintf(stderr,
6506                                 "%s: '-k' is useless together with '-c'\n",
6507                                 progname);
6508                         return CMD_HELP;
6509                 }
6510                 break;
6511         case LFS_PROJECT_CLEAR:
6512                 if (!phc.newline) {
6513                         fprintf(stderr,
6514                                 "%s: '-0' is useless together with '-C'\n",
6515                                 progname);
6516                         return CMD_HELP;
6517                 }
6518                 if (phc.assign_projid) {
6519                         fprintf(stderr,
6520                                 "%s: '-p' is useless together with '-C'\n",
6521                                 progname);
6522                         return CMD_HELP;
6523                 }
6524                 break;
6525         case LFS_PROJECT_SET:
6526                 if (!phc.newline) {
6527                         fprintf(stderr,
6528                                 "%s: '-0' is useless together with '-s'\n",
6529                                 progname);
6530                         return CMD_HELP;
6531                 }
6532                 if (phc.keep_projid) {
6533                         fprintf(stderr,
6534                                 "%s: '-k' is useless together with '-s'\n",
6535                                 progname);
6536                         return CMD_HELP;
6537                 }
6538                 break;
6539         default:
6540                 if (!phc.newline) {
6541                         fprintf(stderr,
6542                                 "%s: '-0' is useless for list operations\n",
6543                                 progname);
6544                         return CMD_HELP;
6545                 }
6546                 break;
6547         }
6548
6549         argv += optind;
6550         argc -= optind;
6551         if (argc == 0) {
6552                 fprintf(stderr, "%s: missing file or directory target(s)\n",
6553                         progname);
6554                 return CMD_HELP;
6555         }
6556
6557         for (i = 0; i < argc; i++) {
6558                 switch (op) {
6559                 case LFS_PROJECT_CHECK:
6560                         err = lfs_project_check(argv[i], &phc);
6561                         break;
6562                 case LFS_PROJECT_LIST:
6563                         err = lfs_project_list(argv[i], &phc);
6564                         break;
6565                 case LFS_PROJECT_CLEAR:
6566                         err = lfs_project_clear(argv[i], &phc);
6567                         break;
6568                 case LFS_PROJECT_SET:
6569                         err = lfs_project_set(argv[i], &phc);
6570                         break;
6571                 default:
6572                         break;
6573                 }
6574                 if (err && !ret)
6575                         ret = err;
6576         }
6577
6578         return ret;
6579 }
6580
6581 static int lfs_quota(int argc, char **argv)
6582 {
6583         int c;
6584         char *mnt, *name = NULL;
6585         struct if_quotactl qctl = { .qc_cmd = LUSTRE_Q_GETQUOTA,
6586                                     .qc_type = ALLQUOTA };
6587         char *obd_uuid = (char *)qctl.obd_uuid.uuid;
6588         int rc = 0, rc1 = 0, verbose = 0, quiet = 0;
6589         char *endptr;
6590         __u32 valid = QC_GENERAL, idx = 0;
6591         bool human_readable = false;
6592         bool show_default = false;
6593         int qtype;
6594
6595         while ((c = getopt(argc, argv, "gGi:I:o:pPqtuUvh")) != -1) {
6596                 switch (c) {
6597                 case 'U':
6598                         show_default = true;
6599                 case 'u':
6600                         qtype = USRQUOTA;
6601                         goto quota_type;
6602                 case 'G':
6603                         show_default = true;
6604                 case 'g':
6605                         qtype = GRPQUOTA;
6606                         goto quota_type;
6607                 case 'P':
6608                         show_default = true;
6609                 case 'p':
6610                         qtype = PRJQUOTA;
6611 quota_type:
6612                         if (qctl.qc_type != ALLQUOTA) {
6613                                 fprintf(stderr,
6614                                         "%s quota: only one of -u, -g, or -p may be specified\n",
6615                                         progname);
6616                                 return CMD_HELP;
6617                         }
6618                         qctl.qc_type = qtype;
6619                         break;
6620                 case 't':
6621                         qctl.qc_cmd = LUSTRE_Q_GETINFO;
6622                         break;
6623                 case 'o':
6624                         valid = qctl.qc_valid = QC_UUID;
6625                         snprintf(obd_uuid, sizeof(qctl.obd_uuid), "%s", optarg);
6626                         break;
6627                 case 'i':
6628                         valid = qctl.qc_valid = QC_MDTIDX;
6629                         idx = qctl.qc_idx = atoi(optarg);
6630                         if (idx == 0 && *optarg != '0') {
6631                                 fprintf(stderr,
6632                                         "%s quota: invalid MDT index '%s'\n",
6633                                         progname, optarg);
6634                                 return CMD_HELP;
6635                         }
6636                         break;
6637                 case 'I':
6638                         valid = qctl.qc_valid = QC_OSTIDX;
6639                         idx = qctl.qc_idx = atoi(optarg);
6640                         if (idx == 0 && *optarg != '0') {
6641                                 fprintf(stderr,
6642                                         "%s quota: invalid OST index '%s'\n",
6643                                         progname, optarg);
6644                                 return CMD_HELP;
6645                         }
6646                         break;
6647                 case 'v':
6648                         verbose = 1;
6649                         break;
6650                 case 'q':
6651                         quiet = 1;
6652                         break;
6653                 case 'h':
6654                         human_readable = true;
6655                         break;
6656                 default:
6657                         fprintf(stderr, "%s quota: unrecognized option '%s'\n",
6658                                 progname, argv[optind - 1]);
6659                         return CMD_HELP;
6660                 }
6661         }
6662
6663         /* current uid/gid info for "lfs quota /path/to/lustre/mount" */
6664         if (qctl.qc_cmd == LUSTRE_Q_GETQUOTA && qctl.qc_type == ALLQUOTA &&
6665             optind == argc - 1 && !show_default) {
6666
6667                 qctl.qc_cmd = LUSTRE_Q_GETQUOTA;
6668                 qctl.qc_valid = valid;
6669                 qctl.qc_idx = idx;
6670
6671                 for (qtype = USRQUOTA; qtype <= GRPQUOTA; qtype++) {
6672                         qctl.qc_type = qtype;
6673                         if (qtype == USRQUOTA) {
6674                                 qctl.qc_id = geteuid();
6675                                 rc = uid2name(&name, qctl.qc_id);
6676                         } else {
6677                                 qctl.qc_id = getegid();
6678                                 rc = gid2name(&name, qctl.qc_id);
6679                         }
6680                         if (rc)
6681                                 name = "<unknown>";
6682                         mnt = argv[optind];
6683                         rc1 = get_print_quota(mnt, name, &qctl, verbose, quiet,
6684                                               human_readable, show_default);
6685                         if (rc1 && !rc)
6686                                 rc = rc1;
6687                 }
6688                 return rc;
6689         /* lfs quota -u username /path/to/lustre/mount */
6690         } else if (qctl.qc_cmd == LUSTRE_Q_GETQUOTA) {
6691                 /* options should be followed by u/g-name and mntpoint */
6692                 if ((!show_default && optind + 2 != argc) ||
6693                     (show_default && optind + 1 != argc) ||
6694                     qctl.qc_type == ALLQUOTA) {
6695                         fprintf(stderr,
6696                                 "%s quota: name and mount point must be specified\n",
6697                                 progname);
6698                         return CMD_HELP;
6699                 }
6700
6701                 if (!show_default) {
6702                         name = argv[optind++];
6703                         switch (qctl.qc_type) {
6704                         case USRQUOTA:
6705                                 rc = name2uid(&qctl.qc_id, name);
6706                                 break;
6707                         case GRPQUOTA:
6708                                 rc = name2gid(&qctl.qc_id, name);
6709                                 break;
6710                         case PRJQUOTA:
6711                                 rc = name2projid(&qctl.qc_id, name);
6712                                 break;
6713                         default:
6714                                 rc = -ENOTSUP;
6715                                 break;
6716                         }
6717                 } else {
6718                         qctl.qc_valid = QC_GENERAL;
6719                         qctl.qc_cmd = LUSTRE_Q_GETDEFAULT;
6720                         qctl.qc_id = 0;
6721                 }
6722
6723                 if (rc) {
6724                         qctl.qc_id = strtoul(name, &endptr, 10);
6725                         if (*endptr != '\0') {
6726                                 fprintf(stderr, "%s quota: invalid id '%s'\n",
6727                                         progname, name);
6728                                 return CMD_HELP;
6729                         }
6730                 }
6731         } else if (optind + 1 != argc || qctl.qc_type == ALLQUOTA) {
6732                 fprintf(stderr, "%s quota: missing quota info argument(s)\n",
6733                         progname);
6734                 return CMD_HELP;
6735         }
6736
6737         mnt = argv[optind];
6738         rc = get_print_quota(mnt, name, &qctl, verbose, quiet,
6739                              human_readable, show_default);
6740         return rc;
6741 }
6742 #endif /* HAVE_SYS_QUOTA_H! */
6743
6744 static int flushctx_ioctl(char *mp)
6745 {
6746         int fd, rc;
6747
6748         fd = open(mp, O_RDONLY);
6749         if (fd == -1) {
6750                 fprintf(stderr, "flushctx: error open %s: %s\n",
6751                         mp, strerror(errno));
6752                 return -1;
6753         }
6754
6755         rc = ioctl(fd, LL_IOC_FLUSHCTX);
6756         if (rc == -1)
6757                 fprintf(stderr, "flushctx: error ioctl %s: %s\n",
6758                         mp, strerror(errno));
6759
6760         close(fd);
6761         return rc;
6762 }
6763
6764 static int lfs_flushctx(int argc, char **argv)
6765 {
6766         int     kdestroy = 0, c;
6767         char    mntdir[PATH_MAX] = {'\0'};
6768         int     index = 0;
6769         int     rc = 0;
6770
6771         while ((c = getopt(argc, argv, "k")) != -1) {
6772                 switch (c) {
6773                 case 'k':
6774                         kdestroy = 1;
6775                         break;
6776                 default:
6777                         fprintf(stderr, "error: %s: option '-%c' "
6778                                         "unrecognized\n", argv[0], c);
6779                         return CMD_HELP;
6780                 }
6781         }
6782
6783         if (kdestroy) {
6784             if ((rc = system("kdestroy > /dev/null")) != 0) {
6785                 rc = WEXITSTATUS(rc);
6786                 fprintf(stderr, "error destroying tickets: %d, continuing\n", rc);
6787             }
6788         }
6789
6790         if (optind >= argc) {
6791                 /* flush for all mounted lustre fs. */
6792                 while (!llapi_search_mounts(NULL, index++, mntdir, NULL)) {
6793                         /* Check if we have a mount point */
6794                         if (mntdir[0] == '\0')
6795                                 continue;
6796
6797                         if (flushctx_ioctl(mntdir))
6798                                 rc = -1;
6799
6800                         mntdir[0] = '\0'; /* avoid matching in next loop */
6801                 }
6802         } else {
6803                 /* flush fs as specified */
6804                 while (optind < argc) {
6805                         if (flushctx_ioctl(argv[optind++]))
6806                                 rc = -1;
6807                 }
6808         }
6809         return rc;
6810 }
6811
6812 static int lfs_changelog(int argc, char **argv)
6813 {
6814         void *changelog_priv;
6815         struct changelog_rec *rec;
6816         long long startrec = 0, endrec = 0;
6817         char *mdd;
6818         struct option long_opts[] = {
6819                 { .val = 'f', .name = "follow", .has_arg = no_argument },
6820                 { .name = NULL } };
6821         char short_opts[] = "f";
6822         int rc, follow = 0;
6823
6824         while ((rc = getopt_long(argc, argv, short_opts,
6825                 long_opts, NULL)) != -1) {
6826                 switch (rc) {
6827                 case 'f':
6828                         follow++;
6829                         break;
6830                 default:
6831                         fprintf(stderr,
6832                                 "%s changelog: unrecognized option '%s'\n",
6833                                 progname, argv[optind - 1]);
6834                         return CMD_HELP;
6835                 }
6836         }
6837         if (optind >= argc) {
6838                 fprintf(stderr, "%s changelog: mdtname must be specified\n",
6839                         progname);
6840                 return CMD_HELP;
6841         }
6842
6843         mdd = argv[optind++];
6844         if (argc > optind)
6845                 startrec = strtoll(argv[optind++], NULL, 10);
6846         if (argc > optind)
6847                 endrec = strtoll(argv[optind++], NULL, 10);
6848
6849         rc = llapi_changelog_start(&changelog_priv,
6850                                    CHANGELOG_FLAG_BLOCK |
6851                                    CHANGELOG_FLAG_JOBID |
6852                                    CHANGELOG_FLAG_EXTRA_FLAGS |
6853                                    (follow ? CHANGELOG_FLAG_FOLLOW : 0),
6854                                    mdd, startrec);
6855         if (rc < 0) {
6856                 fprintf(stderr, "%s changelog: cannot start changelog: %s\n",
6857                         progname, strerror(errno = -rc));
6858                 return rc;
6859         }
6860
6861         rc = llapi_changelog_set_xflags(changelog_priv,
6862                                         CHANGELOG_EXTRA_FLAG_UIDGID |
6863                                         CHANGELOG_EXTRA_FLAG_NID |
6864                                         CHANGELOG_EXTRA_FLAG_OMODE |
6865                                         CHANGELOG_EXTRA_FLAG_XATTR);
6866         if (rc < 0) {
6867                 fprintf(stderr,
6868                         "%s changelog: cannot set xflags for changelog: %s\n",
6869                         progname, strerror(errno = -rc));
6870                 return rc;
6871         }
6872
6873         while ((rc = llapi_changelog_recv(changelog_priv, &rec)) == 0) {
6874                 time_t secs;
6875                 struct tm ts;
6876
6877                 if (endrec && rec->cr_index > endrec) {
6878                         llapi_changelog_free(&rec);
6879                         break;
6880                 }
6881                 if (rec->cr_index < startrec) {
6882                         llapi_changelog_free(&rec);
6883                         continue;
6884                 }
6885
6886                 secs = rec->cr_time >> 30;
6887                 gmtime_r(&secs, &ts);
6888                 printf("%ju %02d%-5s %02d:%02d:%02d.%09d %04d.%02d.%02d "
6889                        "0x%x t="DFID, (uintmax_t)rec->cr_index, rec->cr_type,
6890                        changelog_type2str(rec->cr_type),
6891                        ts.tm_hour, ts.tm_min, ts.tm_sec,
6892                        (int)(rec->cr_time & ((1 << 30) - 1)),
6893                        ts.tm_year + 1900, ts.tm_mon + 1, ts.tm_mday,
6894                        rec->cr_flags & CLF_FLAGMASK, PFID(&rec->cr_tfid));
6895
6896                 if (rec->cr_flags & CLF_JOBID) {
6897                         struct changelog_ext_jobid *jid =
6898                                 changelog_rec_jobid(rec);
6899
6900                         if (jid->cr_jobid[0] != '\0')
6901                                 printf(" j=%s", jid->cr_jobid);
6902                 }
6903
6904                 if (rec->cr_flags & CLF_EXTRA_FLAGS) {
6905                         struct changelog_ext_extra_flags *ef =
6906                                 changelog_rec_extra_flags(rec);
6907
6908                         printf(" ef=0x%llx",
6909                                (unsigned long long)ef->cr_extra_flags);
6910
6911                         if (ef->cr_extra_flags & CLFE_UIDGID) {
6912                                 struct changelog_ext_uidgid *uidgid =
6913                                         changelog_rec_uidgid(rec);
6914
6915                                 printf(" u=%llu:%llu",
6916                                        (unsigned long long)uidgid->cr_uid,
6917                                        (unsigned long long)uidgid->cr_gid);
6918                         }
6919                         if (ef->cr_extra_flags & CLFE_NID) {
6920                                 struct changelog_ext_nid *nid =
6921                                         changelog_rec_nid(rec);
6922
6923                                 printf(" nid=%s",
6924                                        libcfs_nid2str(nid->cr_nid));
6925                         }
6926
6927                         if (ef->cr_extra_flags & CLFE_OPEN) {
6928                                 struct changelog_ext_openmode *omd =
6929                                         changelog_rec_openmode(rec);
6930                                 char mode[] = "---";
6931
6932                                 /* exec mode must be exclusive */
6933                                 if (omd->cr_openflags & MDS_FMODE_EXEC) {
6934                                         mode[2] = 'x';
6935                                 } else {
6936                                         if (omd->cr_openflags & MDS_FMODE_READ)
6937                                                 mode[0] = 'r';
6938                                         if (omd->cr_openflags &
6939                                             (MDS_FMODE_WRITE |
6940                                              MDS_OPEN_TRUNC |
6941                                              MDS_OPEN_APPEND))
6942                                                 mode[1] = 'w';
6943                                 }
6944
6945                                 if (strcmp(mode, "---") != 0)
6946                                         printf(" m=%s", mode);
6947
6948                         }
6949
6950                         if (ef->cr_extra_flags & CLFE_XATTR) {
6951                                 struct changelog_ext_xattr *xattr =
6952                                         changelog_rec_xattr(rec);
6953
6954                                 if (xattr->cr_xattr[0] != '\0')
6955                                         printf(" x=%s", xattr->cr_xattr);
6956                         }
6957                 }
6958
6959                 if (rec->cr_namelen)
6960                         printf(" p="DFID" %.*s", PFID(&rec->cr_pfid),
6961                                rec->cr_namelen, changelog_rec_name(rec));
6962
6963                 if (rec->cr_flags & CLF_RENAME) {
6964                         struct changelog_ext_rename *rnm =
6965                                 changelog_rec_rename(rec);
6966
6967                         if (!fid_is_zero(&rnm->cr_sfid))
6968                                 printf(" s="DFID" sp="DFID" %.*s",
6969                                        PFID(&rnm->cr_sfid),
6970                                        PFID(&rnm->cr_spfid),
6971                                        (int)changelog_rec_snamelen(rec),
6972                                        changelog_rec_sname(rec));
6973                 }
6974                 printf("\n");
6975
6976                 llapi_changelog_free(&rec);
6977         }
6978
6979         llapi_changelog_fini(&changelog_priv);
6980
6981         if (rc < 0)
6982                 fprintf(stderr, "%s changelog: cannot access changelog: %s\n",
6983                         progname, strerror(errno = -rc));
6984
6985         return (rc == 1 ? 0 : rc);
6986 }
6987
6988 static int lfs_changelog_clear(int argc, char **argv)
6989 {
6990         long long endrec;
6991         int rc;
6992
6993         if (argc != 4)
6994                 return CMD_HELP;
6995
6996         endrec = strtoll(argv[3], NULL, 10);
6997
6998         rc = llapi_changelog_clear(argv[1], argv[2], endrec);
6999
7000         if (rc == -EINVAL)
7001                 fprintf(stderr, "%s: record out of range: %llu\n",
7002                         argv[0], endrec);
7003         else if (rc == -ENOENT)
7004                 fprintf(stderr, "%s: no changelog user: %s\n",
7005                         argv[0], argv[2]);
7006         else if (rc)
7007                 fprintf(stderr, "%s error: %s\n", argv[0],
7008                         strerror(-rc));
7009
7010         if (rc)
7011                 errno = -rc;
7012
7013         return rc;
7014 }
7015
7016 static int lfs_fid2path(int argc, char **argv)
7017 {
7018         struct option long_opts[] = {
7019                 { .val = 'c',   .name = "cur",  .has_arg = no_argument },
7020                 { .val = 'l',   .name = "link", .has_arg = required_argument },
7021                 { .val = 'r',   .name = "rec",  .has_arg = required_argument },
7022                 { .name = NULL } };
7023         char  short_opts[] = "cl:r:";
7024         char *device, *fid, *path;
7025         long long recno = -1;
7026         int linkno = -1;
7027         int lnktmp;
7028         int printcur = 0;
7029         int rc = 0;
7030         char *endptr = NULL;
7031
7032         while ((rc = getopt_long(argc, argv, short_opts,
7033                 long_opts, NULL)) != -1) {
7034                 switch (rc) {
7035                 case 'c':
7036                         printcur++;
7037                         break;
7038                 case 'l':
7039                         linkno = strtol(optarg, &endptr, 10);
7040                         if (*endptr != '\0') {
7041                                 fprintf(stderr,
7042                                         "%s fid2path: invalid linkno '%s'\n",
7043                                         progname, optarg);
7044                                 return CMD_HELP;
7045                         }
7046                         break;
7047                 case 'r':
7048                         recno = strtoll(optarg, &endptr, 10);
7049                         if (*endptr != '\0') {
7050                                 fprintf(stderr,
7051                                         "%s fid2path: invalid recno '%s'\n",
7052                                         progname, optarg);
7053                                 return CMD_HELP;
7054                         }
7055                         break;
7056                 default:
7057                         fprintf(stderr,
7058                                 "%s fid2path: unrecognized option '%s'\n",
7059                                 progname, argv[optind - 1]);
7060                         return CMD_HELP;
7061                 }
7062         }
7063
7064         if (argc < 3) {
7065                 fprintf(stderr,
7066                         "%s fid2path: <fsname|rootpath> and <fid>... must be specified\n",
7067                         progname);
7068                 return CMD_HELP;
7069         }
7070
7071         device = argv[optind++];
7072         path = calloc(1, PATH_MAX);
7073         if (path == NULL) {
7074                 rc = -errno;
7075                 fprintf(stderr,
7076                         "%s fid2path: cannot allocate memory for path: %s\n",
7077                         progname, strerror(-rc));
7078                 return rc;
7079         }
7080
7081         rc = 0;
7082         while (optind < argc) {
7083                 fid = argv[optind++];
7084
7085                 lnktmp = (linkno >= 0) ? linkno : 0;
7086                 while (1) {
7087                         int oldtmp = lnktmp;
7088                         long long rectmp = recno;
7089                         int rc2;
7090                         rc2 = llapi_fid2path(device, fid, path, PATH_MAX,
7091                                              &rectmp, &lnktmp);
7092                         if (rc2 < 0) {
7093                                 fprintf(stderr,
7094                                         "%s fid2path: cannot find '%s': %s\n",
7095                                         progname, fid, strerror(errno = -rc2));
7096                                 if (rc == 0)
7097                                         rc = rc2;
7098                                 break;
7099                         }
7100
7101                         if (printcur)
7102                                 fprintf(stdout, "%lld ", rectmp);
7103                         if (device[0] == '/') {
7104                                 fprintf(stdout, "%s", device);
7105                                 if (device[strlen(device) - 1] != '/')
7106                                         fprintf(stdout, "/");
7107                         } else if (path[0] == '\0') {
7108                                 fprintf(stdout, "/");
7109                         }
7110                         fprintf(stdout, "%s\n", path);
7111
7112                         if (linkno >= 0)
7113                                 /* specified linkno */
7114                                 break;
7115                         if (oldtmp == lnktmp)
7116                                 /* no more links */
7117                                 break;
7118                 }
7119         }
7120
7121         free(path);
7122         return rc;
7123 }
7124
7125 static int lfs_path2fid(int argc, char **argv)
7126 {
7127         struct option long_opts[] = {
7128                 { .val = 'p', .name = "parents", .has_arg = no_argument },
7129                 { .name = NULL } };
7130         char            **path;
7131         const char        short_opts[] = "p";
7132         const char       *sep = "";
7133         struct lu_fid     fid;
7134         int               rc = 0;
7135         bool              show_parents = false;
7136
7137         while ((rc = getopt_long(argc, argv, short_opts,
7138                                  long_opts, NULL)) != -1) {
7139                 switch (rc) {
7140                 case 'p':
7141                         show_parents = true;
7142                         break;
7143                 default:
7144                         fprintf(stderr,
7145                                 "%s path2fid: unrecognized option '%s'\n",
7146                                 progname, argv[optind - 1]);
7147                         return CMD_HELP;
7148                 }
7149         }
7150
7151         if (optind > argc - 1) {
7152                 fprintf(stderr, "%s path2fid: FILE... must be specified\n",
7153                         progname);
7154                 return CMD_HELP;
7155         }
7156         else if (optind < argc - 1)
7157                 sep = ": ";
7158
7159         rc = 0;
7160         for (path = argv + optind; *path != NULL; path++) {
7161                 int err = 0;
7162                 if (!show_parents) {
7163                         err = llapi_path2fid(*path, &fid);
7164                         if (!err)
7165                                 printf("%s%s"DFID"\n",
7166                                        *sep != '\0' ? *path : "", sep,
7167                                        PFID(&fid));
7168                 } else {
7169                         char            name[NAME_MAX + 1];
7170                         unsigned int    linkno = 0;
7171
7172                         while ((err = llapi_path2parent(*path, linkno, &fid,
7173                                                 name, sizeof(name))) == 0) {
7174                                 if (*sep != '\0' && linkno == 0)
7175                                         printf("%s%s", *path, sep);
7176
7177                                 printf("%s"DFID"/%s", linkno != 0 ? "\t" : "",
7178                                        PFID(&fid), name);
7179                                 linkno++;
7180                         }
7181
7182                         /* err == -ENODATA is end-of-loop */
7183                         if (linkno > 0 && err == -ENODATA) {
7184                                 printf("\n");
7185                                 err = 0;
7186                         }
7187                 }
7188
7189                 if (err) {
7190                         fprintf(stderr,
7191                                 "%s path2fid: cannot get %sfid for '%s': %s\n",
7192                                 progname, show_parents ? "parent " : "", *path,
7193                                 strerror(-err));
7194                         if (rc == 0) {
7195                                 rc = err;
7196                                 errno = -err;
7197                         }
7198                 }
7199         }
7200
7201         return rc;
7202 }
7203
7204 #define MAX_ERRNO       4095
7205 #define IS_ERR_VALUE(x) ((unsigned long)(x) >= (unsigned long)-MAX_ERRNO)
7206
7207 static int lfs_rmfid_and_show_errors(const char *device, struct fid_array *fa)
7208 {
7209         int rc, rc2 = 0, k;
7210
7211         rc = llapi_rmfid(device, fa);
7212         if (rc) {
7213                 fprintf(stderr, "rmfid(): rc = %d\n", rc);
7214                 return rc;
7215         }
7216
7217         for (k = 0; k < fa->fa_nr; k++) {
7218                 rc = (__s32)fa->fa_fids[k].f_ver;
7219                 if (!IS_ERR_VALUE(rc))
7220                         continue;
7221                 if (!rc2 && rc)
7222                         rc2 = rc;
7223                 if (!rc)
7224                         continue;
7225                 fa->fa_fids[k].f_ver = 0;
7226                 fprintf(stderr, "rmfid("DFID"): rc = %d\n",
7227                         PFID(&fa->fa_fids[k]), rc);
7228         }
7229
7230         return rc2;
7231 }
7232
7233 static int lfs_rmfid(int argc, char **argv)
7234 {
7235         char *fidstr, *device;
7236         int rc = 0, rc2, nr;
7237         struct fid_array *fa;
7238
7239         if (optind > argc - 1) {
7240                 fprintf(stderr, "%s rmfid: missing dirname\n", progname);
7241                 return CMD_HELP;
7242         }
7243
7244         device = argv[optind++];
7245
7246         nr = argc - optind;
7247         fa = malloc(offsetof(struct fid_array, fa_fids[nr + 1]));
7248         if (fa == NULL)
7249                 return -ENOMEM;
7250
7251         fa->fa_nr = 0;
7252         rc = 0;
7253         while (optind < argc) {
7254                 int found;
7255
7256                 fidstr = argv[optind++];
7257                 while (*fidstr == '[')
7258                         fidstr++;
7259                 found = sscanf(fidstr, SFID, RFID(&fa->fa_fids[fa->fa_nr]));
7260                 if (found != 3) {
7261                         fprintf(stderr, "unrecognized FID: %s\n",
7262                                 argv[optind - 1]);
7263                         exit(1);
7264                 }
7265                 fa->fa_nr++;
7266                 if (fa->fa_nr == OBD_MAX_FIDS_IN_ARRAY) {
7267                         /* start another batch */
7268                         rc2 = lfs_rmfid_and_show_errors(device, fa);
7269                         if (rc2 && !rc)
7270                                 rc = rc2;
7271                         fa->fa_nr = 0;
7272                 }
7273         }
7274         if (fa->fa_nr) {
7275                 rc2 = lfs_rmfid_and_show_errors(device, fa);
7276                 if (rc2 && !rc)
7277                         rc = rc2;
7278         }
7279
7280         return rc;
7281 }
7282
7283 static int lfs_data_version(int argc, char **argv)
7284 {
7285         char *path;
7286         __u64 data_version;
7287         int fd;
7288         int rc;
7289         int c;
7290         int data_version_flags = LL_DV_RD_FLUSH; /* Read by default */
7291
7292         if (argc < 2) {
7293                 fprintf(stderr, "%s data_version: FILE must be specified\n",
7294                         progname);
7295                 return CMD_HELP;
7296         }
7297
7298         while ((c = getopt(argc, argv, "nrw")) != -1) {
7299                 switch (c) {
7300                 case 'n':
7301                         data_version_flags = 0;
7302                         break;
7303                 case 'r':
7304                         data_version_flags |= LL_DV_RD_FLUSH;
7305                         break;
7306                 case 'w':
7307                         data_version_flags |= LL_DV_WR_FLUSH;
7308                         break;
7309                 default:
7310                         fprintf(stderr,
7311                                 "%s data_version: unrecognized option '%s'\n",
7312                                 progname, argv[optind - 1]);
7313                         return CMD_HELP;
7314                 }
7315         }
7316         if (optind == argc) {
7317                 fprintf(stderr, "%s data_version: FILE must be specified\n",
7318                         progname);
7319                 return CMD_HELP;
7320         }
7321
7322         path = argv[optind];
7323         fd = open(path, O_RDONLY);
7324         if (fd < 0) {
7325                 rc = -errno;
7326                 fprintf(stderr, "%s data_version: cannot open file '%s': %s\n",
7327                         progname, path, strerror(-rc));
7328                 return rc;
7329         }
7330
7331         rc = llapi_get_data_version(fd, &data_version, data_version_flags);
7332         if (rc < 0)
7333                 fprintf(stderr,
7334                         "%s data_version: cannot get version for '%s': %s\n",
7335                         progname, path, strerror(-rc));
7336         else
7337                 printf("%ju" "\n", (uintmax_t)data_version);
7338
7339         close(fd);
7340         return rc;
7341 }
7342
7343 static int lfs_hsm_state(int argc, char **argv)
7344 {
7345         int rc;
7346         int i = 1;
7347         char *path;
7348         struct hsm_user_state hus;
7349
7350         if (argc < 2)
7351                 return CMD_HELP;
7352
7353         do {
7354                 path = argv[i];
7355
7356                 rc = llapi_hsm_state_get(path, &hus);
7357                 if (rc) {
7358                         fprintf(stderr, "can't get hsm state for %s: %s\n",
7359                                 path, strerror(errno = -rc));
7360                         return rc;
7361                 }
7362
7363                 /* Display path name and status flags */
7364                 printf("%s: (0x%08x)", path, hus.hus_states);
7365
7366                 if (hus.hus_states & HS_RELEASED)
7367                         printf(" released");
7368                 if (hus.hus_states & HS_EXISTS)
7369                         printf(" exists");
7370                 if (hus.hus_states & HS_DIRTY)
7371                         printf(" dirty");
7372                 if (hus.hus_states & HS_ARCHIVED)
7373                         printf(" archived");
7374                 /* Display user-settable flags */
7375                 if (hus.hus_states & HS_NORELEASE)
7376                         printf(" never_release");
7377                 if (hus.hus_states & HS_NOARCHIVE)
7378                         printf(" never_archive");
7379                 if (hus.hus_states & HS_LOST)
7380                         printf(" lost_from_hsm");
7381
7382                 if (hus.hus_archive_id != 0)
7383                         printf(", archive_id:%d", hus.hus_archive_id);
7384                 printf("\n");
7385
7386         } while (++i < argc);
7387
7388         return 0;
7389 }
7390
7391 #define LFS_HSM_SET   0
7392 #define LFS_HSM_CLEAR 1
7393
7394 /**
7395  * Generic function to set or clear HSM flags.
7396  * Used by hsm_set and hsm_clear.
7397  *
7398  * @mode  if LFS_HSM_SET, set the flags, if LFS_HSM_CLEAR, clear the flags.
7399  */
7400 static int lfs_hsm_change_flags(int argc, char **argv, int mode)
7401 {
7402         struct option long_opts[] = {
7403         { .val = 'A',   .name = "archived",     .has_arg = no_argument },
7404         { .val = 'a',   .name = "noarchive",    .has_arg = no_argument },
7405         { .val = 'd',   .name = "dirty",        .has_arg = no_argument },
7406         { .val = 'e',   .name = "exists",       .has_arg = no_argument },
7407         { .val = 'l',   .name = "lost",         .has_arg = no_argument },
7408         { .val = 'r',   .name = "norelease",    .has_arg = no_argument },
7409         { .val = 'i',   .name = "archive-id",   .has_arg = required_argument },
7410         { .name = NULL } };
7411         char short_opts[] = "lraAdei:";
7412         __u64 mask = 0;
7413         int c, rc;
7414         char *path;
7415         __u32 archive_id = 0;
7416         char *end = NULL;
7417
7418         if (argc < 3)
7419                 return CMD_HELP;
7420
7421         while ((c = getopt_long(argc, argv, short_opts,
7422                                 long_opts, NULL)) != -1) {
7423                 switch (c) {
7424                 case 'l':
7425                         mask |= HS_LOST;
7426                         break;
7427                 case 'a':
7428                         mask |= HS_NOARCHIVE;
7429                         break;
7430                 case 'A':
7431                         mask |= HS_ARCHIVED;
7432                         break;
7433                 case 'r':
7434                         mask |= HS_NORELEASE;
7435                         break;
7436                 case 'd':
7437                         mask |= HS_DIRTY;
7438                         break;
7439                 case 'e':
7440                         mask |= HS_EXISTS;
7441                         break;
7442                 case 'i':
7443                         archive_id = strtol(optarg, &end, 10);
7444                         if (*end != '\0') {
7445                                 fprintf(stderr, "invalid archive_id: '%s'\n",
7446                                         end);
7447                                 return CMD_HELP;
7448                         }
7449                         break;
7450                 case '?':
7451                         return CMD_HELP;
7452                 default:
7453                         fprintf(stderr, "error: %s: option '%s' unrecognized\n",
7454                                 argv[0], argv[optind - 1]);
7455                         return CMD_HELP;
7456                 }
7457         }
7458
7459         /* User should have specified a flag */
7460         if (mask == 0)
7461                 return CMD_HELP;
7462
7463         while (optind < argc) {
7464
7465                 path = argv[optind];
7466
7467                 /* If mode == 0, this means we apply the mask. */
7468                 if (mode == LFS_HSM_SET)
7469                         rc = llapi_hsm_state_set(path, mask, 0, archive_id);
7470                 else
7471                         rc = llapi_hsm_state_set(path, 0, mask, 0);
7472
7473                 if (rc != 0) {
7474                         fprintf(stderr, "Can't change hsm flags for %s: %s\n",
7475                                 path, strerror(errno = -rc));
7476                         return rc;
7477                 }
7478                 optind++;
7479         }
7480
7481         return 0;
7482 }
7483
7484 static int lfs_hsm_action(int argc, char **argv)
7485 {
7486         int                              rc;
7487         int                              i = 1;
7488         char                            *path;
7489         struct hsm_current_action        hca;
7490         struct hsm_extent                he;
7491         enum hsm_user_action             hua;
7492         enum hsm_progress_states         hps;
7493
7494         if (argc < 2)
7495                 return CMD_HELP;
7496
7497         do {
7498                 path = argv[i];
7499
7500                 rc = llapi_hsm_current_action(path, &hca);
7501                 if (rc) {
7502                         fprintf(stderr, "can't get hsm action for %s: %s\n",
7503                                 path, strerror(errno = -rc));
7504                         return rc;
7505                 }
7506                 he = hca.hca_location;
7507                 hua = hca.hca_action;
7508                 hps = hca.hca_state;
7509
7510                 printf("%s: %s", path, hsm_user_action2name(hua));
7511
7512                 /* Skip file without action */
7513                 if (hca.hca_action == HUA_NONE) {
7514                         printf("\n");
7515                         continue;
7516                 }
7517
7518                 printf(" %s ", hsm_progress_state2name(hps));
7519
7520                 if ((hps == HPS_RUNNING) &&
7521                     (hua == HUA_ARCHIVE || hua == HUA_RESTORE))
7522                         printf("(%llu bytes moved)\n",
7523                                (unsigned long long)he.length);
7524                 else if ((he.offset + he.length) == LUSTRE_EOF)
7525                         printf("(from %llu to EOF)\n",
7526                                (unsigned long long)he.offset);
7527                 else
7528                         printf("(from %llu to %llu)\n",
7529                                (unsigned long long)he.offset,
7530                                (unsigned long long)(he.offset + he.length));
7531
7532         } while (++i < argc);
7533
7534         return 0;
7535 }
7536
7537 static int lfs_hsm_set(int argc, char **argv)
7538 {
7539         return lfs_hsm_change_flags(argc, argv, LFS_HSM_SET);
7540 }
7541
7542 static int lfs_hsm_clear(int argc, char **argv)
7543 {
7544         return lfs_hsm_change_flags(argc, argv, LFS_HSM_CLEAR);
7545 }
7546
7547 /**
7548  * Check file state and return its fid, to be used by lfs_hsm_request().
7549  *
7550  * \param[in]     file      Path to file to check
7551  * \param[in,out] fid       Pointer to allocated lu_fid struct.
7552  * \param[in,out] last_dev  Pointer to last device id used.
7553  *
7554  * \return 0 on success.
7555  */
7556 static int lfs_hsm_prepare_file(const char *file, struct lu_fid *fid,
7557                                 dev_t *last_dev)
7558 {
7559         struct stat     st;
7560         int             rc;
7561
7562         rc = lstat(file, &st);
7563         if (rc) {
7564                 fprintf(stderr, "Cannot stat %s: %s\n", file, strerror(errno));
7565                 return -errno;
7566         }
7567         /* Checking for regular file as archiving as posix copytool
7568          * rejects archiving files other than regular files
7569          */
7570         if (!S_ISREG(st.st_mode)) {
7571                 fprintf(stderr, "error: \"%s\" is not a regular file\n", file);
7572                 return CMD_HELP;
7573         }
7574         /* A request should be ... */
7575         if (*last_dev != st.st_dev && *last_dev != 0) {
7576                 fprintf(stderr, "All files should be "
7577                         "on the same filesystem: %s\n", file);
7578                 return -EINVAL;
7579         }
7580         *last_dev = st.st_dev;
7581
7582         rc = llapi_path2fid(file, fid);
7583         if (rc) {
7584                 fprintf(stderr, "Cannot read FID of %s: %s\n",
7585                         file, strerror(-rc));
7586                 return rc;
7587         }
7588         return 0;
7589 }
7590
7591 /* Fill an HSM HUR item with a given file name.
7592  *
7593  * If mntpath is set, then the filename is actually a FID, and no
7594  * lookup on the filesystem will be performed.
7595  *
7596  * \param[in]  hur         the user request to fill
7597  * \param[in]  idx         index of the item inside the HUR to fill
7598  * \param[in]  mntpath     mountpoint of Lustre
7599  * \param[in]  fname       filename (if mtnpath is NULL)
7600  *                         or FID (if mntpath is set)
7601  * \param[in]  last_dev    pointer to last device id used
7602  *
7603  * \retval 0 on success
7604  * \retval CMD_HELP or a negative errno on error
7605  */
7606 static int fill_hur_item(struct hsm_user_request *hur, unsigned int idx,
7607                          const char *mntpath, const char *fname,
7608                          dev_t *last_dev)
7609 {
7610         struct hsm_user_item *hui = &hur->hur_user_item[idx];
7611         int rc;
7612
7613         hui->hui_extent.length = -1;
7614
7615         if (mntpath != NULL) {
7616                 if (*fname == '[')
7617                         fname++;
7618                 rc = sscanf(fname, SFID, RFID(&hui->hui_fid));
7619                 if (rc == 3) {
7620                         rc = 0;
7621                 } else {
7622                         fprintf(stderr, "hsm: '%s' is not a valid FID\n",
7623                                 fname);
7624                         rc = -EINVAL;
7625                 }
7626         } else {
7627                 rc = lfs_hsm_prepare_file(fname, &hui->hui_fid, last_dev);
7628         }
7629
7630         if (rc == 0)
7631                 hur->hur_request.hr_itemcount++;
7632
7633         return rc;
7634 }
7635
7636 static int lfs_hsm_request(int argc, char **argv, int action)
7637 {
7638         struct option long_opts[] = {
7639         { .val = 'a',   .name = "archive",      .has_arg = required_argument },
7640         { .val = 'D',   .name = "data",         .has_arg = required_argument },
7641         { .val = 'l',   .name = "filelist",     .has_arg = required_argument },
7642         { .val = 'm',   .name = "mntpath",      .has_arg = required_argument },
7643         { .name = NULL } };
7644         dev_t                    last_dev = 0;
7645         char                     short_opts[] = "l:D:a:m:";
7646         struct hsm_user_request *hur, *oldhur;
7647         int                      c, i;
7648         size_t                   len;
7649         int                      nbfile;
7650         char                    *line = NULL;
7651         char                    *filelist = NULL;
7652         char                     fullpath[PATH_MAX];
7653         char                    *opaque = NULL;
7654         int                      opaque_len = 0;
7655         int                      archive_id = 0;
7656         FILE                    *fp;
7657         int                      nbfile_alloc = 0;
7658         char                    *some_file = NULL;
7659         char                    *mntpath = NULL;
7660         int                      rc;
7661
7662         if (argc < 2)
7663                 return CMD_HELP;
7664
7665         while ((c = getopt_long(argc, argv, short_opts,
7666                                 long_opts, NULL)) != -1) {
7667                 switch (c) {
7668                 case 'l':
7669                         filelist = optarg;
7670                         break;
7671                 case 'D':
7672                         opaque = optarg;
7673                         break;
7674                 case 'a':
7675                         if (action != HUA_ARCHIVE &&
7676                             action != HUA_REMOVE) {
7677                                 fprintf(stderr,
7678                                         "error: -a is supported only "
7679                                         "when archiving or removing\n");
7680                                 return CMD_HELP;
7681                         }
7682                         archive_id = atoi(optarg);
7683                         break;
7684                 case 'm':
7685                         if (some_file == NULL) {
7686                                 mntpath = optarg;
7687                                 some_file = strdup(optarg);
7688                         }
7689                         break;
7690                 case '?':
7691                         return CMD_HELP;
7692                 default:
7693                         fprintf(stderr, "error: %s: option '%s' unrecognized\n",
7694                                 argv[0], argv[optind - 1]);
7695                         return CMD_HELP;
7696                 }
7697         }
7698
7699         /* All remaining args are files, so we have at least nbfile */
7700         nbfile = argc - optind;
7701
7702         if ((nbfile == 0) && (filelist == NULL))
7703                 return CMD_HELP;
7704
7705         if (opaque != NULL)
7706                 opaque_len = strlen(opaque);
7707
7708         /* Alloc the request structure with enough place to store all files
7709          * from command line. */
7710         hur = llapi_hsm_user_request_alloc(nbfile, opaque_len);
7711         if (hur == NULL) {
7712                 fprintf(stderr, "Cannot create the request: %s\n",
7713                         strerror(errno));
7714                 return errno;
7715         }
7716         nbfile_alloc = nbfile;
7717
7718         hur->hur_request.hr_action = action;
7719         hur->hur_request.hr_archive_id = archive_id;
7720         hur->hur_request.hr_flags = 0;
7721
7722         /* All remaining args are files, add them */
7723         if (nbfile != 0 && some_file == NULL)
7724                 some_file = strdup(argv[optind]);
7725
7726         for (i = 0; i < nbfile; i++) {
7727                 rc = fill_hur_item(hur, i, mntpath, argv[optind + i],
7728                                    &last_dev);
7729                 if (rc)
7730                         goto out_free;
7731         }
7732
7733         /* from here stop using nb_file, use hur->hur_request.hr_itemcount */
7734
7735         /* If a filelist was specified, read the filelist from it. */
7736         if (filelist != NULL) {
7737                 fp = fopen(filelist, "r");
7738                 if (fp == NULL) {
7739                         fprintf(stderr, "Cannot read the file list %s: %s\n",
7740                                 filelist, strerror(errno));
7741                         rc = -errno;
7742                         goto out_free;
7743                 }
7744
7745                 while ((rc = getline(&line, &len, fp)) != -1) {
7746                         /* If allocated buffer was too small, get something
7747                          * larger */
7748                         if (nbfile_alloc <= hur->hur_request.hr_itemcount) {
7749                                 ssize_t size;
7750
7751                                 nbfile_alloc = nbfile_alloc * 2 + 1;
7752                                 oldhur = hur;
7753                                 hur = llapi_hsm_user_request_alloc(nbfile_alloc,
7754                                                                    opaque_len);
7755                                 if (hur == NULL) {
7756                                         fprintf(stderr, "hsm: cannot allocate "
7757                                                 "the request: %s\n",
7758                                                 strerror(errno));
7759                                         hur = oldhur;
7760                                         rc = -errno;
7761                                         fclose(fp);
7762                                         goto out_free;
7763                                 }
7764                                 size = hur_len(oldhur);
7765                                 if (size < 0) {
7766                                         fprintf(stderr, "hsm: cannot allocate "
7767                                                 "%u files + %u bytes data\n",
7768                                             oldhur->hur_request.hr_itemcount,
7769                                             oldhur->hur_request.hr_data_len);
7770                                         free(hur);
7771                                         hur = oldhur;
7772                                         rc = -E2BIG;
7773                                         fclose(fp);
7774                                         goto out_free;
7775                                 }
7776                                 memcpy(hur, oldhur, size);
7777                                 free(oldhur);
7778                         }
7779
7780                         /* Chop CR */
7781                         if (line[strlen(line) - 1] == '\n')
7782                                 line[strlen(line) - 1] = '\0';
7783
7784                         rc = fill_hur_item(hur, hur->hur_request.hr_itemcount,
7785                                            mntpath, line, &last_dev);
7786                         if (rc) {
7787                                 fclose(fp);
7788                                 goto out_free;
7789                         }
7790
7791                         if (some_file == NULL) {
7792                                 some_file = line;
7793                                 line = NULL;
7794                         }
7795                 }
7796
7797                 rc = fclose(fp);
7798                 free(line);
7799         }
7800
7801         /* If a --data was used, add it to the request */
7802         hur->hur_request.hr_data_len = opaque_len;
7803         if (opaque != NULL)
7804                 memcpy(hur_data(hur), opaque, opaque_len);
7805
7806         /* Send the HSM request */
7807         if (realpath(some_file, fullpath) == NULL) {
7808                 fprintf(stderr, "Could not find path '%s': %s\n",
7809                         some_file, strerror(errno));
7810         }
7811         rc = llapi_hsm_request(fullpath, hur);
7812         if (rc) {
7813                 fprintf(stderr, "Cannot send HSM request (use of %s): %s\n",
7814                         some_file, strerror(-rc));
7815                 goto out_free;
7816         }
7817
7818 out_free:
7819         free(some_file);
7820         free(hur);
7821         return rc;
7822 }
7823
7824 static int lfs_hsm_archive(int argc, char **argv)
7825 {
7826         return lfs_hsm_request(argc, argv, HUA_ARCHIVE);
7827 }
7828
7829 static int lfs_hsm_restore(int argc, char **argv)
7830 {
7831         return lfs_hsm_request(argc, argv, HUA_RESTORE);
7832 }
7833
7834 static int lfs_hsm_release(int argc, char **argv)
7835 {
7836         return lfs_hsm_request(argc, argv, HUA_RELEASE);
7837 }
7838
7839 static int lfs_hsm_remove(int argc, char **argv)
7840 {
7841         return lfs_hsm_request(argc, argv, HUA_REMOVE);
7842 }
7843
7844 static int lfs_hsm_cancel(int argc, char **argv)
7845 {
7846         return lfs_hsm_request(argc, argv, HUA_CANCEL);
7847 }
7848
7849 static int lfs_swap_layouts(int argc, char **argv)
7850 {
7851         if (argc != 3)
7852                 return CMD_HELP;
7853
7854         return llapi_swap_layouts(argv[1], argv[2], 0, 0,
7855                                   SWAP_LAYOUTS_KEEP_MTIME |
7856                                   SWAP_LAYOUTS_KEEP_ATIME);
7857 }
7858
7859 static const char *const ladvise_names[] = LU_LADVISE_NAMES;
7860
7861 static const char *const lock_mode_names[] = LOCK_MODE_NAMES;
7862
7863 int lfs_get_mode(const char *string)
7864 {
7865         enum lock_mode_user mode;
7866
7867         for (mode = 0; mode < ARRAY_SIZE(lock_mode_names); mode++) {
7868                 if (lock_mode_names[mode] == NULL)
7869                         continue;
7870                 if (strcmp(string, lock_mode_names[mode]) == 0)
7871                         return mode;
7872         }
7873
7874         return -EINVAL;
7875 }
7876
7877 static enum lu_ladvise_type lfs_get_ladvice(const char *string)
7878 {
7879         enum lu_ladvise_type advice;
7880
7881         for (advice = 0;
7882              advice < ARRAY_SIZE(ladvise_names); advice++) {
7883                 if (ladvise_names[advice] == NULL)
7884                         continue;
7885                 if (strcmp(string, ladvise_names[advice]) == 0)
7886                         return advice;
7887         }
7888
7889         return LU_LADVISE_INVALID;
7890 }
7891
7892 static int lfs_ladvise(int argc, char **argv)
7893 {
7894         struct option long_opts[] = {
7895         { .val = 'a',   .name = "advice",       .has_arg = required_argument },
7896         { .val = 'b',   .name = "background",   .has_arg = no_argument },
7897         { .val = 'e',   .name = "end",          .has_arg = required_argument },
7898         { .val = 'l',   .name = "length",       .has_arg = required_argument },
7899         { .val = 'm',   .name = "mode",         .has_arg = required_argument },
7900         { .val = 's',   .name = "start",        .has_arg = required_argument },
7901         { .val = 'u',   .name = "unset",        .has_arg = no_argument },
7902         { .name = NULL } };
7903         char                     short_opts[] = "a:be:l:m:s:u";
7904         int                      c;
7905         int                      rc = 0;
7906         const char              *path;
7907         int                      fd;
7908         struct llapi_lu_ladvise  advice;
7909         enum lu_ladvise_type     advice_type = LU_LADVISE_INVALID;
7910         unsigned long long       start = 0;
7911         unsigned long long       end = LUSTRE_EOF;
7912         unsigned long long       length = 0;
7913         unsigned long long       size_units;
7914         unsigned long long       flags = 0;
7915         int                      mode = 0;
7916
7917         optind = 0;
7918         while ((c = getopt_long(argc, argv, short_opts,
7919                                 long_opts, NULL)) != -1) {
7920                 switch (c) {
7921                 case 'a':
7922                         advice_type = lfs_get_ladvice(optarg);
7923                         if (advice_type == LU_LADVISE_INVALID) {
7924                                 fprintf(stderr, "%s: invalid advice type "
7925                                         "'%s'\n", argv[0], optarg);
7926                                 fprintf(stderr, "Valid types:");
7927
7928                                 for (advice_type = 0;
7929                                      advice_type < ARRAY_SIZE(ladvise_names);
7930                                      advice_type++) {
7931                                         if (ladvise_names[advice_type] == NULL)
7932                                                 continue;
7933                                         fprintf(stderr, " %s",
7934                                                 ladvise_names[advice_type]);
7935                                 }
7936                                 fprintf(stderr, "\n");
7937
7938                                 return CMD_HELP;
7939                         }
7940                         break;
7941                 case 'b':
7942                         flags |= LF_ASYNC;
7943                         break;
7944                 case 'u':
7945                         flags |= LF_UNSET;
7946                         break;
7947                 case 'e':
7948                         size_units = 1;
7949                         rc = llapi_parse_size(optarg, &end,
7950                                               &size_units, 0);
7951                         if (rc) {
7952                                 fprintf(stderr, "%s: bad end offset '%s'\n",
7953                                         argv[0], optarg);
7954                                 return CMD_HELP;
7955                         }
7956                         break;
7957                 case 's':
7958                         size_units = 1;
7959                         rc = llapi_parse_size(optarg, &start,
7960                                               &size_units, 0);
7961                         if (rc) {
7962                                 fprintf(stderr, "%s: bad start offset "
7963                                         "'%s'\n", argv[0], optarg);
7964                                 return CMD_HELP;
7965                         }
7966                         break;
7967                 case 'l':
7968                         size_units = 1;
7969                         rc = llapi_parse_size(optarg, &length,
7970                                               &size_units, 0);
7971                         if (rc) {
7972                                 fprintf(stderr, "%s: bad length '%s'\n",
7973                                         argv[0], optarg);
7974                                 return CMD_HELP;
7975                         }
7976                         break;
7977                 case 'm':
7978                         mode = lfs_get_mode(optarg);
7979                         if (mode < 0) {
7980                                 fprintf(stderr, "%s: bad mode '%s', valid "
7981                                                  "modes are READ or WRITE\n",
7982                                         argv[0], optarg);
7983                                 return CMD_HELP;
7984                         }
7985                         break;
7986                 case '?':
7987                         return CMD_HELP;
7988                 default:
7989                         fprintf(stderr, "%s: option '%s' unrecognized\n",
7990                                 argv[0], argv[optind - 1]);
7991                         return CMD_HELP;
7992                 }
7993         }
7994
7995         if (advice_type == LU_LADVISE_INVALID) {
7996                 fprintf(stderr, "%s: please give an advice type\n", argv[0]);
7997                 fprintf(stderr, "Valid types:");
7998                 for (advice_type = 0; advice_type < ARRAY_SIZE(ladvise_names);
7999                      advice_type++) {
8000                         if (ladvise_names[advice_type] == NULL)
8001                                 continue;
8002                         fprintf(stderr, " %s", ladvise_names[advice_type]);
8003                 }
8004                 fprintf(stderr, "\n");
8005                 return CMD_HELP;
8006         }
8007
8008         if (advice_type == LU_LADVISE_LOCKNOEXPAND) {
8009                 fprintf(stderr, "%s: Lock no expand advice is a per file "
8010                                  "descriptor advice, so when called from lfs, "
8011                                  "it does nothing.\n", argv[0]);
8012                 return CMD_HELP;
8013         }
8014
8015         if (argc <= optind) {
8016                 fprintf(stderr, "%s: please give one or more file names\n",
8017                         argv[0]);
8018                 return CMD_HELP;
8019         }
8020
8021         if (end != LUSTRE_EOF && length != 0 && end != start + length) {
8022                 fprintf(stderr, "%s: conflicting arguments of -l and -e\n",
8023                         argv[0]);
8024                 return CMD_HELP;
8025         }
8026
8027         if (end == LUSTRE_EOF && length != 0)
8028                 end = start + length;
8029
8030         if (end <= start) {
8031                 fprintf(stderr, "%s: range [%llu, %llu] is invalid\n",
8032                         argv[0], start, end);
8033                 return CMD_HELP;
8034         }
8035
8036         if (advice_type != LU_LADVISE_LOCKAHEAD && mode != 0) {
8037                 fprintf(stderr, "%s: mode is only valid with lockahead\n",
8038                         argv[0]);
8039                 return CMD_HELP;
8040         }
8041
8042         if (advice_type == LU_LADVISE_LOCKAHEAD && mode == 0) {
8043                 fprintf(stderr, "%s: mode is required with lockahead\n",
8044                         argv[0]);
8045                 return CMD_HELP;
8046         }
8047
8048         while (optind < argc) {
8049                 int rc2;
8050
8051                 path = argv[optind++];
8052
8053                 fd = open(path, O_RDONLY);
8054                 if (fd < 0) {
8055                         fprintf(stderr, "%s: cannot open file '%s': %s\n",
8056                                 argv[0], path, strerror(errno));
8057                         rc2 = -errno;
8058                         goto next;
8059                 }
8060
8061                 advice.lla_start = start;
8062                 advice.lla_end = end;
8063                 advice.lla_advice = advice_type;
8064                 advice.lla_value1 = 0;
8065                 advice.lla_value2 = 0;
8066                 advice.lla_value3 = 0;
8067                 advice.lla_value4 = 0;
8068                 if (advice_type == LU_LADVISE_LOCKAHEAD) {
8069                         advice.lla_lockahead_mode = mode;
8070                         advice.lla_peradvice_flags = flags;
8071                 }
8072
8073                 rc2 = llapi_ladvise(fd, flags, 1, &advice);
8074                 close(fd);
8075                 if (rc2 < 0) {
8076                         fprintf(stderr, "%s: cannot give advice '%s' to file "
8077                                 "'%s': %s\n", argv[0],
8078                                 ladvise_names[advice_type],
8079                                 path, strerror(errno));
8080
8081                         goto next;
8082                 }
8083
8084 next:
8085                 if (rc == 0 && rc2 < 0)
8086                         rc = rc2;
8087         }
8088         return rc;
8089 }
8090
8091 /** The input string contains a comma delimited list of component ids and
8092  * ranges, for example "1,2-4,7".
8093  */
8094 static int parse_mirror_ids(__u16 *ids, int size, char *arg)
8095 {
8096         bool end_of_loop = false;
8097         char *ptr = NULL;
8098         int nr = 0;
8099         int rc;
8100
8101         if (arg == NULL)
8102                 return -EINVAL;
8103
8104         while (!end_of_loop) {
8105                 int start_index;
8106                 int end_index;
8107                 int i;
8108                 char *endptr = NULL;
8109
8110                 rc = -EINVAL;
8111                 ptr = strchrnul(arg, ',');
8112                 end_of_loop = *ptr == '\0';
8113                 *ptr = '\0';
8114
8115                 start_index = strtol(arg, &endptr, 0);
8116                 if (endptr == arg) /* no data at all */
8117                         break;
8118                 if (*endptr != '-' && *endptr != '\0') /* has invalid data */
8119                         break;
8120                 if (start_index < 0)
8121                         break;
8122
8123                 end_index = start_index;
8124                 if (*endptr == '-') {
8125                         end_index = strtol(endptr + 1, &endptr, 0);
8126                         if (*endptr != '\0')
8127                                 break;
8128                         if (end_index < start_index)
8129                                 break;
8130                 }
8131
8132                 for (i = start_index; i <= end_index && size > 0; i++) {
8133                         int j;
8134
8135                         /* remove duplicate */
8136                         for (j = 0; j < nr; j++) {
8137                                 if (ids[j] == i)
8138                                         break;
8139                         }
8140                         if (j == nr) { /* no duplicate */
8141                                 ids[nr++] = i;
8142                                 --size;
8143                         }
8144                 }
8145
8146                 if (size == 0 && i < end_index)
8147                         break;
8148
8149                 *ptr = ',';
8150                 arg = ++ptr;
8151                 rc = 0;
8152         }
8153         if (!end_of_loop && ptr != NULL)
8154                 *ptr = ',';
8155
8156         return rc < 0 ? rc : nr;
8157 }
8158
8159 /**
8160  * struct verify_mirror_id - Mirror id to be verified.
8161  * @mirror_id:   A specified mirror id.
8162  * @is_valid_id: @mirror_id is valid or not in the mirrored file.
8163  */
8164 struct verify_mirror_id {
8165         __u16 mirror_id;
8166         bool is_valid_id;
8167 };
8168
8169 /**
8170  * compare_mirror_ids() - Compare mirror ids.
8171  * @layout: Mirror component list.
8172  * @cbdata: Callback data in verify_mirror_id structure.
8173  *
8174  * This is a callback function called by llapi_layout_comp_iterate()
8175  * to compare the specified mirror id with the one in the current
8176  * component of @layout. If they are the same, then the specified
8177  * mirror id is valid.
8178  *
8179  * Return: a negative error code on failure or
8180  *         LLAPI_LAYOUT_ITER_CONT: Proceed iteration
8181  *         LLAPI_LAYOUT_ITER_STOP: Stop iteration
8182  */
8183 static inline
8184 int compare_mirror_ids(struct llapi_layout *layout, void *cbdata)
8185 {
8186         struct verify_mirror_id *mirror_id_cbdata =
8187                                  (struct verify_mirror_id *)cbdata;
8188         uint32_t mirror_id;
8189         int rc = 0;
8190
8191         rc = llapi_layout_mirror_id_get(layout, &mirror_id);
8192         if (rc < 0) {
8193                 rc = -errno;
8194                 fprintf(stderr,
8195                         "%s: llapi_layout_mirror_id_get failed: %s.\n",
8196                         progname, strerror(errno));
8197                 return rc;
8198         }
8199
8200         if (mirror_id_cbdata->mirror_id == mirror_id) {
8201                 mirror_id_cbdata->is_valid_id = true;
8202                 return LLAPI_LAYOUT_ITER_STOP;
8203         }
8204
8205         return LLAPI_LAYOUT_ITER_CONT;
8206 }
8207
8208 /**
8209  * verify_mirror_ids() - Verify specified mirror ids.
8210  * @fname:      Mirrored file name.
8211  * @mirror_ids: Specified mirror ids to be verified.
8212  * @ids_nr:     Number of specified mirror ids.
8213  *
8214  * This function verifies that specified @mirror_ids are valid
8215  * in the mirrored file @fname.
8216  *
8217  * Return: 0 on success or a negative error code on failure.
8218  */
8219 static inline
8220 int verify_mirror_ids(const char *fname, __u16 *mirror_ids, int ids_nr)
8221 {
8222         struct llapi_layout *layout = NULL;
8223         struct verify_mirror_id mirror_id_cbdata = { 0 };
8224         struct stat stbuf;
8225         uint32_t flr_state;
8226         int i;
8227         int fd;
8228         int rc = 0;
8229         int rc2 = 0;
8230
8231         if (ids_nr <= 0)
8232                 return -EINVAL;
8233
8234         if (stat(fname, &stbuf) < 0) {
8235                 fprintf(stderr, "%s: cannot stat file '%s': %s.\n",
8236                         progname, fname, strerror(errno));
8237                 rc = -errno;
8238                 goto error;
8239         }
8240
8241         if (!S_ISREG(stbuf.st_mode)) {
8242                 fprintf(stderr, "%s: '%s' is not a regular file.\n",
8243                         progname, fname);
8244                 rc = -EINVAL;
8245                 goto error;
8246         }
8247
8248         fd = open(fname, O_DIRECT | O_RDONLY);
8249         if (fd < 0) {
8250                 fprintf(stderr, "%s: cannot open '%s': %s.\n",
8251                         progname, fname, strerror(errno));
8252                 rc = -errno;
8253                 goto error;
8254         }
8255
8256         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
8257         if (rc < 0) {
8258                 fprintf(stderr, "%s: '%s' llapi_lease_acquire failed: %s.\n",
8259                         progname, fname, strerror(errno));
8260                 goto close_fd;
8261         }
8262
8263         layout = llapi_layout_get_by_fd(fd, 0);
8264         if (layout == NULL) {
8265                 fprintf(stderr, "%s: '%s' llapi_layout_get_by_fd failed: %s.\n",
8266                         progname, fname, strerror(errno));
8267                 rc = -errno;
8268                 llapi_lease_release(fd);
8269                 goto close_fd;
8270         }
8271
8272         rc = llapi_layout_flags_get(layout, &flr_state);
8273         if (rc < 0) {
8274                 fprintf(stderr, "%s: '%s' llapi_layout_flags_get failed: %s.\n",
8275                         progname, fname, strerror(errno));
8276                 rc = -errno;
8277                 goto free_layout;
8278         }
8279
8280         flr_state &= LCM_FL_FLR_MASK;
8281         switch (flr_state) {
8282         case LCM_FL_NONE:
8283                 rc = -EINVAL;
8284                 fprintf(stderr, "%s: '%s' file state error: %s.\n",
8285                         progname, fname, llapi_layout_flags_string(flr_state));
8286                 goto free_layout;
8287         default:
8288                 break;
8289         }
8290
8291         rc2 = 0;
8292         for (i = 0; i < ids_nr; i++) {
8293                 mirror_id_cbdata.mirror_id = mirror_ids[i];
8294                 mirror_id_cbdata.is_valid_id = false;
8295
8296                 rc = llapi_layout_comp_iterate(layout, compare_mirror_ids,
8297                                                &mirror_id_cbdata);
8298                 if (rc < 0) {
8299                         rc = -errno;
8300                         fprintf(stderr,
8301                                 "%s: '%s' failed to verify mirror id: %u.\n",
8302                                 progname, fname, mirror_ids[i]);
8303                         goto free_layout;
8304                 }
8305
8306                 if (!mirror_id_cbdata.is_valid_id) {
8307                         rc2 = -EINVAL;
8308                         fprintf(stderr,
8309                                 "%s: '%s' invalid specified mirror id: %u.\n",
8310                                 progname, fname, mirror_ids[i]);
8311                 }
8312         }
8313         rc = rc2;
8314
8315 free_layout:
8316         llapi_layout_free(layout);
8317         llapi_lease_release(fd);
8318 close_fd:
8319         close(fd);
8320 error:
8321         return rc;
8322 }
8323
8324 static inline
8325 int lfs_mirror_resync_file(const char *fname, struct ll_ioc_lease *ioc,
8326                            __u16 *mirror_ids, int ids_nr)
8327 {
8328         struct llapi_resync_comp comp_array[1024] = { { 0 } };
8329         struct llapi_layout *layout;
8330         struct stat stbuf;
8331         uint32_t flr_state;
8332         uint64_t start;
8333         uint64_t end;
8334         int comp_size = 0;
8335         int idx;
8336         int fd;
8337         int rc;
8338         int rc2;
8339
8340         if (stat(fname, &stbuf) < 0) {
8341                 fprintf(stderr, "%s: cannot stat file '%s': %s.\n",
8342                         progname, fname, strerror(errno));
8343                 rc = -errno;
8344                 goto error;
8345         }
8346         if (!S_ISREG(stbuf.st_mode)) {
8347                 fprintf(stderr, "%s: '%s' is not a regular file.\n",
8348                         progname, fname);
8349                 rc = -EINVAL;
8350                 goto error;
8351         }
8352
8353         fd = open(fname, O_DIRECT | O_RDWR);
8354         if (fd < 0) {
8355                 fprintf(stderr, "%s: cannot open '%s': %s.\n",
8356                         progname, fname, strerror(errno));
8357                 rc = -errno;
8358                 goto error;
8359         }
8360
8361         layout = llapi_layout_get_by_fd(fd, 0);
8362         if (layout == NULL) {
8363                 fprintf(stderr, "%s: '%s' llapi_layout_get_by_fd failed: %s.\n",
8364                         progname, fname, strerror(errno));
8365                 rc = -errno;
8366                 goto close_fd;
8367         }
8368
8369         rc = llapi_layout_flags_get(layout, &flr_state);
8370         if (rc) {
8371                 fprintf(stderr, "%s: '%s' llapi_layout_flags_get failed: %s.\n",
8372                         progname, fname, strerror(errno));
8373                 rc = -errno;
8374                 goto free_layout;
8375         }
8376
8377         flr_state &= LCM_FL_FLR_MASK;
8378         if (flr_state == LCM_FL_NONE) {
8379                 rc = -EINVAL;
8380                 fprintf(stderr, "%s: '%s' is not a FLR file.\n",
8381                         progname, fname);
8382                 goto free_layout;
8383         }
8384
8385         /* get stale component info */
8386         comp_size = llapi_mirror_find_stale(layout, comp_array,
8387                                             ARRAY_SIZE(comp_array),
8388                                             mirror_ids, ids_nr);
8389         if (comp_size <= 0) {
8390                 rc = comp_size;
8391                 goto free_layout;
8392         }
8393
8394         ioc->lil_mode = LL_LEASE_WRLCK;
8395         ioc->lil_flags = LL_LEASE_RESYNC;
8396         rc = llapi_lease_set(fd, ioc);
8397         if (rc < 0) {
8398                 if (rc == -EALREADY)
8399                         rc = 0;
8400                 else
8401                         fprintf(stderr,
8402                             "%s: '%s' llapi_lease_get_ext resync failed: %s.\n",
8403                                 progname, fname, strerror(-rc));
8404                 goto free_layout;
8405         }
8406
8407         /* get the read range [start, end) */
8408         start = comp_array[0].lrc_start;
8409         end = comp_array[0].lrc_end;
8410         for (idx = 1; idx < comp_size; idx++) {
8411                 if (comp_array[idx].lrc_start < start)
8412                         start = comp_array[idx].lrc_start;
8413                 if (end < comp_array[idx].lrc_end)
8414                         end = comp_array[idx].lrc_end;
8415         }
8416
8417         rc = llapi_lease_check(fd);
8418         if (rc != LL_LEASE_WRLCK) {
8419                 fprintf(stderr, "%s: '%s' lost lease lock.\n",
8420                         progname, fname);
8421                 goto free_layout;
8422         }
8423
8424         rc = llapi_mirror_resync_many(fd, layout, comp_array, comp_size,
8425                                       start, end);
8426         if (rc < 0)
8427                 fprintf(stderr, "%s: '%s' llapi_mirror_resync_many: %s.\n",
8428                         progname, fname, strerror(-rc));
8429
8430         /* need to do the lease unlock even resync fails */
8431         ioc->lil_mode = LL_LEASE_UNLCK;
8432         ioc->lil_flags = LL_LEASE_RESYNC_DONE;
8433         ioc->lil_count = 0;
8434         for (idx = 0; idx < comp_size; idx++) {
8435                 if (comp_array[idx].lrc_synced) {
8436                         ioc->lil_ids[ioc->lil_count] = comp_array[idx].lrc_id;
8437                         ioc->lil_count++;
8438                 }
8439         }
8440
8441         rc2 = llapi_lease_set(fd, ioc);
8442         /**
8443          * llapi_lease_set returns lease mode when it request to unlock
8444          * the lease lock.
8445          */
8446         if (rc2 <= 0) {
8447                 /* rc2 == 0 means lost lease lock */
8448                 if (rc2 == 0 && rc == 0)
8449                         rc = -EBUSY;
8450                 fprintf(stderr, "%s: resync file '%s' failed: %s.\n",
8451                         progname, fname,
8452                         rc2 == 0 ? "lost lease lock" : strerror(-rc2));
8453         }
8454
8455 free_layout:
8456         llapi_layout_free(layout);
8457 close_fd:
8458         close(fd);
8459 error:
8460         return rc;
8461 }
8462
8463 static inline int lfs_mirror_resync(int argc, char **argv)
8464 {
8465         struct ll_ioc_lease *ioc = NULL;
8466         __u16 mirror_ids[128] = { 0 };
8467         int ids_nr = 0;
8468         int c;
8469         int rc = 0;
8470
8471         struct option long_opts[] = {
8472         { .val = 'o',   .name = "only",         .has_arg = required_argument },
8473         { .name = NULL } };
8474
8475         while ((c = getopt_long(argc, argv, "o:", long_opts, NULL)) >= 0) {
8476                 switch (c) {
8477                 case 'o':
8478                         rc = parse_mirror_ids(mirror_ids,
8479                                         sizeof(mirror_ids) / sizeof(__u16),
8480                                         optarg);
8481                         if (rc < 0) {
8482                                 fprintf(stderr,
8483                                         "%s: bad mirror ids '%s'.\n",
8484                                         argv[0], optarg);
8485                                 goto error;
8486                         }
8487                         ids_nr = rc;
8488                         break;
8489                 default:
8490                         fprintf(stderr, "%s: options '%s' unrecognized.\n",
8491                                 argv[0], argv[optind - 1]);
8492                         rc = -EINVAL;
8493                         goto error;
8494                 }
8495         }
8496
8497         if (argc == optind) {
8498                 fprintf(stderr, "%s: no file name given.\n", argv[0]);
8499                 rc = CMD_HELP;
8500                 goto error;
8501         }
8502
8503         if (ids_nr > 0 && argc > optind + 1) {
8504                 fprintf(stderr,
8505                     "%s: option '--only' cannot be used upon multiple files.\n",
8506                         argv[0]);
8507                 rc = CMD_HELP;
8508                 goto error;
8509
8510         }
8511
8512         if (ids_nr > 0) {
8513                 rc = verify_mirror_ids(argv[optind], mirror_ids, ids_nr);
8514                 if (rc < 0)
8515                         goto error;
8516         }
8517
8518         /* set the lease on the file */
8519         ioc = calloc(sizeof(*ioc) + sizeof(__u32) * 4096, 1);
8520         if (ioc == NULL) {
8521                 fprintf(stderr, "%s: cannot alloc id array for ioc: %s.\n",
8522                         argv[0], strerror(errno));
8523                 rc = -errno;
8524                 goto error;
8525         }
8526
8527         for (; optind < argc; optind++) {
8528                 rc = lfs_mirror_resync_file(argv[optind], ioc,
8529                                             mirror_ids, ids_nr);
8530                 /* ignore previous file's error, continue with next file */
8531
8532                 /* reset ioc */
8533                 memset(ioc, 0, sizeof(*ioc) + sizeof(__u32) * 4096);
8534         }
8535
8536         free(ioc);
8537 error:
8538         return rc;
8539 }
8540
8541 static inline int verify_mirror_id_by_fd(int fd, __u16 mirror_id)
8542 {
8543         struct llapi_layout *layout;
8544         int rc;
8545
8546         layout = llapi_layout_get_by_fd(fd, 0);
8547         if (layout == NULL) {
8548                 fprintf(stderr, "could not get layout.\n");
8549                 return  -EINVAL;
8550         }
8551
8552         rc = llapi_layout_comp_iterate(layout, find_mirror_id, &mirror_id);
8553         if (rc < 0) {
8554                 fprintf(stderr, "failed to iterate layout\n");
8555                 llapi_layout_free(layout);
8556
8557                 return rc;
8558         } else if (rc == LLAPI_LAYOUT_ITER_CONT) {
8559                 fprintf(stderr, "does not find mirror with ID %u\n", mirror_id);
8560                 llapi_layout_free(layout);
8561
8562                 return -EINVAL;
8563         }
8564         llapi_layout_free(layout);
8565
8566         return 0;
8567 }
8568
8569 /**
8570  * Check whether two files are the same file
8571  * \retval      0  same file
8572  * \retval      1  not the same file
8573  * \retval      <0 error code
8574  */
8575 static inline int check_same_file(const char *f1, const char *f2)
8576 {
8577         struct stat stbuf1;
8578         struct stat stbuf2;
8579
8580         if (stat(f1, &stbuf1) < 0) {
8581                 fprintf(stderr, "%s: cannot stat file '%s': %s\n",
8582                         progname, f1, strerror(errno));
8583                 return -errno;
8584         }
8585
8586         if (stat(f2, &stbuf2) < 0) {
8587                 fprintf(stderr, "%s: cannot stat file '%s': %s\n",
8588                         progname, f2, strerror(errno));
8589                 return -errno;
8590         }
8591
8592         if (stbuf1.st_rdev == stbuf2.st_rdev &&
8593             stbuf1.st_ino == stbuf2.st_ino)
8594                 return 0;
8595
8596         return 1;
8597 }
8598
8599 static inline int lfs_mirror_read(int argc, char **argv)
8600 {
8601         int rc = CMD_HELP;
8602         __u16 mirror_id = 0;
8603         const char *outfile = NULL;
8604         char *fname;
8605         int fd = 0;
8606         int outfd;
8607         int c;
8608         void *buf;
8609         const size_t buflen = 4 << 20;
8610         off_t pos;
8611         struct option long_opts[] = {
8612         { .val = 'N',   .name = "mirror-id",    .has_arg = required_argument },
8613         { .val = 'o',   .name = "outfile",      .has_arg = required_argument },
8614         { .name = NULL } };
8615
8616         while ((c = getopt_long(argc, argv, "N:o:", long_opts, NULL)) >= 0) {
8617                 char *end;
8618
8619                 switch (c) {
8620                 case 'N':
8621                         mirror_id = strtoul(optarg, &end, 0);
8622                         if (*end != '\0' || mirror_id == 0) {
8623                                 fprintf(stderr,
8624                                         "%s %s: invalid mirror ID '%s'\n",
8625                                         progname, argv[0], optarg);
8626                                 return rc;
8627                         }
8628                         break;
8629                 case 'o':
8630                         outfile = optarg;
8631                         break;
8632                 default:
8633                         fprintf(stderr, "%s: option '%s' unrecognized.\n",
8634                                 progname, argv[optind - 1]);
8635                         return -EINVAL;
8636                 }
8637         }
8638
8639         if (argc == optind) {
8640                 fprintf(stderr, "%s %s: no mirrored file provided\n",
8641                         progname, argv[0]);
8642                 return rc;
8643         } else if (argc > optind + 1) {
8644                 fprintf(stderr, "%s %s: too many files\n", progname, argv[0]);
8645                 return rc;
8646         }
8647
8648         if (mirror_id == 0) {
8649                 fprintf(stderr, "%s %s: no valid mirror ID is provided\n",
8650                         progname, argv[0]);
8651                 return rc;
8652         }
8653
8654         /* open mirror file */
8655         fname = argv[optind];
8656
8657         if (outfile) {
8658                 rc = check_same_file(fname, outfile);
8659                 if (rc == 0) {
8660                         fprintf(stderr,
8661                         "%s %s: output file cannot be the mirrored file\n",
8662                                 progname, argv[0]);
8663                         return -EINVAL;
8664                 }
8665                 if (rc < 0)
8666                         return rc;
8667         }
8668
8669         fd = open(fname, O_DIRECT | O_RDONLY);
8670         if (fd < 0) {
8671                 fprintf(stderr, "%s %s: cannot open '%s': %s\n",
8672                         progname, argv[0], fname, strerror(errno));
8673                 return rc;
8674         }
8675
8676         /* verify mirror id */
8677         rc = verify_mirror_id_by_fd(fd, mirror_id);
8678         if (rc) {
8679                 fprintf(stderr,
8680                         "%s %s: cannot find mirror with ID %u in '%s'\n",
8681                         progname, argv[0], mirror_id, fname);
8682                 goto close_fd;
8683         }
8684
8685         /* open output file */
8686         if (outfile) {
8687                 outfd = open(outfile, O_EXCL | O_WRONLY | O_CREAT, 0644);
8688                 if (outfd < 0) {
8689                         fprintf(stderr, "%s %s: cannot create file '%s': %s\n",
8690                                 progname, argv[0], outfile, strerror(errno));
8691                         rc = -errno;
8692                         goto close_fd;
8693                 }
8694         } else {
8695                 outfd = STDOUT_FILENO;
8696         }
8697
8698         /* allocate buffer */
8699         rc = posix_memalign(&buf, sysconf(_SC_PAGESIZE), buflen);
8700         if (rc) {
8701                 fprintf(stderr, "%s %s: posix_memalign returns %d\n",
8702                                 progname, argv[0], rc);
8703                 goto close_outfd;
8704         }
8705
8706         pos = 0;
8707         while (1) {
8708                 ssize_t bytes_read;
8709                 ssize_t written = 0;
8710
8711                 bytes_read = llapi_mirror_read(fd, mirror_id, buf, buflen, pos);
8712                 if (bytes_read < 0) {
8713                         rc = bytes_read;
8714                         fprintf(stderr,
8715                                 "%s %s: fail to read data from mirror %u: %s\n",
8716                                 progname, argv[0], mirror_id, strerror(-rc));
8717                         goto free_buf;
8718                 }
8719
8720                 /* EOF reached */
8721                 if (bytes_read == 0)
8722                         break;
8723
8724                 while (written < bytes_read) {
8725                         ssize_t written2;
8726
8727                         written2 = write(outfd, buf + written,
8728                                          bytes_read - written);
8729                         if (written2 < 0) {
8730                                 fprintf(stderr,
8731                                         "%s %s: fail to write %s: %s\n",
8732                                         progname, argv[0], outfile ? : "STDOUT",
8733                                         strerror(errno));
8734                                 rc = -errno;
8735                                 goto free_buf;
8736                         }
8737                         written += written2;
8738                 }
8739
8740                 if (written != bytes_read) {
8741                         fprintf(stderr,
8742                 "%s %s: written %ld bytes does not match with %ld read.\n",
8743                                 progname, argv[0], written, bytes_read);
8744                         rc = -EIO;
8745                         goto free_buf;
8746                 }
8747
8748                 pos += bytes_read;
8749         }
8750
8751         fsync(outfd);
8752         rc = 0;
8753
8754 free_buf:
8755         free(buf);
8756 close_outfd:
8757         if (outfile)
8758                 close(outfd);
8759 close_fd:
8760         close(fd);
8761
8762         return rc;
8763 }
8764
8765 static inline int lfs_mirror_write(int argc, char **argv)
8766 {
8767         int rc = CMD_HELP;
8768         __u16 mirror_id = 0;
8769         const char *inputfile = NULL;
8770         char *fname;
8771         int fd = 0;
8772         int inputfd;
8773         int c;
8774         void *buf;
8775         const size_t buflen = 4 << 20;
8776         off_t pos;
8777         size_t page_size = sysconf(_SC_PAGESIZE);
8778         struct ll_ioc_lease_id ioc;
8779
8780         struct option long_opts[] = {
8781         { .val = 'N',   .name = "mirror-id",    .has_arg = required_argument },
8782         { .val = 'i',   .name = "inputfile",    .has_arg = required_argument },
8783         { .name = NULL } };
8784
8785         while ((c = getopt_long(argc, argv, "N:i:", long_opts, NULL)) >= 0) {
8786                 char *end;
8787
8788                 switch (c) {
8789                 case 'N':
8790                         mirror_id = strtoul(optarg, &end, 0);
8791                         if (*end != '\0' || mirror_id == 0) {
8792                                 fprintf(stderr,
8793                                         "%s %s: invalid mirror ID '%s'\n",
8794                                         progname, argv[0], optarg);
8795                                 return rc;
8796                         }
8797                         break;
8798                 case 'i':
8799                         inputfile = optarg;
8800                         break;
8801                 default:
8802                         fprintf(stderr, "%s: option '%s' unrecognized\n",
8803                                 progname, argv[optind - 1]);
8804                         return -EINVAL;
8805                 }
8806         }
8807
8808         if (argc == optind) {
8809                 fprintf(stderr, "%s %s: no mirrored file provided\n",
8810                         progname, argv[0]);
8811                 return rc;
8812         } else if (argc > optind + 1) {
8813                 fprintf(stderr, "%s %s: too many files\n", progname, argv[0]);
8814                 return rc;
8815         }
8816
8817         if (mirror_id == 0) {
8818                 fprintf(stderr, "%s %s: no valid mirror ID is provided\n",
8819                         progname, argv[0]);
8820                 return rc;
8821         }
8822
8823         /* open mirror file */
8824         fname = argv[optind];
8825
8826         if (inputfile) {
8827                 rc = check_same_file(fname, inputfile);
8828                 if (rc == 0) {
8829                         fprintf(stderr,
8830                         "%s %s: input file cannot be the mirrored file\n",
8831                                 progname, argv[0]);
8832                         return -EINVAL;
8833                 }
8834                 if (rc < 0)
8835                         return rc;
8836         }
8837
8838         fd = open(fname, O_DIRECT | O_WRONLY);
8839         if (fd < 0) {
8840                 fprintf(stderr, "%s %s: cannot open '%s': %s\n",
8841                         progname, argv[0], fname, strerror(errno));
8842                 return rc;
8843         }
8844
8845         /* verify mirror id */
8846         rc = verify_mirror_id_by_fd(fd, mirror_id);
8847         if (rc) {
8848                 fprintf(stderr,
8849                         "%s %s: cannot find mirror with ID %u in '%s'\n",
8850                         progname, argv[0], mirror_id, fname);
8851                 goto close_fd;
8852         }
8853
8854         /* open input file */
8855         if (inputfile) {
8856                 inputfd = open(inputfile, O_RDONLY, 0644);
8857                 if (inputfd < 0) {
8858                         fprintf(stderr, "%s %s: cannot open file '%s': %s\n",
8859                                 progname, argv[0], inputfile, strerror(errno));
8860                         rc = -errno;
8861                         goto close_fd;
8862                 }
8863         } else {
8864                 inputfd = STDIN_FILENO;
8865         }
8866
8867         /* allocate buffer */
8868         rc = posix_memalign(&buf, page_size, buflen);
8869         if (rc) {
8870                 fprintf(stderr, "%s %s: posix_memalign returns %d\n",
8871                         progname, argv[0], rc);
8872                 goto close_inputfd;
8873         }
8874
8875         /* prepare target mirror components instantiation */
8876         ioc.lil_mode = LL_LEASE_WRLCK;
8877         ioc.lil_flags = LL_LEASE_RESYNC;
8878         ioc.lil_mirror_id = mirror_id;
8879         rc = llapi_lease_set(fd, (struct ll_ioc_lease *)&ioc);
8880         if (rc < 0) {
8881                 fprintf(stderr,
8882                         "%s %s: '%s' llapi_lease_get_ext failed: %s\n",
8883                         progname, argv[0], fname, strerror(errno));
8884                 goto free_buf;
8885         }
8886
8887         pos = 0;
8888         while (1) {
8889                 ssize_t bytes_read;
8890                 ssize_t written;
8891                 size_t to_write;
8892
8893                 rc = llapi_lease_check(fd);
8894                 if (rc != LL_LEASE_WRLCK) {
8895                         fprintf(stderr, "%s %s: '%s' lost lease lock\n",
8896                                 progname, argv[0], fname);
8897                         goto free_buf;
8898                 }
8899
8900                 bytes_read = read(inputfd, buf, buflen);
8901                 if (bytes_read < 0) {
8902                         rc = bytes_read;
8903                         fprintf(stderr,
8904                                 "%s %s: fail to read data from '%s': %s\n",
8905                                 progname, argv[0], inputfile ? : "STDIN",
8906                                 strerror(errno));
8907                         rc = -errno;
8908                         goto free_buf;
8909                 }
8910
8911                 /* EOF reached */
8912                 if (bytes_read == 0)
8913                         break;
8914
8915                 /* round up to page align to make direct IO happy. */
8916                 to_write = (bytes_read + page_size - 1) & ~(page_size - 1);
8917
8918                 written = llapi_mirror_write(fd, mirror_id, buf, to_write,
8919                                              pos);
8920                 if (written < 0) {
8921                         rc = written;
8922                         fprintf(stderr,
8923                               "%s %s: fail to write to mirror %u: %s\n",
8924                                 progname, argv[0], mirror_id,
8925                                 strerror(-rc));
8926                         goto free_buf;
8927                 }
8928
8929                 pos += bytes_read;
8930         }
8931
8932         if (pos & (page_size - 1)) {
8933                 rc = llapi_mirror_truncate(fd, mirror_id, pos);
8934                 if (rc < 0)
8935                         goto free_buf;
8936         }
8937
8938         ioc.lil_mode = LL_LEASE_UNLCK;
8939         ioc.lil_flags = LL_LEASE_RESYNC_DONE;
8940         ioc.lil_count = 0;
8941         rc = llapi_lease_set(fd, (struct ll_ioc_lease *)&ioc);
8942         if (rc <= 0) {
8943                 if (rc == 0)
8944                         rc = -EBUSY;
8945                 fprintf(stderr,
8946                         "%s %s: release lease lock of '%s' failed: %s\n",
8947                         progname, argv[0], fname, strerror(errno));
8948                 goto free_buf;
8949         }
8950
8951         rc = 0;
8952
8953 free_buf:
8954         free(buf);
8955 close_inputfd:
8956         if (inputfile)
8957                 close(inputfd);
8958 close_fd:
8959         close(fd);
8960
8961         return rc;
8962 }
8963
8964 static inline int get_other_mirror_ids(int fd, __u16 *ids, __u16 exclude_id)
8965 {
8966         struct llapi_layout *layout;
8967         struct collect_ids_data cid = { .cid_ids = ids,
8968                                         .cid_count = 0,
8969                                         .cid_exclude = exclude_id, };
8970         int rc;
8971
8972         layout = llapi_layout_get_by_fd(fd, 0);
8973         if (layout == NULL) {
8974                 fprintf(stderr, "could not get layout\n");
8975                 return -EINVAL;
8976         }
8977
8978         rc = llapi_layout_comp_iterate(layout, collect_mirror_id, &cid);
8979         if (rc < 0) {
8980                 fprintf(stderr, "failed to iterate layout\n");
8981                 llapi_layout_free(layout);
8982
8983                 return rc;
8984         }
8985         llapi_layout_free(layout);
8986
8987         return cid.cid_count;
8988 }
8989
8990 static inline int lfs_mirror_copy(int argc, char **argv)
8991 {
8992         int rc = CMD_HELP;
8993         __u16 read_mirror_id = 0;
8994         __u16 ids[128] = { 0 };
8995         int count = 0;
8996         struct llapi_layout *layout = NULL;
8997         struct llapi_resync_comp comp_array[1024] = { { 0 } };
8998         int comp_size = 0;
8999         char *fname;
9000         int fd = 0;
9001         int c;
9002         int i;
9003         ssize_t copied;
9004         struct ll_ioc_lease *ioc = NULL;
9005         struct ll_ioc_lease_id *resync_ioc;
9006
9007         struct option long_opts[] = {
9008         { .val = 'i',   .name = "read-mirror",  .has_arg = required_argument },
9009         { .val = 'o',   .name = "write-mirror", .has_arg = required_argument },
9010         { .name = NULL } };
9011
9012         while ((c = getopt_long(argc, argv, "i:o:", long_opts, NULL)) >= 0) {
9013                 char *end;
9014
9015                 switch (c) {
9016                 case 'i':
9017                         read_mirror_id = strtoul(optarg, &end, 0);
9018                         if (*end != '\0' || read_mirror_id == 0) {
9019                                 fprintf(stderr,
9020                                         "%s %s: invalid read mirror ID '%s'\n",
9021                                         progname, argv[0], optarg);
9022                                 return rc;
9023                         }
9024                         break;
9025                 case 'o':
9026                         if (!strcmp(optarg, "-1")) {
9027                                 /* specify all other mirrors */
9028                                 ids[0] = (__u16)-1;
9029                                 count = 1;
9030                         } else {
9031                                 count = parse_mirror_ids((__u16 *)ids,
9032                                                          ARRAY_SIZE(ids),
9033                                                          optarg);
9034                                 if (count < 0)
9035                                         return rc;
9036                         }
9037                         break;
9038                 default:
9039                         fprintf(stderr, "%s: option '%s' unrecognized\n",
9040                                 progname, argv[optind - 1]);
9041                         return -EINVAL;
9042                 }
9043         }
9044
9045         if (argc == optind) {
9046                 fprintf(stderr, "%s %s: no mirrored file provided\n",
9047                         progname, argv[0]);
9048                 return rc;
9049         } else if (argc > optind + 1) {
9050                 fprintf(stderr, "%s %s: too many files\n", progname, argv[0]);
9051                 return rc;
9052         }
9053
9054         if (read_mirror_id == 0) {
9055                 fprintf(stderr,
9056                         "%s %s: no valid read mirror ID %d is provided\n",
9057                         progname, argv[0], read_mirror_id);
9058                 return rc;
9059         }
9060
9061         if (count == 0) {
9062                 fprintf(stderr,
9063                         "%s %s: no write mirror ID is provided\n",
9064                         progname, argv[0]);
9065                 return rc;
9066         }
9067
9068         for (i = 0; i < count; i++) {
9069                 if (read_mirror_id == ids[i]) {
9070                         fprintf(stderr,
9071                         "%s %s: read and write mirror ID cannot be the same\n",
9072                                 progname, argv[0]);
9073                         return rc;
9074                 }
9075         }
9076
9077         /* open mirror file */
9078         fname = argv[optind];
9079
9080         fd = open(fname, O_DIRECT | O_RDWR);
9081         if (fd < 0) {
9082                 fprintf(stderr, "%s %s: cannot open '%s': %s\n",
9083                         progname, argv[0], fname, strerror(errno));
9084                 return rc;
9085         }
9086
9087         /* write to all other mirrors */
9088         if (ids[0] == (__u16)-1) {
9089                 count = get_other_mirror_ids(fd, ids, read_mirror_id);
9090                 if (count <= 0) {
9091                         rc = count;
9092                         fprintf(stderr,
9093                         "%s %s: failed to get other mirror ids in '%s': %d\n",
9094                                 progname, argv[0], fname, rc);
9095                         goto close_fd;
9096                 }
9097         }
9098
9099         /* verify mirror id */
9100         rc = verify_mirror_id_by_fd(fd, read_mirror_id);
9101         if (rc) {
9102                 fprintf(stderr,
9103                         "%s %s: cannot find mirror with ID %u in '%s'\n",
9104                         progname, argv[0], read_mirror_id, fname);
9105                 goto close_fd;
9106         }
9107
9108         for (i = 0; i < count; i++) {
9109                 rc = verify_mirror_id_by_fd(fd, ids[i]);
9110                 if (rc) {
9111                         fprintf(stderr,
9112                         "%s %s: cannot find mirror with ID %u in '%s'\n",
9113                                 progname, argv[0], ids[i], fname);
9114                         goto close_fd;
9115                 }
9116         }
9117
9118         ioc = calloc(sizeof(*ioc) + sizeof(__u32) * 4096, 1);
9119         if (ioc == NULL) {
9120                 fprintf(stderr,
9121                         "%s %s: cannot alloc comp id array for ioc: %s\n",
9122                         progname, argv[0], strerror(errno));
9123                 rc = -errno;
9124                 goto close_fd;
9125         }
9126
9127         /* get stale component info */
9128         layout = llapi_layout_get_by_fd(fd, 0);
9129         if (layout == NULL) {
9130                 fprintf(stderr, "%s %s: failed to get layout of '%s': %s\n",
9131                         progname, argv[0], fname, strerror(errno));
9132                 rc = -errno;
9133                 goto free_ioc;
9134         }
9135         comp_size = llapi_mirror_find_stale(layout, comp_array,
9136                                             ARRAY_SIZE(comp_array),
9137                                             ids, count);
9138         llapi_layout_free(layout);
9139         if (comp_size < 0) {
9140                 rc = comp_size;
9141                 goto free_ioc;
9142         }
9143
9144         /* prepare target mirror components instantiation */
9145         resync_ioc = (struct ll_ioc_lease_id *)ioc;
9146         resync_ioc->lil_mode = LL_LEASE_WRLCK;
9147         resync_ioc->lil_flags = LL_LEASE_RESYNC;
9148         if (count == 1)
9149                 resync_ioc->lil_mirror_id = ids[0];
9150         else
9151                 resync_ioc->lil_mirror_id = read_mirror_id | MIRROR_ID_NEG;
9152         rc = llapi_lease_set(fd, ioc);
9153         if (rc < 0) {
9154                 fprintf(stderr,
9155                         "%s %s: '%s' llapi_lease_get_ext failed: %s\n",
9156                         progname, argv[0], fname, strerror(errno));
9157                 goto free_ioc;
9158         }
9159
9160         copied = llapi_mirror_copy_many(fd, read_mirror_id, ids, count);
9161         if (copied < 0) {
9162                 rc = copied;
9163                 fprintf(stderr, "%s %s: copy error: %d\n",
9164                         progname, argv[0], rc);
9165                 goto free_ioc;
9166         }
9167
9168         fprintf(stdout, "mirror copied successfully: ");
9169         for (i = 0; i < copied; i++)
9170                 fprintf(stdout, "%d ", ids[i]);
9171         fprintf(stdout, "\n");
9172
9173         ioc->lil_mode = LL_LEASE_UNLCK;
9174         ioc->lil_flags = LL_LEASE_RESYNC_DONE;
9175         ioc->lil_count = 0;
9176         for (i = 0; i < comp_size; i++) {
9177                 int j;
9178
9179                 for (j = 0; j < copied; j++) {
9180                         if (comp_array[i].lrc_mirror_id != ids[j])
9181                                 continue;
9182
9183                         ioc->lil_ids[ioc->lil_count] = comp_array[i].lrc_id;
9184                         ioc->lil_count++;
9185                 }
9186         }
9187         rc = llapi_lease_set(fd, ioc);
9188         if (rc <= 0) {
9189                 if (rc == 0)
9190                         rc = -EBUSY;
9191                 fprintf(stderr,
9192                         "%s %s: release lease lock of '%s' failed: %s\n",
9193                         progname, argv[0], fname, strerror(errno));
9194                 goto free_ioc;
9195         }
9196
9197         rc = 0;
9198
9199 free_ioc:
9200         free(ioc);
9201 close_fd:
9202         close(fd);
9203
9204         return rc;
9205 }
9206 /**
9207  * struct verify_chunk - Mirror chunk to be verified.
9208  * @chunk:        [start, end) of the chunk.
9209  * @mirror_count: Number of mirror ids in @mirror_id array.
9210  * @mirror_id:    Array of valid mirror ids that cover the chunk.
9211  */
9212 struct verify_chunk {
9213         struct lu_extent chunk;
9214         unsigned int mirror_count;
9215         __u16 mirror_id[LUSTRE_MIRROR_COUNT_MAX];
9216 };
9217
9218 /**
9219  * print_chunks() - Print chunk information.
9220  * @fname:       Mirrored file name.
9221  * @chunks:      Array of chunks.
9222  * @chunk_count: Number of chunks in @chunks array.
9223  *
9224  * This function prints [start, end) of each chunk in @chunks
9225  * for mirrored file @fname, and also prints the valid mirror ids
9226  * that cover the chunk.
9227  *
9228  * Return: void.
9229  */
9230 static inline
9231 void print_chunks(const char *fname, struct verify_chunk *chunks,
9232                   int chunk_count)
9233 {
9234         int i;
9235         int j;
9236
9237         fprintf(stdout, "Chunks to be verified in %s:\n", fname);
9238         for (i = 0; i < chunk_count; i++) {
9239                 fprintf(stdout, DEXT, PEXT(&chunks[i].chunk));
9240
9241                 if (chunks[i].mirror_count == 0)
9242                         fprintf(stdout, "\t[");
9243                 else {
9244                         fprintf(stdout, "\t[%u", chunks[i].mirror_id[0]);
9245                         for (j = 1; j < chunks[i].mirror_count; j++)
9246                                 fprintf(stdout, ", %u", chunks[i].mirror_id[j]);
9247                 }
9248                 fprintf(stdout, "]\t%u\n", chunks[i].mirror_count);
9249         }
9250         fprintf(stdout, "\n");
9251 }
9252
9253 /**
9254  * print_checksums() - Print CRC-32 checksum values.
9255  * @chunk: A chunk and its corresponding valid mirror ids.
9256  * @crc:   CRC-32 checksum values on the chunk for each valid mirror.
9257  *
9258  * This function prints CRC-32 checksum values on @chunk for
9259  * each valid mirror that covers it.
9260  *
9261  * Return: void.
9262  */
9263 static inline
9264 void print_checksums(struct verify_chunk *chunk, unsigned long *crc)
9265 {
9266         int i;
9267
9268         fprintf(stdout,
9269                 "CRC-32 checksum value for chunk "DEXT":\n",
9270                 PEXT(&chunk->chunk));
9271         for (i = 0; i < chunk->mirror_count; i++)
9272                 fprintf(stdout, "Mirror %u:\t%#lx\n",
9273                         chunk->mirror_id[i], crc[i]);
9274         fprintf(stdout, "\n");
9275 }
9276
9277 /**
9278  * filter_mirror_id() - Filter specified mirror ids.
9279  * @chunks:      Array of chunks.
9280  * @chunk_count: Number of chunks in @chunks array.
9281  * @mirror_ids:  Specified mirror ids to be verified.
9282  * @ids_nr:      Number of specified mirror ids.
9283  *
9284  * This function scans valid mirror ids that cover each chunk in @chunks
9285  * and filters specified mirror ids.
9286  *
9287  * Return: void.
9288  */
9289 static inline
9290 void filter_mirror_id(struct verify_chunk *chunks, int chunk_count,
9291                       __u16 *mirror_ids, int ids_nr)
9292 {
9293         int i;
9294         int j;
9295         int k;
9296         __u16 valid_id[LUSTRE_MIRROR_COUNT_MAX] = { 0 };
9297         unsigned int valid_count = 0;
9298
9299         for (i = 0; i < chunk_count; i++) {
9300                 if (chunks[i].mirror_count == 0)
9301                         continue;
9302
9303                 valid_count = 0;
9304                 for (j = 0; j < ids_nr; j++) {
9305                         for (k = 0; k < chunks[i].mirror_count; k++) {
9306                                 if (chunks[i].mirror_id[k] == mirror_ids[j]) {
9307                                         valid_id[valid_count] = mirror_ids[j];
9308                                         valid_count++;
9309                                         break;
9310                                 }
9311                         }
9312                 }
9313
9314                 memcpy(chunks[i].mirror_id, valid_id,
9315                        sizeof(__u16) * valid_count);
9316                 chunks[i].mirror_count = valid_count;
9317         }
9318 }
9319
9320 /**
9321  * lfs_mirror_prepare_chunk() - Find mirror chunks to be verified.
9322  * @layout:      Mirror component list.
9323  * @chunks:      Array of chunks.
9324  * @chunks_size: Array size of @chunks.
9325  *
9326  * This function scans the components in @layout from offset 0 to LUSTRE_EOF
9327  * to find out chunk segments and store them in @chunks array.
9328  *
9329  * The @mirror_id array in each element of @chunks will store the valid
9330  * mirror ids that cover the chunk. If a mirror component covering the
9331  * chunk has LCME_FL_STALE or LCME_FL_OFFLINE flag, then the mirror id
9332  * will not be stored into the @mirror_id array, and the chunk for that
9333  * mirror will not be verified.
9334  *
9335  * The @mirror_count in each element of @chunks will store the number of
9336  * mirror ids in @mirror_id array. If @mirror_count is 0, it indicates the
9337  * chunk is invalid in all of the mirrors. And if @mirror_count is 1, it
9338  * indicates the chunk is valid in only one mirror. In both cases, the
9339  * chunk will not be verified.
9340  *
9341  * Here is an example:
9342  *
9343  *  0      1M     2M     3M     4M           EOF
9344  *  +------+-------------+--------------------+
9345  *  |      |             |      S             |       mirror1
9346  *  +------+------+------+------+-------------+
9347  *  |             |   S  |   S  |             |       mirror2
9348  *  +-------------+------+------+-------------+
9349  *
9350  * prepared @chunks array will contain 5 elements:
9351  * (([0, 1M), [1, 2], 2),
9352  *  ([1M, 2M), [1, 2], 2),
9353  *  ([2M, 3M), [1], 1),
9354  *  ([3M, 4M], [], 0),
9355  *  ([4M, EOF), [2], 1))
9356  *
9357  * Return: the actual array size of @chunks on success
9358  *         or a negative error code on failure.
9359  */
9360 static inline
9361 int lfs_mirror_prepare_chunk(struct llapi_layout *layout,
9362                              struct verify_chunk *chunks,
9363                              size_t chunks_size)
9364 {
9365         uint64_t start;
9366         uint64_t end;
9367         uint32_t mirror_id;
9368         uint32_t flags;
9369         int idx = 0;
9370         int i = 0;
9371         int rc = 0;
9372
9373         memset(chunks, 0, sizeof(*chunks) * chunks_size);
9374
9375         while (1) {
9376                 rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_FIRST);
9377                 if (rc < 0) {
9378                         fprintf(stderr,
9379                                 "%s: move to the first layout component: %s.\n",
9380                                 progname, strerror(errno));
9381                         goto error;
9382                 }
9383
9384                 i = 0;
9385                 rc = 0;
9386                 chunks[idx].chunk.e_end = LUSTRE_EOF;
9387                 while (rc == 0) {
9388                         rc = llapi_layout_comp_extent_get(layout, &start, &end);
9389                         if (rc < 0) {
9390                                 fprintf(stderr,
9391                                         "%s: llapi_layout_comp_extent_get failed: %s.\n",
9392                                         progname, strerror(errno));
9393                                 goto error;
9394                         }
9395
9396                         if (start > chunks[idx].chunk.e_start ||
9397                             end <= chunks[idx].chunk.e_start)
9398                                 goto next;
9399
9400                         if (end < chunks[idx].chunk.e_end)
9401                                 chunks[idx].chunk.e_end = end;
9402
9403                         rc = llapi_layout_comp_flags_get(layout, &flags);
9404                         if (rc < 0) {
9405                                 fprintf(stderr,
9406                                         "%s: llapi_layout_comp_flags_get failed: %s.\n",
9407                                         progname, strerror(errno));
9408                                 goto error;
9409                         }
9410
9411                         if (flags & LCME_FL_STALE || flags & LCME_FL_OFFLINE)
9412                                 goto next;
9413
9414                         rc = llapi_layout_mirror_id_get(layout, &mirror_id);
9415                         if (rc < 0) {
9416                                 fprintf(stderr,
9417                                         "%s: llapi_layout_mirror_id_get failed: %s.\n",
9418                                         progname, strerror(errno));
9419                                 goto error;
9420                         }
9421
9422                         chunks[idx].mirror_id[i] = mirror_id;
9423                         i++;
9424                         if (i >= ARRAY_SIZE(chunks[idx].mirror_id)) {
9425                                 fprintf(stderr,
9426                                         "%s: mirror_id array is too small.\n",
9427                                         progname);
9428                                 rc = -EINVAL;
9429                                 goto error;
9430                         }
9431
9432                 next:
9433                         rc = llapi_layout_comp_use(layout,
9434                                                    LLAPI_LAYOUT_COMP_USE_NEXT);
9435                         if (rc < 0) {
9436                                 fprintf(stderr,
9437                                         "%s: move to the next layout component: %s.\n",
9438                                         progname, strerror(errno));
9439                                 goto error;
9440                         }
9441                 } /* loop through all components */
9442
9443                 chunks[idx].mirror_count = i;
9444
9445                 if (chunks[idx].chunk.e_end == LUSTRE_EOF)
9446                         break;
9447
9448                 idx++;
9449                 if (idx >= chunks_size) {
9450                         fprintf(stderr, "%s: chunks array is too small.\n",
9451                                 progname);
9452                         rc = -EINVAL;
9453                         goto error;
9454                 }
9455
9456                 chunks[idx].chunk.e_start = chunks[idx - 1].chunk.e_end;
9457         }
9458
9459 error:
9460         return rc < 0 ? rc : idx + 1;
9461 }
9462
9463 /**
9464  * lfs_mirror_verify_chunk() - Verify a chunk.
9465  * @fd:        File descriptor of the mirrored file.
9466  * @file_size: Size of the mirrored file.
9467  * @chunk:     A chunk and its corresponding valid mirror ids.
9468  * @verbose:   Verbose mode.
9469  *
9470  * This function verifies a @chunk contains exactly the same data
9471  * ammong the mirrors that cover it.
9472  *
9473  * If @verbose is specified, then the function will print where the
9474  * differences are if the data do not match. Otherwise, it will
9475  * just return an error in that case.
9476  *
9477  * Return: 0 on success or a negative error code on failure.
9478  */
9479 static inline
9480 int lfs_mirror_verify_chunk(int fd, size_t file_size,
9481                             struct verify_chunk *chunk, int verbose)
9482 {
9483         const size_t buflen = 4 * 1024 * 1024; /* 4M */
9484         void *buf;
9485         size_t page_size = sysconf(_SC_PAGESIZE);
9486         ssize_t bytes_read;
9487         ssize_t bytes_done;
9488         size_t count;
9489         off_t pos;
9490         unsigned long crc;
9491         unsigned long crc_array[LUSTRE_MIRROR_COUNT_MAX] = { 0 };
9492         int i;
9493         int rc = 0;
9494
9495         if (file_size == 0)
9496                 return 0;
9497
9498         rc = posix_memalign(&buf, page_size, buflen);
9499         if (rc) /* error code is returned directly */
9500                 return -rc;
9501
9502         if (verbose > 1) {
9503                 fprintf(stdout, "Verifying chunk "DEXT" on mirror:",
9504                         PEXT(&chunk->chunk));
9505                 for (i = 0; i < chunk->mirror_count; i++)
9506                         fprintf(stdout, " %u", chunk->mirror_id[i]);
9507                 fprintf(stdout, "\n");
9508         }
9509
9510         bytes_done = 0;
9511         count = MIN(chunk->chunk.e_end, file_size) - chunk->chunk.e_start;
9512         pos = chunk->chunk.e_start;
9513         while (bytes_done < count) {
9514                 /* compute initial CRC-32 checksum */
9515                 crc = crc32(0L, Z_NULL, 0);
9516                 memset(crc_array, 0, sizeof(crc_array));
9517
9518                 bytes_read = 0;
9519                 for (i = 0; i < chunk->mirror_count; i++) {
9520                         bytes_read = llapi_mirror_read(fd, chunk->mirror_id[i],
9521                                                        buf, buflen, pos);
9522                         if (bytes_read < 0) {
9523                                 rc = bytes_read;
9524                                 fprintf(stderr,
9525                                         "%s: failed to read data from mirror %u: %s.\n",
9526                                         progname, chunk->mirror_id[i],
9527                                         strerror(-rc));
9528                                 goto error;
9529                         }
9530
9531                         /* compute new CRC-32 checksum */
9532                         crc_array[i] = crc32(crc, buf, bytes_read);
9533                 }
9534
9535                 if (verbose)
9536                         print_checksums(chunk, crc_array);
9537
9538                 /* compare CRC-32 checksum values */
9539                 for (i = 1; i < chunk->mirror_count; i++) {
9540                         if (crc_array[i] != crc_array[0]) {
9541                                 rc = -EINVAL;
9542
9543                                 fprintf(stderr,
9544                                         "%s: chunk "DEXT" has different checksum value on mirror %u and mirror %u.\n",
9545                                         progname, PEXT(&chunk->chunk),
9546                                         chunk->mirror_id[0],
9547                                         chunk->mirror_id[i]);
9548                         }
9549                 }
9550
9551                 pos += bytes_read;
9552                 bytes_done += bytes_read;
9553         }
9554
9555         if (verbose > 1 && rc == 0) {
9556                 fprintf(stdout, "Verifying chunk "DEXT" on mirror:",
9557                         PEXT(&chunk->chunk));
9558                 for (i = 0; i < chunk->mirror_count; i++)
9559                         fprintf(stdout, " %u", chunk->mirror_id[i]);
9560                 fprintf(stdout, " PASS\n\n");
9561         }
9562
9563 error:
9564         free(buf);
9565         return rc;
9566 }
9567
9568 /**
9569  * lfs_mirror_verify_file() - Verify a mirrored file.
9570  * @fname:      Mirrored file name.
9571  * @mirror_ids: Specified mirror ids to be verified.
9572  * @ids_nr:     Number of specified mirror ids.
9573  * @verbose:    Verbose mode.
9574  *
9575  * This function verifies that each SYNC mirror of a mirrored file
9576  * specified by @fname contains exactly the same data.
9577  *
9578  * If @mirror_ids is specified, then the function will verify the
9579  * mirrors specified by @mirror_ids contain exactly the same data.
9580  *
9581  * If @verbose is specified, then the function will print where the
9582  * differences are if the data do not match. Otherwise, it will
9583  * just return an error in that case.
9584  *
9585  * Return: 0 on success or a negative error code on failure.
9586  */
9587 static inline
9588 int lfs_mirror_verify_file(const char *fname, __u16 *mirror_ids, int ids_nr,
9589                            int verbose)
9590 {
9591         struct verify_chunk chunks_array[1024] = { };
9592         struct llapi_layout *layout = NULL;
9593         struct stat stbuf;
9594         uint32_t flr_state;
9595         int fd;
9596         int chunk_count = 0;
9597         int idx = 0;
9598         int rc = 0;
9599         int rc1 = 0;
9600         int rc2 = 0;
9601
9602         if (stat(fname, &stbuf) < 0) {
9603                 fprintf(stderr, "%s: cannot stat file '%s': %s.\n",
9604                         progname, fname, strerror(errno));
9605                 rc = -errno;
9606                 goto error;
9607         }
9608
9609         if (!S_ISREG(stbuf.st_mode)) {
9610                 fprintf(stderr, "%s: '%s' is not a regular file.\n",
9611                         progname, fname);
9612                 rc = -EINVAL;
9613                 goto error;
9614         }
9615
9616         if (stbuf.st_size == 0) {
9617                 if (verbose)
9618                         fprintf(stdout, "%s: '%s' file size is 0.\n",
9619                                 progname, fname);
9620                 rc = 0;
9621                 goto error;
9622         }
9623
9624         fd = open(fname, O_DIRECT | O_RDONLY);
9625         if (fd < 0) {
9626                 fprintf(stderr, "%s: cannot open '%s': %s.\n",
9627                         progname, fname, strerror(errno));
9628                 rc = -errno;
9629                 goto error;
9630         }
9631
9632         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
9633         if (rc < 0) {
9634                 fprintf(stderr, "%s: '%s' llapi_lease_acquire failed: %s.\n",
9635                         progname, fname, strerror(errno));
9636                 goto close_fd;
9637         }
9638
9639         layout = llapi_layout_get_by_fd(fd, 0);
9640         if (layout == NULL) {
9641                 fprintf(stderr, "%s: '%s' llapi_layout_get_by_fd failed: %s.\n",
9642                         progname, fname, strerror(errno));
9643                 rc = -errno;
9644                 llapi_lease_release(fd);
9645                 goto close_fd;
9646         }
9647
9648         rc = llapi_layout_flags_get(layout, &flr_state);
9649         if (rc < 0) {
9650                 fprintf(stderr, "%s: '%s' llapi_layout_flags_get failed: %s.\n",
9651                         progname, fname, strerror(errno));
9652                 rc = -errno;
9653                 goto free_layout;
9654         }
9655
9656         flr_state &= LCM_FL_FLR_MASK;
9657         switch (flr_state) {
9658         case LCM_FL_NONE:
9659                 rc = -EINVAL;
9660                 fprintf(stderr, "%s: '%s' file state error: %s.\n",
9661                         progname, fname, llapi_layout_flags_string(flr_state));
9662                 goto free_layout;
9663         default:
9664                 break;
9665         }
9666
9667         /* find out mirror chunks to be verified */
9668         chunk_count = lfs_mirror_prepare_chunk(layout, chunks_array,
9669                                                ARRAY_SIZE(chunks_array));
9670         if (chunk_count < 0) {
9671                 rc = chunk_count;
9672                 goto free_layout;
9673         }
9674
9675         if (ids_nr > 0)
9676                 /* filter specified mirror ids */
9677                 filter_mirror_id(chunks_array, chunk_count, mirror_ids, ids_nr);
9678
9679         if (verbose > 2)
9680                 print_chunks(fname, chunks_array, chunk_count);
9681
9682         for (idx = 0; idx < chunk_count; idx++) {
9683                 if (chunks_array[idx].chunk.e_start >= stbuf.st_size) {
9684                         if (verbose)
9685                                 fprintf(stdout,
9686                                         "%s: '%s' chunk "DEXT" exceeds file size %#llx: skipped\n",
9687                                         progname, fname,
9688                                         PEXT(&chunks_array[idx].chunk),
9689                                         (unsigned long long)stbuf.st_size);
9690                         break;
9691                 }
9692
9693                 if (chunks_array[idx].mirror_count == 0) {
9694                         fprintf(stderr,
9695                                 "%s: '%s' chunk "DEXT" is invalid in all of the mirrors: ",
9696                                 progname, fname,
9697                                 PEXT(&chunks_array[idx].chunk));
9698                         if (verbose) {
9699                                 fprintf(stderr, "skipped\n");
9700                                 continue;
9701                         }
9702                         rc = -EINVAL;
9703                         fprintf(stderr, "failed\n");
9704                         goto free_layout;
9705                 }
9706
9707                 if (chunks_array[idx].mirror_count == 1) {
9708                         if (verbose)
9709                                 fprintf(stdout,
9710                                         "%s: '%s' chunk "DEXT" is only valid in mirror %u: skipped\n",
9711                                         progname, fname,
9712                                         PEXT(&chunks_array[idx].chunk),
9713                                         chunks_array[idx].mirror_id[0]);
9714                         continue;
9715                 }
9716
9717                 rc = llapi_lease_check(fd);
9718                 if (rc != LL_LEASE_RDLCK) {
9719                         fprintf(stderr, "%s: '%s' lost lease lock.\n",
9720                                 progname, fname);
9721                         goto free_layout;
9722                 }
9723
9724                 /* verify one chunk */
9725                 rc1 = lfs_mirror_verify_chunk(fd, stbuf.st_size,
9726                                               &chunks_array[idx], verbose);
9727                 if (rc1 < 0) {
9728                         rc2 = rc1;
9729                         if (!verbose) {
9730                                 rc = rc1;
9731                                 goto free_layout;
9732                         }
9733                 }
9734         }
9735
9736         if (rc2 < 0)
9737                 rc = rc2;
9738
9739 free_layout:
9740         llapi_layout_free(layout);
9741         llapi_lease_release(fd);
9742 close_fd:
9743         close(fd);
9744 error:
9745         return rc;
9746 }
9747
9748 /**
9749  * lfs_mirror_verify() - Parse and execute lfs mirror verify command.
9750  * @argc: The count of lfs mirror verify command line arguments.
9751  * @argv: Array of strings for lfs mirror verify command line arguments.
9752  *
9753  * This function parses lfs mirror verify command and verifies the
9754  * specified mirrored file(s).
9755  *
9756  * Return: 0 on success or a negative error code on failure.
9757  */
9758 static inline int lfs_mirror_verify(int argc, char **argv)
9759 {
9760         __u16 mirror_ids[LUSTRE_MIRROR_COUNT_MAX] = { 0 };
9761         int ids_nr = 0;
9762         int c;
9763         int verbose = 0;
9764         int rc = 0;
9765         int rc1 = 0;
9766         char cmd[PATH_MAX];
9767
9768         struct option long_opts[] = {
9769         { .val = 'o',   .name = "only",         .has_arg = required_argument },
9770         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
9771         { .name = NULL } };
9772
9773         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
9774         progname = cmd;
9775         while ((c = getopt_long(argc, argv, "o:v", long_opts, NULL)) >= 0) {
9776                 switch (c) {
9777                 case 'o':
9778                         rc = parse_mirror_ids(mirror_ids,
9779                                               ARRAY_SIZE(mirror_ids),
9780                                               optarg);
9781                         if (rc < 0) {
9782                                 fprintf(stderr,
9783                                         "%s: bad mirror ids '%s'.\n",
9784                                         progname, optarg);
9785                                 goto error;
9786                         }
9787                         ids_nr = rc;
9788                         if (ids_nr < 2) {
9789                                 fprintf(stderr,
9790                                         "%s: at least 2 mirror ids needed with '--only' option.\n",
9791                                         progname);
9792                                 rc = CMD_HELP;
9793                                 goto error;
9794                         }
9795                         break;
9796                 case 'v':
9797                         verbose++;
9798                         break;
9799                 default:
9800                         fprintf(stderr, "%s: option '%s' unrecognized.\n",
9801                                 progname, argv[optind - 1]);
9802                         rc = -EINVAL;
9803                         goto error;
9804                 }
9805         }
9806
9807         if (argc == optind) {
9808                 fprintf(stderr, "%s: no file name given.\n", progname);
9809                 rc = CMD_HELP;
9810                 goto error;
9811         }
9812
9813         if (ids_nr > 0 && argc > optind + 1) {
9814                 fprintf(stderr,
9815                         "%s: '--only' cannot be used upon multiple files.\n",
9816                         progname);
9817                 rc = CMD_HELP;
9818                 goto error;
9819
9820         }
9821
9822         if (ids_nr > 0) {
9823                 rc = verify_mirror_ids(argv[optind], mirror_ids, ids_nr);
9824                 if (rc < 0)
9825                         goto error;
9826         }
9827
9828         rc = 0;
9829         for (; optind < argc; optind++) {
9830                 rc1 = lfs_mirror_verify_file(argv[optind], mirror_ids, ids_nr,
9831                                              verbose);
9832                 if (rc1 < 0)
9833                         rc = rc1;
9834         }
9835 error:
9836         return rc;
9837 }
9838
9839 /**
9840  * lfs_mirror() - Parse and execute lfs mirror commands.
9841  * @argc: The count of lfs mirror command line arguments.
9842  * @argv: Array of strings for lfs mirror command line arguments.
9843  *
9844  * This function parses lfs mirror commands and performs the
9845  * corresponding functions specified in mirror_cmdlist[].
9846  *
9847  * Return: 0 on success or an error code on failure.
9848  */
9849 static int lfs_mirror(int argc, char **argv)
9850 {
9851         char cmd[PATH_MAX];
9852         int rc = 0;
9853
9854         setlinebuf(stdout);
9855
9856         Parser_init("lfs-mirror > ", mirror_cmdlist);
9857
9858         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
9859         progname = cmd;
9860         program_invocation_short_name = cmd;
9861         if (argc > 1)
9862                 rc = Parser_execarg(argc - 1, argv + 1, mirror_cmdlist);
9863         else
9864                 rc = Parser_commands();
9865
9866         return rc < 0 ? -rc : rc;
9867 }
9868
9869 static void lustre_som_swab(struct lustre_som_attrs *attrs)
9870 {
9871 #if __BYTE_ORDER == __BIG_ENDIAN
9872         __swab16s(&attrs->lsa_valid);
9873         __swab64s(&attrs->lsa_size);
9874         __swab64s(&attrs->lsa_blocks);
9875 #endif
9876 }
9877
9878 enum lfs_som_type {
9879         LFS_SOM_SIZE = 0x1,
9880         LFS_SOM_BLOCKS = 0x2,
9881         LFS_SOM_FLAGS = 0x4,
9882         LFS_SOM_ATTR_ALL = LFS_SOM_SIZE | LFS_SOM_BLOCKS |
9883                            LFS_SOM_FLAGS,
9884 };
9885
9886 static int lfs_getsom(int argc, char **argv)
9887 {
9888         const char *path;
9889         struct lustre_som_attrs *attrs;
9890         char buf[sizeof(*attrs) + 64];
9891         enum lfs_som_type type = LFS_SOM_ATTR_ALL;
9892         int rc = 0, c;
9893
9894         while ((c = getopt(argc, argv, "sbf")) != -1) {
9895                 switch (c) {
9896                 case 's':
9897                         type = LFS_SOM_SIZE;
9898                         break;
9899                 case 'b':
9900                         type = LFS_SOM_BLOCKS;
9901                         break;
9902                 case 'f':
9903                         type = LFS_SOM_FLAGS;
9904                         break;
9905                 default:
9906                         fprintf(stderr, "%s: invalid option '%c'\n",
9907                                 progname, optopt);
9908                         return CMD_HELP;
9909                 }
9910         }
9911
9912         argc -= optind;
9913         argv += optind;
9914
9915         if (argc != 1) {
9916                 fprintf(stderr, "%s: %s\n",
9917                         progname, argc == 0 ? "miss file target" :
9918                         "input more than 2 files");
9919                 return CMD_HELP;
9920         }
9921
9922         path = argv[0];
9923         attrs = (void *)buf;
9924         rc = lgetxattr(path, "trusted.som", attrs, sizeof(buf));
9925         if (rc < 0) {
9926                 rc = -errno;
9927                 fprintf(stderr, "%s failed to get som xattr: %s (%d)\n",
9928                         argv[0], strerror(errno), errno);
9929                 return rc;
9930         }
9931
9932         lustre_som_swab(attrs);
9933
9934         switch (type) {
9935         case LFS_SOM_ATTR_ALL:
9936                 printf("file: %s size: %llu blocks: %llu flags: %x\n",
9937                        path, (unsigned long long)attrs->lsa_size,
9938                        (unsigned long long)attrs->lsa_blocks,
9939                        attrs->lsa_valid);
9940                 break;
9941         case LFS_SOM_SIZE:
9942                 printf("%llu\n", (unsigned long long)attrs->lsa_size);
9943                 break;
9944         case LFS_SOM_BLOCKS:
9945                 printf("%llu\n", (unsigned long long)attrs->lsa_blocks);
9946                 break;
9947         case LFS_SOM_FLAGS:
9948                 printf("%x\n", attrs->lsa_valid);
9949                 break;
9950         default:
9951                 fprintf(stderr, "%s: unknown option\n", progname);
9952                 return CMD_HELP;
9953         }
9954
9955         return 0;
9956 }
9957
9958 /**
9959  * lfs_mirror_list_commands() - List lfs mirror commands.
9960  * @argc: The count of command line arguments.
9961  * @argv: Array of strings for command line arguments.
9962  *
9963  * This function lists lfs mirror commands defined in mirror_cmdlist[].
9964  *
9965  * Return: 0 on success.
9966  */
9967 static int lfs_mirror_list_commands(int argc, char **argv)
9968 {
9969         char buffer[81] = "";
9970
9971         Parser_list_commands(mirror_cmdlist, buffer, sizeof(buffer),
9972                              NULL, 0, 4);
9973
9974         return 0;
9975 }
9976
9977 static int lfs_list_commands(int argc, char **argv)
9978 {
9979         char buffer[81] = ""; /* 80 printable chars + terminating NUL */
9980
9981         Parser_list_commands(cmdlist, buffer, sizeof(buffer), NULL, 0, 4);
9982
9983         return 0;
9984 }
9985
9986 int main(int argc, char **argv)
9987 {
9988         int rc;
9989
9990         /* Ensure that liblustreapi constructor has run */
9991         if (!llapi_liblustreapi_initialized())
9992                 fprintf(stderr, "liblustreapi was not properly initialized\n");
9993
9994         setlinebuf(stdout);
9995         opterr = 0;
9996
9997         Parser_init("lfs > ", cmdlist);
9998
9999         progname = program_invocation_short_name; /* Used in error messages */
10000         if (argc > 1) {
10001                 llapi_set_command_name(argv[1]);
10002                 rc = Parser_execarg(argc - 1, argv + 1, cmdlist);
10003                 llapi_clear_command_name();
10004         } else {
10005                 rc = Parser_commands();
10006         }
10007
10008         return rc < 0 ? -rc : rc;
10009 }
10010
10011 #ifdef _LUSTRE_IDL_H_
10012 /* Everything we need here should be included by lustreapi.h. */
10013 # error "lfs should not depend on lustre_idl.h"
10014 #endif /* _LUSTRE_IDL_H_ */