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