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