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