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