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