Whamcloud - gitweb
LU-930 utils: fix lfs setstripe option description
[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|-o 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:",<