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