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