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