Whamcloud - gitweb
LU-13142 lod: cleanup layout checking
[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         "                 [--pool|-p <pool_name>]\n"                    \
190         "                 [--ost|-o <ost_indices>]\n"                   \
191         "                 [--yaml|-y <yaml_template_file>]\n"           \
192         "                 [--copy=<lustre_src>]\n"
193
194 #define SSM_HELP_COMMON \
195         "\tstripe_count: Number of OSTs to stripe over (0=fs default, -1 all)\n" \
196         "\t              Using -C instead of -c allows overstriping, which\n" \
197          "\t             will place more than one stripe per OST if\n" \
198          "\t             stripe_count is greater than the number of OSTs\n" \
199         "\tstart_ost_idx: OST index of first stripe (-1=default round robin)\n"\
200         "\tstripe_size:  Number of bytes on each OST (0=fs default)\n" \
201         "\t              Can be specified with K, M or G (for KB, MB, GB\n" \
202         "\t              respectively)\n"                               \
203         "\tpool_name:    Name of OST pool to use (default none)\n"      \
204         "\tlayout:       stripe pattern type: raid0, mdt (default raid0)\n"\
205         "\tost_indices:  List of OST indices, can be repeated multiple times\n"\
206         "\t              Indices be specified in a format of:\n"        \
207         "\t                -o <ost_1>,<ost_i>-<ost_j>,<ost_n>\n"        \
208         "\t              Or:\n"                                         \
209         "\t                -o <ost_1> -o <ost_i>-<ost_j> -o <ost_n>\n"  \
210         "\t              If --pool is set with --ost, then the OSTs\n"  \
211         "\t              must be the members of the pool.\n"            \
212         "\tcomp_end:     Extent end of component, start after previous end.\n"\
213         "\t              Can be specified with K, M or G (for KB, MB, GB\n" \
214         "\t              respectively, -1 for EOF). Must be a multiple of\n"\
215         "\t              stripe_size.\n"                                      \
216         "\tyaml_template_file:\n"                                             \
217         "\t              YAML layout template file, can't be used with -c,\n" \
218         "\t              -i, -S, -p, -o, or -E arguments.\n"                  \
219         "\tlustre_src:   Lustre file/dir whose layout info is used to set\n"  \
220         "\t              another lustre file or directory, can't used with\n" \
221         "\t              -c, -i, -S, -p, -o, or -E arguments.\n"
222
223 #define MIRROR_CREATE_HELP                                                     \
224         "\tmirror_count: Number of mirrors to be created with the upcoming\n"  \
225         "\t              setstripe layout options\n"                           \
226         "\t              It defaults to 1 if not specified; if specified,\n"   \
227         "\t              it must follow the option without a space.\n"         \
228         "\t              The option can also be repeated multiple times to\n"  \
229         "\t              separate mirrors that have different layouts.\n"      \
230         "\tsetstripe options: Mirror layout\n"                                 \
231         "\t              It can be a plain layout or a composite layout.\n"    \
232         "\t              If not specified, the stripe options inherited\n"     \
233         "\t              from the previous component will be used.\n"          \
234         "\tflags:        set flags to the component of the current mirror.\n"  \
235         "\t              Only \"prefer\" flag is supported so far.\n"
236
237 #define MIRROR_EXTEND_HELP                                                     \
238         MIRROR_CREATE_HELP                                                     \
239         "\tvictim_file:  The layout of victim_file will be split and used\n"   \
240         "\t              as a mirror added to the mirrored file.\n"            \
241         "\tno-verify:    This option indicates not to verify the mirror(s)\n"  \
242         "\t              from victim file(s) in case the victim file(s)\n"     \
243         "\t              contains the same data as the original mirrored\n"    \
244         "\t              file.\n"
245
246 #define MIRROR_EXTEND_USAGE                                                    \
247         "                 <--mirror-count|-N[mirror_count]>\n"                 \
248         "                 [setstripe options|-f <victim_file>]\n"              \
249         "                 [--no-verify]\n"
250
251 #define SETSTRIPE_USAGE                                                 \
252         SSM_CMD_COMMON("setstripe")                                     \
253         MIRROR_EXTEND_USAGE                                             \
254         "                 <directory|filename>\n"                       \
255         SSM_HELP_COMMON                                                 \
256         MIRROR_EXTEND_HELP
257
258 #define MIGRATE_USAGE                                                   \
259         SSM_CMD_COMMON("migrate  ")                                     \
260         "                 [--block|-b] [--non-block|-n]\n"              \
261         "                 [--non-direct|-D] [--verbose|-v]\n"           \
262         "                 <filename>\n"                                 \
263         SSM_HELP_COMMON                                                 \
264         "\n"                                                            \
265         "\tblock:        Block file access during data migration (default)\n" \
266         "\tnon-block:    Abort migrations if concurrent access is detected\n" \
267         "\tnon-direct:   Do not use direct I/O to copy file contents\n" \
268         "\tverbose:      Print each filename as it is migrated\n"       \
269
270 #define SETDIRSTRIPE_USAGE                                              \
271         "               [--mdt-count|-c stripe_count>\n"                \
272         "               [--mdt-hash|-H mdt_hash]\n"                     \
273         "               [--mdt-index|-i mdt_index[,mdt_index,...]\n"    \
274         "               [--default|-D] [--mode|-o mode] <dir>\n"        \
275         "\tstripe_count: stripe count of the striped directory\n"       \
276         "\tmdt_index: MDT index of first stripe\n"                      \
277         "\tmdt_hash:  hash type of the striped directory. mdt types:\n" \
278         "       fnv_1a_64 FNV-1a hash algorithm (default)\n"            \
279         "       all_char  sum of characters % MDT_COUNT (not recommended)\n" \
280         "       space     create subdirectories with balanced space usage\n" \
281         "\tdefault_stripe: set default dirstripe of the directory\n"    \
282         "\tmode: the file access permission of the directory (octal)\n" \
283         "To create dir with a foreign (free format) layout :\n" \
284         "setdirstripe|mkdir --foreign[=<foreign_type>] -x|-xattr <string> " \
285                 "[--mode|-m mode] [--flags <hex>] <dir>\n" \
286         "\tmode: the mode of the directory\n" \
287         "\tforeign_type: none or daos\n"
288
289 /**
290  * command_t mirror_cmdlist - lfs mirror commands.
291  */
292 command_t mirror_cmdlist[] = {
293         { .pc_name = "create", .pc_func = lfs_mirror_create,
294           .pc_help = "Create a mirrored file.\n"
295                 "usage: lfs mirror create "
296                 "<--mirror-count|-N[mirror_count]> "
297                 "[setstripe options] ... <filename|directory> ...\n"
298           MIRROR_CREATE_HELP },
299         { .pc_name = "delete", .pc_func = lfs_mirror_delete,
300           .pc_help = "delete a mirror from a file.\n"
301                 "usage: lfs mirror delete {--comp-id|-I <comp_id>|-p <pool>} <mirrored_file> ...\n"
302         },
303         { .pc_name = "extend", .pc_func = lfs_mirror_extend,
304           .pc_help = "Extend a mirrored file.\n"
305                 "usage: lfs mirror extend "
306                 "<--mirror-count|-N[mirror_count]> [--no-verify] "
307                 "[setstripe options|-f <victim_file>] ... <filename> ...\n"
308           MIRROR_EXTEND_HELP },
309         { .pc_name = "split", .pc_func = lfs_mirror_split,
310           .pc_help = "Split a mirrored file.\n"
311         "usage: lfs mirror split <--mirror-id <mirror_id> |\n"
312         "\t             <--component-id|-I <comp_id>|-p <pool>> [--destroy|-d]\n"
313         "\t             [-f <new_file>] <mirrored_file> ...\n"
314         "\tmirror_id:   The numerical unique identifier for a mirror. It\n"
315         "\t             can be fetched by lfs getstripe command.\n"
316         "\tcomp_id:     Unique component ID within a mirror.\n"
317         "\tpool:        Components on specified pool.\n"
318         "\tnew_file:    This option indicates the layout of the split\n"
319         "\t             mirror will be stored into. If not specified,\n"
320         "\t             a new file named <mirrored_file>.mirror~<mirror_id>\n"
321         "\t             will be used.\n" },
322         { .pc_name = "read", .pc_func = lfs_mirror_read,
323           .pc_help = "Read the content of a specified mirror of a file.\n"
324                 "usage: lfs mirror read <--mirror-id|-N <mirror_id> "
325                 "[--outfile|-o <output_file>] <mirrored_file>\n" },
326         { .pc_name = "write", .pc_func = lfs_mirror_write,
327           .pc_help = "Write to a specified mirror of a file.\n"
328                 "usage: lfs mirror write <--mirror-id|-N <mirror_id> "
329                 "[--inputfile|-i <input_file>] <mirrored_file>\n" },
330         { .pc_name = "copy", .pc_func = lfs_mirror_copy,
331           .pc_help = "Copy a specified mirror to other mirror(s) of a file.\n"
332                 "usage: lfs mirror copy <--read-mirror|-i <id0>> "
333                 "<--write-mirror|-o <id1,id2>> <mirrored_file>\n" },
334         { .pc_name = "resync", .pc_func = lfs_mirror_resync,
335           .pc_help = "Resynchronizes out-of-sync mirrored file(s).\n"
336                 "usage: lfs mirror resync [--only <mirror_id[,...]>] "
337                 "<mirrored file> [<mirrored file2>...]\n"},
338         { .pc_name = "verify", .pc_func = lfs_mirror_verify,
339           .pc_help = "Verify mirrored file(s).\n"
340                 "usage: lfs mirror verify "
341                 "[--only <mirror_id,mirror_id2[,...]>] "
342                 "[--verbose|-v] <mirrored_file> [<mirrored_file2> ...]\n"},
343         { .pc_name = "list-commands", .pc_func = lfs_mirror_list_commands,
344           .pc_help = "list commands supported by lfs mirror"},
345         { .pc_name = "help", .pc_func = Parser_help, .pc_help = "help" },
346         { .pc_name = "exit", .pc_func = Parser_quit, .pc_help = "quit" },
347         { .pc_name = "quit", .pc_func = Parser_quit, .pc_help = "quit" },
348         { .pc_help = NULL }
349 };
350
351 /**
352  * command_t pcc_cmdlist - lfs pcc commands.
353  */
354 command_t pcc_cmdlist[] = {
355         { .pc_name = "attach", .pc_func = lfs_pcc_attach,
356           .pc_help = "Attach given files to the Persistent Client Cache.\n"
357                 "usage: lfs pcc attach <--id|-i NUM> <file> ...\n"
358                 "\t-i: archive id for RW-PCC\n" },
359         { .pc_name = "attach_fid", .pc_func = lfs_pcc_attach_fid,
360           .pc_help = "Attach given files into PCC by FID(s).\n"
361                 "usage: lfs pcc attach_id <--id|-i NUM> <--mnt|-m mnt> "
362                 "<fid> ...\n"
363                 "\t-i: archive id for RW-PCC\n"
364                 "\t-m: Lustre mount point\n" },
365         { .pc_name = "state", .pc_func = lfs_pcc_state,
366           .pc_help = "Display the PCC state for given files.\n"
367                 "usage: lfs pcc state <file> ...\n" },
368         { .pc_name = "detach", .pc_func = lfs_pcc_detach,
369           .pc_help = "Detach given files from the Persistent Client Cache.\n"
370                 "usage: lfs pcc detach <file> ...\n" },
371         { .pc_name = "detach_fid", .pc_func = lfs_pcc_detach_fid,
372           .pc_help = "Detach given files from PCC by FID(s).\n"
373                 "usage: lfs pcc detach_fid <mntpath> <fid>...\n" },
374         { .pc_name = "list-commands", .pc_func = lfs_pcc_list_commands,
375           .pc_help = "list commands supported by lfs pcc"},
376         { .pc_name = "help", .pc_func = Parser_help, .pc_help = "help" },
377         { .pc_name = "exit", .pc_func = Parser_quit, .pc_help = "quit" },
378         { .pc_name = "quit", .pc_func = Parser_quit, .pc_help = "quit" },
379         { .pc_help = NULL }
380 };
381
382 /* all available commands */
383 command_t cmdlist[] = {
384         {"setstripe", lfs_setstripe, 0,
385          "To create a file with specified striping/composite layout, or\n"
386          "create/replace the default layout on an existing directory:\n"
387          SSM_CMD_COMMON("setstripe")
388          "                 [--mode <mode>]\n"
389          "                 <directory|filename>\n"
390          " or\n"
391          "To add component(s) to an existing composite file:\n"
392          SSM_CMD_COMMON("setstripe --component-add")
393          SSM_HELP_COMMON
394          "To totally delete the default striping from an existing directory:\n"
395          "usage: setstripe -d <directory>\n"
396          " or\n"
397          "To create a mirrored file or set s default mirror layout on a directory:\n"
398          "usage: setstripe -N[mirror_count] [STRIPE_OPTIONS] <directory|filename>\n"
399          " or\n"
400          "To delete the last component(s) from an existing composite file\n"
401          "(note that this will also delete any data in those components):\n"
402          "usage: setstripe --component-del [--component-id|-I <comp_id>]\n"
403          "                               [--component-flags|-F <comp_flags>]\n"
404          "                               <filename>\n"
405          "\tcomp_id:     Unique component ID to delete\n"
406          "\tcomp_flags:  'init' indicating all instantiated components\n"
407          "\t             '^init' indicating all uninstantiated components\n"
408          "\t-I and -F cannot be specified at the same time\n"
409          "To create a file with a foreign (free format) layout:\n"
410          "usage: setstripe --foreign[=<foreign_type>]\n"
411          "                 --xattr|-x <layout_string> [--flags <hex>]\n"
412          "                 [--mode <mode>] <filename>\n"},
413         {"getstripe", lfs_getstripe, 0,
414          "To list the layout pattern for a given file or files in a\n"
415          "directory or recursively for all files in a directory tree.\n"
416          "usage: getstripe [--ost|-O <uuid>] [--quiet|-q] [--verbose|-v]\n"
417          "                 [--stripe-count|-c] [--stripe-index|-i] [--fid|-F]\n"
418          "                 [--pool|-p] [--stripe-size|-S] [--directory|-d]\n"
419          "                 [--mdt-index|-m] [--recursive|-r] [--raw|-R]\n"
420          "                 [--layout|-L] [--generation|-g] [--yaml|-y]\n"
421          "                 [--component-id[=comp_id]|-I[comp_id]]\n"
422          "                 [--component-flags[=comp_flags]]\n"
423          "                 [--component-count]\n"
424          "                 [--extension-size|--ext-size|-z]\n"
425          "                 [--component-start[=[+-]comp_start]]\n"
426          "                 [--component-end[=[+-]comp_end]|-E[[+-]comp_end]]\n"
427          "                 [[!] --mirror-index=[+-]<index> |\n"
428          "                  [!] --mirror-id=[+-]<id>]\n"
429          "                 <directory|filename> ..."},
430         {"setdirstripe", lfs_setdirstripe, 0,
431          "To create a striped directory on a specified MDT. This can only\n"
432          "be done on MDT0 with the right of administrator.\n"
433          "usage: setdirstripe [OPTION] <directory>\n"
434          SETDIRSTRIPE_USAGE},
435         {"getdirstripe", lfs_getdirstripe, 0,
436          "To list the layout pattern info for a given directory\n"
437          "or recursively for all directories in a directory tree.\n"
438          "usage: getdirstripe [--mdt-count|-c] [--mdt-index|-m|-i]\n"
439          "                    [--mdt-hash|-H] [--obd|-O <uuid>]\n"
440          "                    [--recursive|-r] [--yaml|-y]\n"
441          "                    [--verbose|-v] [--default|-D] <dir> ..."},
442         {"mkdir", lfs_setdirstripe, 0,
443          "To create a striped directory on a specified MDT. This can only\n"
444          "be done on MDT0 with the right of administrator.\n"
445          "usage: mkdir [OPTION] <directory>\n"
446          SETDIRSTRIPE_USAGE},
447         {"rm_entry", lfs_rmentry, 0,
448          "To remove the name entry of the remote directory. Note: This\n"
449          "command will only delete the name entry, i.e. the remote directory\n"
450          "will become inaccessable after this command. This can only be done\n"
451          "by the administrator\n"
452          "usage: rm_entry <dir>\n"},
453         {"pool_list", lfs_poollist, 0,
454          "List pools or pool OSTs\n"
455          "usage: pool_list <fsname>[.<pool>] | <pathname>\n"},
456         {"find", lfs_find, 0,
457          "find files matching given attributes recursively in directory tree.\n"
458          "usage: find <directory|filename> ...\n"
459          "     [[!] --atime|-A [+-]N[smhdwy]] [[!] --ctime|-C [+-]N[smhdwy]]\n"
460          "     [[!] --mtime|-M [+-]N[smhdwy]] [[!] --blocks|-b N]\n"
461          "     [[!] --newer[XY] <reference>]\n"
462          "     [--maxdepth|-D N] [[!] --mdt-index|--mdt|-m <uuid|index,...>]\n"
463          "     [[!] --name|-n <pattern>] [[!] --ost|-O <uuid|index,...>]\n"
464          "     [--print|-P] [--print0|-0] [[!] --size|-s [+-]N[bkMGTPE]]\n"
465          "     [[!] --stripe-count|-c [+-]<stripes>]\n"
466          "     [[!] --stripe-index|-i <index,...>]\n"
467          "     [[!] --stripe-size|-S [+-]N[kMGT]] [[!] --type|-t <filetype>]\n"
468          "     [[!] --gid|-g|--group|-G <gid>|<gname>]\n"
469          "     [[!] --uid|-u|--user|-U <uid>|<uname>] [[!] --pool <pool>]\n"
470          "     [[!] --projid <projid>]\n"
471          "     [[!] --foreign[=<foreign_type>]]\n"
472          "     [[!] --layout|-L released,raid0,mdt]\n"
473          "     [[!] --foreign[=<foreign_type>]]\n"
474          "     [[!] --component-count [+-]<comp_cnt>]\n"
475          "     [[!] --component-start [+-]N[kMGTPE]]\n"
476          "     [[!] --component-end|-E [+-]N[kMGTPE]]\n"
477          "     [[!] --component-flags <comp_flags>]\n"
478          "     [[!] --mirror-count|-N [+-]<n>]\n"
479          "     [[!] --mirror-state <[^]state>]\n"
480          "     [[!] --mdt-count|-T [+-]<stripes>]\n"
481          "     [[!] --mdt-hash|-H <hashtype>\n"
482          "     [[!] --mdt-index|-m <uuid|index,...>]\n"
483          "\t !: used before an option indicates 'NOT' requested attribute\n"
484          "\t -: used before a value indicates less than requested value\n"
485          "\t +: used before a value indicates more than requested value\n"
486          "\thashtype:   hash type of the striped directory.\n"
487          "\t            fnv_1a_64 FNV-1a hash algorithm\n"
488          "\t            all_char  sum of characters % MDT_COUNT\n"},
489         {"check", lfs_check, 0,
490          "Display the status of MGTs, MDTs or OSTs (as specified in the command)\n"
491          "or all the servers (MGTs, MDTs and OSTs).\n"
492          "usage: check <mgts|osts|mdts|all>"},
493         {"osts", lfs_osts, 0, "list OSTs connected to client "
494          "[for specified path only]\n" "usage: osts [path]"},
495         {"mdts", lfs_mdts, 0, "list MDTs connected to client "
496          "[for specified path only]\n" "usage: mdts [path]"},
497         {"df", lfs_df, 0,
498          "report filesystem disk space usage or inodes usage "
499          "of each MDS and all OSDs or a batch belonging to a specific pool.\n"
500          "Usage: df [-i] [-h] [--lazy|-l] [--pool|-p <fsname>[.<pool>] [path]"},
501         {"getname", lfs_getname, 0,
502          "list instances and specified mount points [for specified path only]\n"
503          "Usage: getname [--help|-h] [--instance|-i] [--fsname|-n] [path ...]"},
504 #ifdef HAVE_SYS_QUOTA_H
505         {"setquota", lfs_setquota, 0, "Set filesystem quotas.\n"
506          "usage: setquota <-u|-g|-p> <uname>|<uid>|<gname>|<gid>|<projid>\n"
507          "                -b <block-softlimit> -B <block-hardlimit>\n"
508          "                -i <inode-softlimit> -I <inode-hardlimit> <filesystem>\n"
509          "       setquota <-u|--user|-g|--group|-p|--projid> <uname>|<uid>|<gname>|<gid>|<projid>\n"
510          "                [--block-softlimit <block-softlimit>]\n"
511          "                [--block-hardlimit <block-hardlimit>]\n"
512          "                [--inode-softlimit <inode-softlimit>]\n"
513          "                [--inode-hardlimit <inode-hardlimit>] <filesystem>\n"
514          "       setquota [-t] <-u|--user|-g|--group|-p|--projid>\n"
515          "                [--block-grace <block-grace>]\n"
516          "                [--inode-grace <inode-grace>] <filesystem>\n"
517          "       setquota <-U|-G|-P>\n"
518          "                -b <block-softlimit> -B <block-hardlimit>\n"
519          "                -i <inode-softlimit> -I <inode-hardlimit> <filesystem>\n"
520          "       setquota <-U|--default-usr|-G|--default-grp|-P|--default-prj>\n"
521          "                [--block-softlimit <block-softlimit>]\n"
522          "                [--block-hardlimit <block-hardlimit>]\n"
523          "                [--inode-softlimit <inode-softlimit>]\n"
524          "                [--inode-hardlimit <inode-hardlimit>] <filesystem>\n"
525          "       setquota <-u|-g|-p> <uname>|<uid>|<gname>|<gid>|<projid>\n"
526          "                <-d|--default>\n"
527          "       -b can be used instead of --block-softlimit/--block-grace\n"
528          "       -B can be used instead of --block-hardlimit\n"
529          "       -i can be used instead of --inode-softlimit/--inode-grace\n"
530          "       -I can be used instead of --inode-hardlimit\n"
531          "       -d can be used instead of --default\n\n"
532          "Note: The total quota space will be split into many qunits and\n"
533          "      balanced over all server targets, the minimal qunit size is\n"
534          "      1M bytes for block space and 1K inodes for inode space.\n\n"
535          "      The maximum quota grace time is 2^48 - 1 seconds.\n\n"
536          "      Quota space rebalancing process will stop when this mininum\n"
537          "      value is reached. As a result, quota exceeded can be returned\n"
538          "      while many targets still have 1MB or 1K inodes of spare\n"
539          "      quota space."},
540         {"quota", lfs_quota, 0, "Display disk usage and limits.\n"
541          "usage: quota [-q] [-v] [-h] [-o <obd_uuid>|-i <mdt_idx>|-I "
542                        "<ost_idx>]\n"
543          "             [<-u|-g|-p> <uname>|<uid>|<gname>|<gid>|<projid>] <filesystem>\n"
544          "       quota [-o <obd_uuid>|-i <mdt_idx>|-I <ost_idx>] -t <-u|-g|-p> <filesystem>\n"
545         "        quota [-q] [-v] [h] <-U|-G|-P> <filesystem>"},
546         {"project", lfs_project, 0,
547          "Change or list project attribute for specified file or directory.\n"
548          "usage: project [-d|-r] <file|directory...>\n"
549          "         list project ID and flags on file(s) or directories\n"
550          "       project [-p id] [-s] [-r] <file|directory...>\n"
551          "         set project ID and/or inherit flag for specified file(s) or directories\n"
552          "       project -c [-d|-r [-p id] [-0]] <file|directory...>\n"
553          "         check project ID and flags on file(s) or directories, print outliers\n"
554          "       project -C [-r] [-k] <file|directory...>\n"
555          "         clear the project inherit flag and ID on the file or directory\n"
556         },
557 #endif
558         {"flushctx", lfs_flushctx, 0, "Flush security context for current user.\n"
559          "usage: flushctx [-k] [mountpoint...]"},
560         {"changelog", lfs_changelog, 0,
561          "Show the metadata changes on an MDT."
562          "\nusage: changelog <mdtname> [startrec [endrec]]"},
563         {"changelog_clear", lfs_changelog_clear, 0,
564          "Indicate that old changelog records up to <endrec> are no longer of "
565          "interest to consumer <id>, allowing the system to free up space.\n"
566          "An <endrec> of 0 means all records.\n"
567          "usage: changelog_clear <mdtname> <id> <endrec>"},
568         {"fid2path", lfs_fid2path, 0,
569          "Resolve the full path(s) for given FID(s). For a specific hardlink "
570          "specify link number <linkno>.\n"
571          "usage: fid2path [-c] [--link|-l <linkno>] <fsname|root> <fid> ..."},
572         {"path2fid", lfs_path2fid, 0, "Display the fid(s) for a given path(s).\n"
573          "usage: path2fid [--parents] <path> ..."},
574         {"rmfid", lfs_rmfid, 0, "Remove file(s) by FID(s)\n"
575          "usage: rmfid <fsname|rootpath> <fid> ..."},
576         {"data_version", lfs_data_version, 0, "Display file data version for "
577          "a given path.\n" "usage: data_version -[n|r|w] <path>"},
578         {"hsm_state", lfs_hsm_state, 0, "Display the HSM information (states, "
579          "undergoing actions) for given files.\n usage: hsm_state <file> ..."},
580         {"hsm_set", lfs_hsm_set, 0, "Set HSM user flag on specified files.\n"
581          "usage: hsm_set [--norelease] [--noarchive] [--dirty] [--exists] "
582          "[--archived] [--lost] [--archive-id NUM] <file> ..."},
583         {"hsm_clear", lfs_hsm_clear, 0, "Clear HSM user flag on specified "
584          "files.\n"
585          "usage: hsm_clear [--norelease] [--noarchive] [--dirty] [--exists] "
586          "[--archived] [--lost] <file> ..."},
587         {"hsm_action", lfs_hsm_action, 0, "Display current HSM request for "
588          "given files.\n" "usage: hsm_action <file> ..."},
589         {"hsm_archive", lfs_hsm_archive, 0,
590          "Archive file to external storage.\n"
591          "usage: hsm_archive [--filelist FILELIST] [--data DATA] [--archive NUM] "
592          "<file> ..."},
593         {"hsm_restore", lfs_hsm_restore, 0,
594          "Restore file from external storage.\n"
595          "usage: hsm_restore [--filelist FILELIST] [--data DATA] <file> ..."},
596         {"hsm_release", lfs_hsm_release, 0,
597          "Release files from Lustre.\n"
598          "usage: hsm_release [--filelist FILELIST] [--data DATA] <file> ..."},
599         {"hsm_remove", lfs_hsm_remove, 0,
600          "Remove file copy from external storage.\n"
601          "usage: hsm_remove [--filelist FILELIST] [--data DATA] "
602          "[--archive NUM]\n"
603          "                  (FILE [FILE ...] | "
604          "--mntpath MOUNTPATH FID [FID ...])\n"
605          "\n"
606          "Note: To remove an archived copy of a file already deleted from a "
607          "Lustre FS, the\n"
608          "--mntpath option and a list of FIDs must be specified"
609         },
610         {"hsm_cancel", lfs_hsm_cancel, 0,
611          "Cancel requests related to specified files.\n"
612          "usage: hsm_cancel [--filelist FILELIST] [--data DATA] <file> ..."},
613         {"swap_layouts", lfs_swap_layouts, 0, "Swap layouts between 2 files.\n"
614          "usage: swap_layouts <path1> <path2>"},
615         {"migrate", lfs_setstripe_migrate, 0,
616          "migrate a directory between MDTs.\n"
617          "usage: migrate [--mdt-count|-c] <stripe_count>\n"
618          "               [--mdt-hash|-H] <hash_type>\n"
619          "               [--mdt-index|-m] <start_mdt_index>\n"
620          "               [--verbose|-v]\n"
621          "               <directory>\n"
622          "\tmdt:        MDTs to stripe over, if only one MDT is specified\n"
623          "                      it's the MDT index of first stripe\n"
624          "\tmdt_count:  number of MDTs to stripe a directory over\n"
625          "\tmdt_hash:   hash type of the striped directory. mdt types:\n"
626          "                      fnv_1a_64 FNV-1a hash algorithm (default)\n"
627          "                      all_char  sum of characters % MDT_COUNT\n"
628          "\n"
629          "migrate file objects from one OST "
630          "layout\nto another (may be not safe with concurent writes).\n"
631          "usage: migrate  "
632          "[--stripe-count|-c] <stripe_count>\n"
633          "[--overstripe-count|-C] <stripe_count>\n"
634          "              [--stripe-index|-i] <start_ost_index>\n"
635          "              [--stripe-size|-S] <stripe_size>\n"
636          "              [--pool|-p] <pool_name>\n"
637          "              [--ost|-o] <ost_indices>\n"
638          "              [--block|-b]\n"
639          "              [--non-block|-n]\n"
640          "              [--non-direct|-D]\n"
641          "              <file|directory>\n"
642          "\tstripe_count:     number of OSTs to stripe a file over\n"
643          "\t              Using -C instead of -c allows overstriping, which\n"
644          "\t              will place more than one stripe per OST if\n"
645          "\t              stripe_count is greater than the number of OSTs\n"
646          "\tstripe_ost_index: index of the first OST to stripe a file over\n"
647          "\tstripe_size:      number of bytes to store before moving to the next OST\n"
648          "\tpool_name:        name of the predefined pool of OSTs\n"
649          "\tost_indices:      OSTs to stripe over, in order\n"
650          "\tblock:        Block file access during data migration (default)\n"
651          "\tnon-block:    Abort migrations if concurrent access is detected\n"
652          "\tnon-direct:       do not use direct I/O to copy file contents.\n"},
653         {"mv", lfs_mv, 0,
654          "To move directories between MDTs. This command is deprecated, "
655          "use \"migrate\" instead.\n"
656          "usage: mv <directory|filename> [--mdt-index|-m] <mdt_index> "
657          "[--verbose|-v]\n"},
658         {"ladvise", lfs_ladvise, 0,
659          "Provide servers with advice about access patterns for a file.\n"
660          "usage: ladvise [--advice|-a ADVICE] [--start|-s START[kMGT]]\n"
661          "               [--background|-b] [--unset|-u]\n\n"
662          "               {[--end|-e END[kMGT]] | [--length|-l LENGTH[kMGT]]}\n"
663          "               {[--mode|-m [READ,WRITE]}\n"
664          "               <file> ...\n"},
665         {"mirror", lfs_mirror, mirror_cmdlist,
666          "lfs commands used to manage files with mirrored components:\n"
667          "lfs mirror create - create a mirrored file or directory\n"
668          "lfs mirror extend - add mirror(s) to an existing file\n"
669          "lfs mirror split  - split a mirror from an existing mirrored file\n"
670          "lfs mirror resync - resynchronize out-of-sync mirrored file(s)\n"
671          "lfs mirror read   - read a mirror content of a mirrored file\n"
672          "lfs mirror write  - write to a mirror of a mirrored file\n"
673          "lfs mirror copy   - copy a mirror to other mirror(s) of a file\n"
674          "lfs mirror verify - verify mirrored file(s)\n"},
675         {"getsom", lfs_getsom, 0, "To list the SOM info for a given file.\n"
676          "usage: getsom [-s] [-b] [-f] <path>\n"
677          "\t-s: Only show the size value of the SOM data for a given file\n"
678          "\t-b: Only show the blocks value of the SOM data for a given file\n"
679          "\t-f: Only show the flags value of the SOM data for a given file\n"},
680         {"heat_get", lfs_heat_get, 0,
681          "To get heat of files.\n"
682          "usage: heat_get <file> ...\n"},
683         {"heat_set", lfs_heat_set, 0,
684          "To set heat flags of files.\n"
685          "usage: heat_set [--clear|-c] [--off|-o] [--on|-O] <file> ...\n"
686          "\t--clear|-c: Clear file heat for given files\n"
687          "\t--off|-o:   Turn off file heat for given files\n"
688          "\t--on|-O:    Turn on file heat for given files\n"},
689         {"pcc", lfs_pcc, pcc_cmdlist,
690          "lfs commands used to interact with PCC features:\n"
691          "lfs pcc attach - attach given files to Persistent Client Cache\n"
692          "lfs pcc attach_fid - attach given files into PCC by FID(s)\n"
693          "lfs pcc state  - display the PCC state for given files\n"
694          "lfs pcc detach - detach given files from Persistent Client Cache\n"
695          "lfs pcc detach_fid - detach given files from PCC by FID(s)\n"},
696         {"help", Parser_help, 0, "help"},
697         {"exit", Parser_quit, 0, "quit"},
698         {"quit", Parser_quit, 0, "quit"},
699         {"--version", Parser_version, 0,
700          "output build version of the utility and exit"},
701         {"--list-commands", lfs_list_commands, 0,
702          "list commands supported by the utility and exit"},
703         { 0, 0, 0, NULL }
704 };
705
706
707 static int check_hashtype(const char *hashtype)
708 {
709         int i;
710
711         for (i = LMV_HASH_TYPE_ALL_CHARS; i < LMV_HASH_TYPE_MAX; i++)
712                 if (strcmp(hashtype, mdt_hash_name[i]) == 0)
713                         return i;
714
715         return 0;
716 }
717
718 static uint32_t check_foreign_type_name(const char *foreign_type_name)
719 {
720         uint32_t i;
721
722         for (i = 0; i < LU_FOREIGN_TYPE_UNKNOWN; i++) {
723                 if (lu_foreign_types[i].lft_name == NULL)
724                         break;
725                 if (strcmp(foreign_type_name,
726                            lu_foreign_types[i].lft_name) == 0)
727                         return lu_foreign_types[i].lft_type;
728         }
729
730         return LU_FOREIGN_TYPE_UNKNOWN;
731 }
732
733 static const char *error_loc = "syserror";
734
735 enum {
736         MIGRATION_NONBLOCK      = 0x0001,
737         MIGRATION_MIRROR        = 0x0002,
738         MIGRATION_NONDIRECT     = 0x0004,
739         MIGRATION_VERBOSE       = 0x0008,
740 };
741
742 static int lfs_component_create(char *fname, int open_flags, mode_t open_mode,
743                                 struct llapi_layout *layout);
744
745 static int
746 migrate_open_files(const char *name, __u64 migration_flags,
747                    const struct llapi_stripe_param *param,
748                    struct llapi_layout *layout, int *fd_src, int *fd_tgt)
749 {
750         int                      fd = -1;
751         int                      fdv = -1;
752         int                      rflags;
753         int                      mdt_index;
754         int                      random_value;
755         char                     parent[PATH_MAX];
756         char                     volatile_file[PATH_MAX];
757         char                    *ptr;
758         int                      rc;
759         struct stat              st;
760         struct stat              stv;
761
762         if (param == NULL && layout == NULL) {
763                 error_loc = "layout information";
764                 return -EINVAL;
765         }
766
767         /* search for file directory pathname */
768         if (strlen(name) > sizeof(parent) - 1) {
769                 error_loc = "source file name";
770                 return -ERANGE;
771         }
772
773         strncpy(parent, name, sizeof(parent));
774         ptr = strrchr(parent, '/');
775         if (ptr == NULL) {
776                 if (getcwd(parent, sizeof(parent)) == NULL) {
777                         error_loc = "getcwd";
778                         return -errno;
779                 }
780         } else {
781                 if (ptr == parent) /* leading '/' */
782                         ptr = parent + 1;
783                 *ptr = '\0';
784         }
785
786         /* open file, direct io */
787         /* even if the file is only read, WR mode is nedeed to allow
788          * layout swap on fd */
789         rflags = O_RDWR;
790         if (!(migration_flags & MIGRATION_NONDIRECT))
791                 rflags |= O_DIRECT;
792         fd = open(name, rflags);
793         if (fd < 0) {
794                 rc = -errno;
795                 error_loc = "cannot open source file";
796                 return rc;
797         }
798
799         rc = llapi_file_fget_mdtidx(fd, &mdt_index);
800         if (rc < 0) {
801                 error_loc = "cannot get MDT index";
802                 goto out;
803         }
804
805         do {
806                 int open_flags = O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW;
807                 mode_t open_mode = S_IRUSR | S_IWUSR;
808
809                 random_value = random();
810                 rc = snprintf(volatile_file, sizeof(volatile_file),
811                               "%s/%s:%.4X:%.4X", parent, LUSTRE_VOLATILE_HDR,
812                               mdt_index, random_value);
813                 if (rc >= sizeof(volatile_file)) {
814                         rc = -ENAMETOOLONG;
815                         break;
816                 }
817
818                 /* create, open a volatile file, use caching (ie no directio) */
819                 if (param != NULL)
820                         fdv = llapi_file_open_param(volatile_file, open_flags,
821                                                     open_mode, param);
822                 else
823                         fdv = lfs_component_create(volatile_file, open_flags,
824                                                    open_mode, layout);
825         } while (fdv < 0 && (rc = fdv) == -EEXIST);
826
827         if (rc < 0) {
828                 error_loc = "cannot create volatile file";
829                 goto out;
830         }
831
832         /* In case the MDT does not support creation of volatile files
833          * we should try to unlink it. */
834         (void)unlink(volatile_file);
835
836         /* Not-owner (root?) special case.
837          * Need to set owner/group of volatile file like original.
838          * This will allow to pass related check during layout_swap.
839          */
840         rc = fstat(fd, &st);
841         if (rc != 0) {
842                 rc = -errno;
843                 error_loc = "cannot stat source file";
844                 goto out;
845         }
846
847         rc = fstat(fdv, &stv);
848         if (rc != 0) {
849                 rc = -errno;
850                 error_loc = "cannot stat volatile";
851                 goto out;
852         }
853
854         if (st.st_uid != stv.st_uid || st.st_gid != stv.st_gid) {
855                 rc = fchown(fdv, st.st_uid, st.st_gid);
856                 if (rc != 0) {
857                         rc = -errno;
858                         error_loc = "cannot change ownwership of volatile";
859                         goto out;
860                 }
861         }
862
863 out:
864         if (rc < 0) {
865                 if (fd > 0)
866                         close(fd);
867                 if (fdv > 0)
868                         close(fdv);
869         } else {
870                 *fd_src = fd;
871                 *fd_tgt = fdv;
872                 error_loc = NULL;
873         }
874         return rc;
875 }
876
877 static int migrate_copy_data(int fd_src, int fd_dst, int (*check_file)(int))
878 {
879         struct llapi_layout *layout;
880         size_t   buf_size = 4 * 1024 * 1024;
881         void    *buf = NULL;
882         ssize_t  rsize = -1;
883         ssize_t  wsize = 0;
884         size_t   rpos = 0;
885         size_t   wpos = 0;
886         off_t    bufoff = 0;
887         int      rc;
888
889         layout = llapi_layout_get_by_fd(fd_src, 0);
890         if (layout != NULL) {
891                 uint64_t stripe_size;
892
893                 rc = llapi_layout_stripe_size_get(layout, &stripe_size);
894                 if (rc == 0)
895                         buf_size = stripe_size;
896
897                 llapi_layout_free(layout);
898         }
899
900         /* Use a page-aligned buffer for direct I/O */
901         rc = posix_memalign(&buf, getpagesize(), buf_size);
902         if (rc != 0)
903                 return -rc;
904
905         while (1) {
906                 /* read new data only if we have written all
907                  * previously read data */
908                 if (wpos == rpos) {
909                         if (check_file) {
910                                 rc = check_file(fd_src);
911                                 if (rc < 0)
912                                         break;
913                         }
914
915                         rsize = read(fd_src, buf, buf_size);
916                         if (rsize < 0) {
917                                 rc = -errno;
918                                 break;
919                         }
920                         rpos += rsize;
921                         bufoff = 0;
922                 }
923                 /* eof ? */
924                 if (rsize == 0)
925                         break;
926
927                 wsize = write(fd_dst, buf + bufoff, rpos - wpos);
928                 if (wsize < 0) {
929                         rc = -errno;
930                         break;
931                 }
932                 wpos += wsize;
933                 bufoff += wsize;
934         }
935
936         if (rc == 0) {
937                 rc = fsync(fd_dst);
938                 if (rc < 0)
939                         rc = -errno;
940         }
941
942         free(buf);
943         return rc;
944 }
945
946 static int migrate_copy_timestamps(int fd, int fdv)
947 {
948         struct stat st;
949
950         if (fstat(fd, &st) == 0) {
951                 struct timeval tv[2] = {
952                         {.tv_sec = st.st_atime},
953                         {.tv_sec = st.st_mtime}
954                 };
955
956                 return futimes(fdv, tv);
957         }
958
959         return -errno;
960 }
961
962 static int migrate_block(int fd, int fdv)
963 {
964         __u64   dv1;
965         int     gid;
966         int     rc;
967         int     rc2;
968
969         rc = llapi_get_data_version(fd, &dv1, LL_DV_RD_FLUSH);
970         if (rc < 0) {
971                 error_loc = "cannot get dataversion";
972                 return rc;
973         }
974
975         do
976                 gid = random();
977         while (gid == 0);
978
979         /* The grouplock blocks all concurrent accesses to the file.
980          * It has to be taken after llapi_get_data_version as it would
981          * block it too. */
982         rc = llapi_group_lock(fd, gid);
983         if (rc < 0) {
984                 error_loc = "cannot get group lock";
985                 return rc;
986         }
987
988         rc = migrate_copy_data(fd, fdv, NULL);
989         if (rc < 0) {
990                 error_loc = "data copy failed";
991                 goto out_unlock;
992         }
993
994         /* Make sure we keep original atime/mtime values */
995         rc = migrate_copy_timestamps(fd, fdv);
996         if (rc < 0) {
997                 error_loc = "timestamp copy failed";
998                 goto out_unlock;
999         }
1000
1001         /* swap layouts
1002          * for a migration we need to check data version on file did
1003          * not change.
1004          *
1005          * Pass in gid=0 since we already own grouplock. */
1006         rc = llapi_fswap_layouts_grouplock(fd, fdv, dv1, 0, 0,
1007                                            SWAP_LAYOUTS_CHECK_DV1);
1008         if (rc == -EAGAIN) {
1009                 error_loc = "file changed";
1010                 goto out_unlock;
1011         } else if (rc < 0) {
1012                 error_loc = "cannot swap layout";
1013                 goto out_unlock;
1014         }
1015
1016 out_unlock:
1017         rc2 = llapi_group_unlock(fd, gid);
1018         if (rc2 < 0 && rc == 0) {
1019                 error_loc = "unlock group lock";
1020                 rc = rc2;
1021         }
1022
1023         return rc;
1024 }
1025
1026 /**
1027  * Internal helper for migrate_copy_data(). Check lease and report error if
1028  * need be.
1029  *
1030  * \param[in]  fd           File descriptor on which to check the lease.
1031  *
1032  * \retval 0       Migration can keep on going.
1033  * \retval -errno  Error occurred, abort migration.
1034  */
1035 static int check_lease(int fd)
1036 {
1037         int rc;
1038
1039         rc = llapi_lease_check(fd);
1040         if (rc > 0)
1041                 return 0; /* llapi_check_lease returns > 0 on success. */
1042
1043         return -EBUSY;
1044 }
1045
1046 static int migrate_nonblock(int fd, int fdv)
1047 {
1048         __u64   dv1;
1049         __u64   dv2;
1050         int     rc;
1051
1052         rc = llapi_get_data_version(fd, &dv1, LL_DV_RD_FLUSH);
1053         if (rc < 0) {
1054                 error_loc = "cannot get data version";
1055                 return rc;
1056         }
1057
1058         rc = migrate_copy_data(fd, fdv, check_lease);
1059         if (rc < 0) {
1060                 error_loc = "data copy failed";
1061                 return rc;
1062         }
1063
1064         rc = llapi_get_data_version(fd, &dv2, LL_DV_RD_FLUSH);
1065         if (rc != 0) {
1066                 error_loc = "cannot get data version";
1067                 return rc;
1068         }
1069
1070         if (dv1 != dv2) {
1071                 rc = -EAGAIN;
1072                 error_loc = "source file changed";
1073                 return rc;
1074         }
1075
1076         /* Make sure we keep original atime/mtime values */
1077         rc = migrate_copy_timestamps(fd, fdv);
1078         if (rc < 0) {
1079                 error_loc = "timestamp copy failed";
1080                 return rc;
1081         }
1082
1083         return 0;
1084 }
1085
1086 static int lfs_component_set(char *fname, int comp_id,
1087                              __u32 flags, __u32 neg_flags)
1088 {
1089         __u32 ids[2];
1090         __u32 flags_array[2];
1091         size_t count = 0;
1092         int rc;
1093
1094         if (flags) {
1095                 ids[count] = comp_id;
1096                 flags_array[count] = flags;
1097                 ++count;
1098         }
1099
1100         if (neg_flags) {
1101                 if (neg_flags & LCME_FL_STALE) {
1102                         fprintf(stderr, "%s: cannot clear 'stale' flags from "
1103                                 "component. Please use lfs-mirror-resync(1) "
1104                                 "instead\n", progname);
1105                         return -EINVAL;
1106                 }
1107
1108                 ids[count] = comp_id;
1109                 flags_array[count] = neg_flags | LCME_FL_NEG;
1110                 ++count;
1111         }
1112
1113         rc = llapi_layout_file_comp_set(fname, ids, flags_array, count);
1114         if (rc) {
1115                 if (errno == EUCLEAN) {
1116                         rc = -errno;
1117                         fprintf(stderr,
1118                                 "%s: cannot set 'stale' flag on component '%#x' of the last non-stale mirror of '%s'\n",
1119                                 progname, comp_id, fname);
1120                 } else {
1121                         fprintf(stderr,
1122                                 "%s: cannot change the flags of component '%#x' of file '%s': %x / ^(%x)\n",
1123                                 progname, comp_id, fname, flags, neg_flags);
1124                 }
1125         }
1126
1127         return rc;
1128 }
1129
1130 static int lfs_component_del(char *fname, __u32 comp_id,
1131                              __u32 flags, __u32 neg_flags)
1132 {
1133         int     rc = 0;
1134
1135         if (flags && neg_flags)
1136                 return -EINVAL;
1137
1138         if (!flags && neg_flags)
1139                 flags = neg_flags | LCME_FL_NEG;
1140
1141         if ((flags && comp_id) || (!flags && !comp_id))
1142                 return -EINVAL;
1143
1144         if (flags) {
1145                 if (flags & ~LCME_KNOWN_FLAGS) {
1146                         fprintf(stderr,
1147                                 "%s setstripe: unknown flags %#x\n",
1148                                 progname, flags);
1149                         return -EINVAL;
1150                 }
1151         } else if (comp_id > LCME_ID_MAX) {
1152                 fprintf(stderr, "%s setstripe: invalid component id %u\n",
1153                         progname, comp_id);
1154                 return -EINVAL;
1155         }
1156
1157         rc = llapi_layout_file_comp_del(fname, comp_id, flags);
1158         if (rc)
1159                 fprintf(stderr,
1160                         "%s setstripe: cannot delete component %#x from '%s': %s\n",
1161                         progname, comp_id, fname, strerror(errno));
1162         return rc;
1163 }
1164
1165 static int lfs_component_add(char *fname, struct llapi_layout *layout)
1166 {
1167         int     rc;
1168
1169         if (layout == NULL)
1170                 return -EINVAL;
1171
1172         rc = llapi_layout_file_comp_add(fname, layout);
1173         if (rc)
1174                 fprintf(stderr, "Add layout component(s) to %s failed. %s\n",
1175                         fname, strerror(errno));
1176         return rc;
1177 }
1178
1179 static int lfs_component_create(char *fname, int open_flags, mode_t open_mode,
1180                                 struct llapi_layout *layout)
1181 {
1182         struct stat     st;
1183         int     fd;
1184
1185         if (layout == NULL)
1186                 return -EINVAL;
1187
1188         fd = lstat(fname, &st);
1189         if (fd == 0 && S_ISDIR(st.st_mode))
1190                 open_flags = O_DIRECTORY | O_RDONLY;
1191
1192         fd = llapi_layout_file_open(fname, open_flags, open_mode, layout);
1193         if (fd < 0)
1194                 fprintf(stderr, "%s: cannot %s '%s': %s\n", progname,
1195                         S_ISDIR(st.st_mode) ?
1196                                 "set default composite layout for" :
1197                                 "create composite file",
1198                         fname, strerror(errno));
1199         return fd;
1200 }
1201
1202 static int lfs_migrate(char *name, __u64 migration_flags,
1203                        struct llapi_stripe_param *param,
1204                        struct llapi_layout *layout)
1205 {
1206         struct llapi_layout *existing;
1207         uint64_t dom_new, dom_cur;
1208         int fd = -1;
1209         int fdv = -1;
1210         int rc;
1211
1212         rc = migrate_open_files(name, migration_flags, param, layout,
1213                                 &fd, &fdv);
1214         if (rc < 0)
1215                 goto out;
1216
1217         rc = llapi_layout_dom_size(layout, &dom_new);
1218         if (rc) {
1219                 error_loc = "cannot get new layout DoM size";
1220                 goto out;
1221         }
1222         /* special case for migration to DOM layout*/
1223         existing = llapi_layout_get_by_fd(fd, 0);
1224         if (!existing) {
1225                 error_loc = "cannot get existing layout";
1226                 goto out;
1227         }
1228
1229         rc = llapi_layout_dom_size(existing, &dom_cur);
1230         if (rc) {
1231                 error_loc = "cannot get current layout DoM size";
1232                 goto out;
1233         }
1234
1235         /* if file has DoM layout already then migration is possible to
1236          * the new layout with the same DoM component via swap layout,
1237          * if new layout used bigger DOM size, then mirroring is used
1238          */
1239         if (dom_new > dom_cur) {
1240                 rc = lfs_migrate_to_dom(fd, fdv, name, migration_flags, param,
1241                                         layout);
1242                 if (rc)
1243                         error_loc = "cannot migrate to DOM layout";
1244                 goto out_closed;
1245         }
1246
1247         if (!(migration_flags & MIGRATION_NONBLOCK)) {
1248                 /* Blocking mode (forced if servers do not support file lease).
1249                  * It is also the default mode, since we cannot distinguish
1250                  * between a broken lease and a server that does not support
1251                  * atomic swap/close (LU-6785) */
1252                 rc = migrate_block(fd, fdv);
1253                 goto out;
1254         }
1255
1256         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
1257         if (rc < 0) {
1258                 error_loc = "cannot get lease";
1259                 goto out;
1260         }
1261
1262         rc = migrate_nonblock(fd, fdv);
1263         if (rc < 0) {
1264                 llapi_lease_release(fd);
1265                 goto out;
1266         }
1267
1268         /* Atomically put lease, swap layouts and close.
1269          * for a migration we need to check data version on file did
1270          * not change. */
1271         rc = llapi_fswap_layouts(fd, fdv, 0, 0, SWAP_LAYOUTS_CLOSE);
1272         if (rc < 0) {
1273                 error_loc = "cannot swap layout";
1274                 goto out;
1275         }
1276
1277 out:
1278         if (fd >= 0)
1279                 close(fd);
1280
1281         if (fdv >= 0)
1282                 close(fdv);
1283 out_closed:
1284         if (rc < 0)
1285                 fprintf(stderr, "error: %s: %s: %s: %s\n",
1286                         progname, name, error_loc, strerror(-rc));
1287         else if (migration_flags & MIGRATION_VERBOSE)
1288                 printf("%s\n", name);
1289
1290         return rc;
1291 }
1292
1293 static int comp_str2flags(char *string, __u32 *flags, __u32 *neg_flags)
1294 {
1295         char *name;
1296
1297         if (string == NULL)
1298                 return -EINVAL;
1299
1300         *flags = 0;
1301         *neg_flags = 0;
1302         for (name = strtok(string, ","); name; name = strtok(NULL, ",")) {
1303                 bool found = false;
1304                 int i;
1305
1306                 for (i = 0; i < ARRAY_SIZE(comp_flags_table); i++) {
1307                         __u32 comp_flag = comp_flags_table[i].cfn_flag;
1308                         const char *comp_name = comp_flags_table[i].cfn_name;
1309
1310                         if (strcmp(name, comp_name) == 0) {
1311                                 *flags |= comp_flag;
1312                                 found = true;
1313                         } else if (strncmp(name, "^", 1) == 0 &&
1314                                    strcmp(name + 1, comp_name) == 0) {
1315                                 *neg_flags |= comp_flag;
1316                                 found = true;
1317                         }
1318                 }
1319                 if (!found) {
1320                         llapi_printf(LLAPI_MSG_ERROR,
1321                                      "%s: component flag '%s' not supported\n",
1322                                      progname, name);
1323                         return -EINVAL;
1324                 }
1325         }
1326
1327         if (!*flags && !*neg_flags)
1328                 return -EINVAL;
1329
1330         /* don't allow to set and exclude the same flag */
1331         if (*flags & *neg_flags)
1332                 return -EINVAL;
1333
1334         return 0;
1335 }
1336
1337 static int mirror_str2state(char *string, __u16 *state, __u16 *neg_state)
1338 {
1339         if (string == NULL)
1340                 return -EINVAL;
1341
1342         *state = 0;
1343         *neg_state = 0;
1344
1345         if (strncmp(string, "^", 1) == 0) {
1346                 *neg_state = llapi_layout_string_flags(string + 1);
1347                 if (*neg_state != 0)
1348                         return 0;
1349         } else {
1350                 *state = llapi_layout_string_flags(string);
1351                 if (*state != 0)
1352                         return 0;
1353         }
1354
1355         llapi_printf(LLAPI_MSG_ERROR,
1356                      "%s: mirrored file state '%s' not supported\n",
1357                      progname, string);
1358         return -EINVAL;
1359 }
1360
1361 /**
1362  * struct mirror_args - Command-line arguments for mirror(s).
1363  * @m_count:  Number of mirrors to be created with this layout.
1364  * @m_flags:  Mirror level flags, only 'prefer' is supported.
1365  * @m_layout: Mirror layout.
1366  * @m_file:   A victim file. Its layout will be split and used as a mirror.
1367  * @m_next:   Point to the next node of the list.
1368  *
1369  * Command-line arguments for mirror(s) will be parsed and stored in
1370  * a linked list that consists of this structure.
1371  */
1372 struct mirror_args {
1373         __u32                   m_count;
1374         __u32                   m_flags;
1375         struct llapi_layout     *m_layout;
1376         const char              *m_file;
1377         struct mirror_args      *m_next;
1378 };
1379
1380 /**
1381  * enum mirror_flags - Flags for extending a mirrored file.
1382  * @MF_NO_VERIFY: Indicates not to verify the mirror(s) from victim file(s)
1383  *             in case the victim file(s) contains the same data as the
1384  *             original mirrored file.
1385  * @MF_DESTROY: Indicates to delete the mirror from the mirrored file.
1386  * @MF_COMP_ID: specified component id instead of mirror id
1387  *
1388  * Flags for extending a mirrored file.
1389  */
1390 enum mirror_flags {
1391         MF_NO_VERIFY    = 0x1,
1392         MF_DESTROY      = 0x2,
1393         MF_COMP_ID      = 0x4,
1394         MF_COMP_POOL    = 0x8,
1395 };
1396
1397 /**
1398  * mirror_create_sanity_check() - Check mirror list.
1399  * @list:  A linked list that stores the mirror arguments.
1400  *
1401  * This function does a sanity check on @list for creating
1402  * a mirrored file.
1403  *
1404  * Return: 0 on success or a negative error code on failure.
1405  */
1406 static int mirror_create_sanity_check(const char *fname,
1407                                       struct mirror_args *list)
1408 {
1409         int rc = 0;
1410         bool has_m_file = false;
1411         bool has_m_layout = false;
1412
1413         if (list == NULL)
1414                 return -EINVAL;
1415
1416         if (fname) {
1417                 struct llapi_layout *layout;
1418
1419                 layout = llapi_layout_get_by_path(fname, 0);
1420                 if (!layout) {
1421                         fprintf(stderr,
1422                                 "error: %s: file '%s' couldn't get layout\n",
1423                                 progname, fname);
1424                         return -ENODATA;
1425                 }
1426
1427                 rc = llapi_layout_sanity(layout, false, true);
1428
1429                 llapi_layout_free(layout);
1430
1431                 if (rc) {
1432                         llapi_layout_sanity_perror(rc);
1433                         return rc;
1434                 }
1435         }
1436
1437         while (list != NULL) {
1438                 if (list->m_file != NULL) {
1439                         has_m_file = true;
1440                         llapi_layout_free(list->m_layout);
1441
1442                         list->m_layout =
1443                                 llapi_layout_get_by_path(list->m_file, 0);
1444                         if (list->m_layout == NULL) {
1445                                 fprintf(stderr,
1446                                         "error: %s: file '%s' has no layout\n",
1447                                         progname, list->m_file);
1448                                 return -ENODATA;
1449                         }
1450                 } else {
1451                         has_m_layout = true;
1452                         if (list->m_layout == NULL) {
1453                                 fprintf(stderr, "error: %s: no mirror layout\n",
1454                                         progname);
1455                                 return -EINVAL;
1456                         }
1457                 }
1458
1459                 rc = llapi_layout_sanity(list->m_layout, false, true);
1460                 if (rc) {
1461                         llapi_layout_sanity_perror(rc);
1462                         return rc;
1463                 }
1464
1465                 list = list->m_next;
1466         }
1467
1468         if (has_m_file && has_m_layout) {
1469                 fprintf(stderr,
1470                         "error: %s: -f <victim_file> option should not be specified with setstripe options\n",
1471                         progname);
1472                 return -EINVAL;
1473         }
1474
1475         return 0;
1476 }
1477
1478 static int mirror_set_flags(struct llapi_layout *layout, void *cbdata)
1479 {
1480         __u32 mirror_flags = *(__u32 *)cbdata;
1481         uint32_t flags;
1482         int rc;
1483
1484         rc = llapi_layout_comp_flags_get(layout, &flags);
1485         if (rc < 0)
1486                 return rc;
1487
1488         if (!flags) {
1489                 rc = llapi_layout_comp_flags_set(layout, mirror_flags);
1490                 if (rc)
1491                         return rc;
1492         }
1493
1494         return LLAPI_LAYOUT_ITER_CONT;
1495 }
1496
1497 /**
1498  * mirror_create() - Create a mirrored file.
1499  * @fname:        The file to be created.
1500  * @mirror_list:  A linked list that stores the mirror arguments.
1501  *
1502  * This function creates a mirrored file @fname with the mirror(s)
1503  * from @mirror_list.
1504  *
1505  * Return: 0 on success or a negative error code on failure.
1506  */
1507 static int mirror_create(char *fname, struct mirror_args *mirror_list)
1508 {
1509         struct llapi_layout *layout = NULL;
1510         struct mirror_args *cur_mirror = NULL;
1511         uint16_t mirror_count = 0;
1512         int i = 0;
1513         int rc = 0;
1514
1515         rc = mirror_create_sanity_check(NULL, mirror_list);
1516         if (rc)
1517                 return rc;
1518
1519         cur_mirror = mirror_list;
1520         while (cur_mirror != NULL) {
1521                 rc = llapi_layout_comp_iterate(cur_mirror->m_layout,
1522                                                mirror_set_flags,
1523                                                &cur_mirror->m_flags);
1524                 if (rc) {
1525                         rc = -errno;
1526                         fprintf(stderr, "%s: failed to set mirror flags\n",
1527                                 progname);
1528                         goto error;
1529                 }
1530
1531                 for (i = 0; i < cur_mirror->m_count; i++) {
1532                         rc = llapi_layout_merge(&layout, cur_mirror->m_layout);
1533                         if (rc) {
1534                                 rc = -errno;
1535                                 fprintf(stderr, "error: %s: "
1536                                         "merge layout failed: %s\n",
1537                                         progname, strerror(errno));
1538                                 goto error;
1539                         }
1540                 }
1541                 mirror_count += cur_mirror->m_count;
1542                 cur_mirror = cur_mirror->m_next;
1543         }
1544
1545         if (layout == NULL) {
1546                 fprintf(stderr, "error: %s: layout is NULL\n", progname);
1547                 return -EINVAL;
1548         }
1549
1550         rc = llapi_layout_mirror_count_set(layout, mirror_count);
1551         if (rc) {
1552                 rc = -errno;
1553                 fprintf(stderr, "error: %s: set mirror count failed: %s\n",
1554                         progname, strerror(errno));
1555                 goto error;
1556         }
1557
1558         rc = lfs_component_create(fname, O_CREAT | O_WRONLY, 0666,
1559                                   layout);
1560         if (rc >= 0) {
1561                 close(rc);
1562                 rc = 0;
1563         }
1564
1565 error:
1566         llapi_layout_free(layout);
1567         return rc;
1568 }
1569
1570 /**
1571  * Compare files and check lease on @fd.
1572  *
1573  * \retval bytes number of bytes are the same
1574  */
1575 static ssize_t mirror_file_compare(int fd, int fdv)
1576 {
1577         const size_t buflen = 4 * 1024 * 1024; /* 4M */
1578         void *buf;
1579         ssize_t bytes_done = 0;
1580         ssize_t bytes_read = 0;
1581
1582         buf = malloc(buflen * 2);
1583         if (!buf)
1584                 return -ENOMEM;
1585
1586         while (1) {
1587                 if (!llapi_lease_check(fd)) {
1588                         bytes_done = -EBUSY;
1589                         break;
1590                 }
1591
1592                 bytes_read = read(fd, buf, buflen);
1593                 if (bytes_read <= 0)
1594                         break;
1595
1596                 if (bytes_read != read(fdv, buf + buflen, buflen))
1597                         break;
1598
1599                 /* XXX: should compute the checksum on each buffer and then
1600                  * compare checksum to avoid cache collision */
1601                 if (memcmp(buf, buf + buflen, bytes_read))
1602                         break;
1603
1604                 bytes_done += bytes_read;
1605         }
1606
1607         free(buf);
1608
1609         return bytes_done;
1610 }
1611
1612 static int mirror_extend_file(const char *fname, const char *victim_file,
1613                               enum mirror_flags mirror_flags)
1614 {
1615         int fd = -1;
1616         int fdv = -1;
1617         struct stat stbuf;
1618         struct stat stbuf_v;
1619         struct ll_ioc_lease *data = NULL;
1620         int rc;
1621
1622         fd = open(fname, O_RDWR);
1623         if (fd < 0) {
1624                 error_loc = "open source file";
1625                 rc = -errno;
1626                 goto out;
1627         }
1628
1629         fdv = open(victim_file, O_RDWR);
1630         if (fdv < 0) {
1631                 error_loc = "open target file";
1632                 rc = -errno;
1633                 goto out;
1634         }
1635
1636         if (fstat(fd, &stbuf) || fstat(fdv, &stbuf_v)) {
1637                 error_loc = "stat source or target file";
1638                 rc = -errno;
1639                 goto out;
1640         }
1641
1642         if (stbuf.st_dev != stbuf_v.st_dev) {
1643                 error_loc = "stat source and target file";
1644                 rc = -EXDEV;
1645                 goto out;
1646         }
1647
1648         /* mirrors should be of the same size */
1649         if (stbuf.st_size != stbuf_v.st_size) {
1650                 error_loc = "file sizes don't match";
1651                 rc = -EINVAL;
1652                 goto out;
1653         }
1654
1655         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
1656         if (rc < 0) {
1657                 error_loc = "cannot get lease";
1658                 goto out;
1659         }
1660
1661         if (!(mirror_flags & MF_NO_VERIFY)) {
1662                 ssize_t ret;
1663                 /* mirrors should have the same contents */
1664                 ret = mirror_file_compare(fd, fdv);
1665                 if (ret != stbuf.st_size) {
1666                         error_loc = "file busy or contents don't match";
1667                         rc = ret < 0 ? ret : -EINVAL;
1668                         goto out;
1669                 }
1670         }
1671
1672         /* Get rid of caching pages from clients */
1673         rc = llapi_file_flush(fd);
1674         if (rc < 0) {
1675                 error_loc = "cannot get data version";
1676                 goto out;
1677         }
1678
1679         rc = llapi_file_flush(fdv);
1680         if (rc < 0) {
1681                 error_loc = "cannot get data version";
1682                 goto out;
1683
1684         }
1685
1686         /* Make sure we keep original atime/mtime values */
1687         rc = migrate_copy_timestamps(fd, fdv);
1688         if (rc < 0) {
1689                 error_loc = "cannot copy timestamp";
1690                 goto out;
1691         }
1692
1693         /* Atomically put lease, merge layouts and close. */
1694         data = calloc(1, offsetof(typeof(*data), lil_ids[1]));
1695         if (!data) {
1696                 error_loc = "memory allocation";
1697                 goto out;
1698         }
1699         data->lil_mode = LL_LEASE_UNLCK;
1700         data->lil_flags = LL_LEASE_LAYOUT_MERGE;
1701         data->lil_count = 1;
1702         data->lil_ids[0] = fdv;
1703         rc = llapi_lease_set(fd, data);
1704         if (rc < 0) {
1705                 error_loc = "cannot merge layout";
1706                 goto out;
1707         } else if (rc == 0) {
1708                 rc = -EBUSY;
1709                 error_loc = "lost lease lock";
1710                 goto out;
1711         }
1712         rc = 0;
1713
1714 out:
1715         if (data)
1716                 free(data);
1717         if (fd >= 0)
1718                 close(fd);
1719         if (fdv >= 0)
1720                 close(fdv);
1721         if (!rc)
1722                 (void) unlink(victim_file);
1723         if (rc < 0)
1724                 fprintf(stderr, "error: %s: %s: %s: %s\n",
1725                         progname, fname, error_loc, strerror(-rc));
1726         return rc;
1727 }
1728
1729 static int mirror_extend_layout(char *name, struct llapi_layout *layout)
1730 {
1731         struct ll_ioc_lease *data = NULL;
1732         int fd = -1;
1733         int fdv = -1;
1734         int rc;
1735
1736         rc = migrate_open_files(name, 0, NULL, layout, &fd, &fdv);
1737         if (rc < 0)
1738                 goto out;
1739
1740         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
1741         if (rc < 0) {
1742                 error_loc = "cannot get lease";
1743                 goto out;
1744         }
1745
1746         rc = migrate_nonblock(fd, fdv);
1747         if (rc < 0) {
1748                 llapi_lease_release(fd);
1749                 goto out;
1750         }
1751
1752         /* Atomically put lease, merge layouts and close. */
1753         data = calloc(1, offsetof(typeof(*data), lil_ids[1]));
1754         if (!data) {
1755                 error_loc = "memory allocation";
1756                 goto out;
1757         }
1758         data->lil_mode = LL_LEASE_UNLCK;
1759         data->lil_flags = LL_LEASE_LAYOUT_MERGE;
1760         data->lil_count = 1;
1761         data->lil_ids[0] = fdv;
1762         rc = llapi_lease_set(fd, data);
1763         if (rc < 0) {
1764                 error_loc = "cannot merge layout";
1765                 goto out;
1766         } else if (rc == 0) {
1767                 rc = -EBUSY;
1768                 error_loc = "lost lease lock";
1769                 goto out;
1770         }
1771         rc = 0;
1772
1773 out:
1774         if (data)
1775                 free(data);
1776         if (fd >= 0)
1777                 close(fd);
1778         if (fdv >= 0)
1779                 close(fdv);
1780         if (rc < 0)
1781                 fprintf(stderr, "error: %s: %s: %s: %s\n",
1782                         progname, name, error_loc, strerror(-rc));
1783         return rc;
1784 }
1785
1786 static int mirror_extend(char *fname, struct mirror_args *mirror_list,
1787                          enum mirror_flags mirror_flags)
1788 {
1789         int rc;
1790
1791         rc = mirror_create_sanity_check(fname, mirror_list);
1792         if (rc)
1793                 return rc;
1794
1795         while (mirror_list) {
1796                 if (mirror_list->m_file != NULL) {
1797                         rc = mirror_extend_file(fname, mirror_list->m_file,
1798                                                 mirror_flags);
1799                 } else {
1800                         __u32 mirror_count = mirror_list->m_count;
1801
1802                         while (mirror_count > 0) {
1803                                 rc = mirror_extend_layout(fname,
1804                                                         mirror_list->m_layout);
1805                                 if (rc)
1806                                         break;
1807
1808                                 --mirror_count;
1809                         }
1810                 }
1811                 if (rc)
1812                         break;
1813
1814                 mirror_list = mirror_list->m_next;
1815         }
1816
1817         return rc;
1818 }
1819
1820 static int find_mirror_id(struct llapi_layout *layout, void *cbdata)
1821 {
1822         uint32_t id;
1823         int rc;
1824
1825         rc = llapi_layout_mirror_id_get(layout, &id);
1826         if (rc < 0)
1827                 return rc;
1828
1829         if ((__u16)id == *(__u16 *)cbdata)
1830                 return LLAPI_LAYOUT_ITER_STOP;
1831
1832         return LLAPI_LAYOUT_ITER_CONT;
1833 }
1834
1835 static int find_comp_id(struct llapi_layout *layout, void *cbdata)
1836 {
1837         uint32_t id;
1838         int rc;
1839
1840         rc = llapi_layout_comp_id_get(layout, &id);
1841         if (rc < 0)
1842                 return rc;
1843
1844         if (id == *(__u32 *)cbdata)
1845                 return LLAPI_LAYOUT_ITER_STOP;
1846
1847         return LLAPI_LAYOUT_ITER_CONT;
1848 }
1849
1850 struct pool_to_id_cbdata {
1851         const char *pool;
1852         __u32 id;
1853 };
1854 static int find_comp_id_by_pool(struct llapi_layout *layout, void *cbdata)
1855 {
1856         char buf[LOV_MAXPOOLNAME + 1];
1857         struct pool_to_id_cbdata *d = (void *)cbdata;
1858         uint32_t id;
1859         int rc;
1860
1861         rc = llapi_layout_pool_name_get(layout, buf, sizeof(buf));
1862         if (rc < 0)
1863                 return rc;
1864         if (strcmp(d->pool, buf))
1865                 return LLAPI_LAYOUT_ITER_CONT;
1866
1867         rc = llapi_layout_mirror_id_get(layout, &id);
1868         if (rc < 0)
1869                 return rc;
1870         d->id = id;
1871
1872         return LLAPI_LAYOUT_ITER_STOP;
1873 }
1874
1875 struct collect_ids_data {
1876         __u16   *cid_ids;
1877         int     cid_count;
1878         __u16   cid_exclude;
1879 };
1880
1881 static int collect_mirror_id(struct llapi_layout *layout, void *cbdata)
1882 {
1883         struct collect_ids_data *cid = cbdata;
1884         uint32_t id;
1885         int rc;
1886
1887         rc = llapi_layout_mirror_id_get(layout, &id);
1888         if (rc < 0)
1889                 return rc;
1890
1891         if ((__u16)id != cid->cid_exclude) {
1892                 int i;
1893
1894                 for (i = 0; i < cid->cid_count; i++) {
1895                         /* already collected the mirror id */
1896                         if (id == cid->cid_ids[i])
1897                                 return LLAPI_LAYOUT_ITER_CONT;
1898                 }
1899                 cid->cid_ids[cid->cid_count] = id;
1900                 cid->cid_count++;
1901         }
1902
1903         return LLAPI_LAYOUT_ITER_CONT;
1904 }
1905
1906 /**
1907  * last_non_stale_mirror() - Check if a mirror is the last non-stale mirror.
1908  * @mirror_id: Mirror id to be checked.
1909  * @layout:    Mirror component list.
1910  *
1911  * This function checks if a mirror with specified @mirror_id is the last
1912  * non-stale mirror of a layout @layout.
1913  *
1914  * Return: true or false.
1915  */
1916 static inline
1917 bool last_non_stale_mirror(__u16 mirror_id, struct llapi_layout *layout)
1918 {
1919         __u16 mirror_ids[128] = { 0 };
1920         struct collect_ids_data cid = { .cid_ids = mirror_ids,
1921                                         .cid_count = 0,
1922                                         .cid_exclude = mirror_id, };
1923         int i;
1924
1925         llapi_layout_comp_iterate(layout, collect_mirror_id, &cid);
1926
1927         for (i = 0; i < cid.cid_count; i++) {
1928                 struct llapi_resync_comp comp_array[1024] = { { 0 } };
1929                 int comp_size = 0;
1930
1931                 comp_size = llapi_mirror_find_stale(layout, comp_array,
1932                                                     ARRAY_SIZE(comp_array),
1933                                                     &mirror_ids[i], 1);
1934                 if (comp_size == 0)
1935                         return false;
1936         }
1937
1938         return true;
1939 }
1940
1941 static int mirror_split(const char *fname, __u32 id, const char *pool,
1942                         enum mirror_flags mflags, const char *victim_file)
1943 {
1944         struct llapi_layout *layout;
1945         char parent[PATH_MAX];
1946         char victim[PATH_MAX];
1947         int flags = O_CREAT | O_EXCL | O_LOV_DELAY_CREATE | O_NOFOLLOW;
1948         char *ptr;
1949         struct ll_ioc_lease *data;
1950         uint16_t mirror_count;
1951         int mdt_index;
1952         int fd, fdv;
1953         int rc;
1954
1955         /* check fname contains mirror with mirror_id/comp_id */
1956         layout = llapi_layout_get_by_path(fname, 0);
1957         if (!layout) {
1958                 fprintf(stderr,
1959                         "error %s: file '%s' couldn't get layout\n",
1960                         progname, fname);
1961                 return -EINVAL;
1962         }
1963
1964         rc = llapi_layout_sanity(layout, false, true);
1965         if (rc) {
1966                 llapi_layout_sanity_perror(rc);
1967                 goto free_layout;
1968         }
1969
1970         rc = llapi_layout_mirror_count_get(layout, &mirror_count);
1971         if (rc) {
1972                 fprintf(stderr,
1973                         "error %s: file '%s' couldn't get mirror count\n",
1974                         progname, fname);
1975                 goto free_layout;
1976         }
1977         if (mirror_count < 2) {
1978                 fprintf(stderr,
1979                         "error %s: file '%s' has %d component, cannot split\n",
1980                         progname, fname, mirror_count);
1981                 goto free_layout;
1982         }
1983
1984         if (mflags & MF_COMP_POOL) {
1985                 struct pool_to_id_cbdata data = { .pool = pool };
1986
1987                 rc = llapi_layout_comp_iterate(layout, find_comp_id_by_pool,
1988                                                &data);
1989                 id = data.id;
1990         } else if (mflags & MF_COMP_ID) {
1991                 rc = llapi_layout_comp_iterate(layout, find_comp_id, &id);
1992                 id = mirror_id_of(id);
1993         } else {
1994                 rc = llapi_layout_comp_iterate(layout, find_mirror_id, &id);
1995         }
1996         if (rc < 0) {
1997                 fprintf(stderr, "error %s: failed to iterate layout of '%s'\n",
1998                         progname, fname);
1999                 goto free_layout;
2000         } else if (rc == LLAPI_LAYOUT_ITER_CONT) {
2001                 fprintf(stderr,
2002                      "error %s: file '%s' does not contain mirror with id %u\n",
2003                         progname, fname, id);
2004                 goto free_layout;
2005         }
2006
2007         fd = open(fname, O_RDWR);
2008         if (fd < 0) {
2009                 fprintf(stderr,
2010                         "error %s: open file '%s' failed: %s\n",
2011                         progname, fname, strerror(errno));
2012                 goto free_layout;
2013         }
2014
2015         /* get victim file directory pathname */
2016         if (strlen(fname) > sizeof(parent) - 1) {
2017                 fprintf(stderr, "error %s: file name of '%s' too long\n",
2018                         progname, fname);
2019                 rc = -ERANGE;
2020                 goto close_fd;
2021         }
2022         strncpy(parent, fname, sizeof(parent));
2023         ptr = strrchr(parent, '/');
2024         if (ptr == NULL) {
2025                 if (getcwd(parent, sizeof(parent)) == NULL) {
2026                         fprintf(stderr, "error %s: getcwd failed: %s\n",
2027                                 progname, strerror(errno));
2028                         rc = -errno;
2029                         goto close_fd;
2030                 }
2031         } else {
2032                 if (ptr == parent)
2033                         ptr = parent + 1;
2034                 *ptr = '\0';
2035         }
2036
2037         rc = llapi_file_fget_mdtidx(fd, &mdt_index);
2038         if (rc < 0) {
2039                 fprintf(stderr, "%s: cannot get MDT index of '%s'\n",
2040                         progname, fname);
2041                 goto close_fd;
2042         }
2043
2044         if (victim_file == NULL) {
2045                 /* use a temp file to store the splitted layout */
2046                 if (mflags & MF_DESTROY) {
2047                         if (last_non_stale_mirror(id, layout)) {
2048                                 rc = -EUCLEAN;
2049                                 fprintf(stderr,
2050                                         "%s: cannot destroy the last non-stale mirror of file '%s'\n",
2051                                         progname, fname);
2052                                 goto close_fd;
2053                         }
2054
2055                         fdv = llapi_create_volatile_idx(parent, mdt_index,
2056                                                         O_LOV_DELAY_CREATE);
2057                 } else {
2058                         snprintf(victim, sizeof(victim), "%s.mirror~%u",
2059                                  fname, id);
2060                         fdv = open(victim, flags, S_IRUSR | S_IWUSR);
2061                 }
2062         } else {
2063                 /* user specified victim file */
2064                 fdv = open(victim_file, flags, S_IRUSR | S_IWUSR);
2065         }
2066
2067         if (fdv < 0) {
2068                 fprintf(stderr,
2069                         "error %s: create victim file failed: %s\n",
2070                         progname, strerror(errno));
2071                 goto close_fd;
2072         }
2073
2074         /* get lease lock of fname */
2075         rc = llapi_lease_acquire(fd, LL_LEASE_WRLCK);
2076         if (rc < 0) {
2077                 fprintf(stderr,
2078                         "error %s: cannot get lease of file '%s': %d\n",
2079                         progname, fname, rc);
2080                 goto close_victim;
2081         }
2082
2083         /* Atomatically put lease, split layouts and close. */
2084         data = malloc(offsetof(typeof(*data), lil_ids[2]));
2085         if (!data) {
2086                 rc = -ENOMEM;
2087                 goto close_victim;
2088         }
2089
2090         data->lil_mode = LL_LEASE_UNLCK;
2091         data->lil_flags = LL_LEASE_LAYOUT_SPLIT;
2092         data->lil_count = 2;
2093         data->lil_ids[0] = fdv;
2094         data->lil_ids[1] = id;
2095         rc = llapi_lease_set(fd, data);
2096         if (rc <= 0) {
2097                 if (rc == 0) /* lost lease lock */
2098                         rc = -EBUSY;
2099                 fprintf(stderr,
2100                         "error %s: cannot split '%s': %s\n",
2101                         progname, fname, strerror(-rc));
2102         } else {
2103                 rc = 0;
2104         }
2105         free(data);
2106
2107 close_victim:
2108         close(fdv);
2109 close_fd:
2110         close(fd);
2111 free_layout:
2112         llapi_layout_free(layout);
2113         return rc;
2114 }
2115
2116 static inline
2117 int lfs_mirror_resync_file(const char *fname, struct ll_ioc_lease *ioc,
2118                            __u16 *mirror_ids, int ids_nr);
2119
2120 static int lfs_migrate_to_dom(int fd, int fdv, char *name,
2121                               __u64 migration_flags,
2122                               struct llapi_stripe_param *param,
2123                               struct llapi_layout *layout)
2124 {
2125         struct ll_ioc_lease *data = NULL;
2126         int rc;
2127
2128         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
2129         if (rc < 0) {
2130                 error_loc = "cannot get lease";
2131                 goto out_close;
2132         }
2133
2134         /* Atomically put lease, merge layouts, resync and close. */
2135         data = calloc(1, offsetof(typeof(*data), lil_ids[1024]));
2136         if (!data) {
2137                 error_loc = "memory allocation";
2138                 goto out_close;
2139         }
2140         data->lil_mode = LL_LEASE_UNLCK;
2141         data->lil_flags = LL_LEASE_LAYOUT_MERGE;
2142         data->lil_count = 1;
2143         data->lil_ids[0] = fdv;
2144         rc = llapi_lease_set(fd, data);
2145         if (rc < 0) {
2146                 error_loc = "cannot merge layout";
2147                 goto out_close;
2148         } else if (rc == 0) {
2149                 rc = -EBUSY;
2150                 error_loc = "lost lease lock";
2151                 goto out_close;
2152         }
2153         close(fd);
2154         close(fdv);
2155
2156         rc = lfs_mirror_resync_file(name, data, NULL, 0);
2157         if (rc) {
2158                 error_loc = "cannot resync file";
2159                 goto out;
2160         }
2161
2162         /* delete first mirror now */
2163         rc = mirror_split(name, 1, NULL, MF_DESTROY, NULL);
2164         if (rc < 0)
2165                 error_loc = "cannot delete old layout";
2166         goto out;
2167
2168 out_close:
2169         close(fd);
2170         close(fdv);
2171 out:
2172         if (rc < 0)
2173                 fprintf(stderr, "error: %s: %s: %s: %s\n",
2174                         progname, name, error_loc, strerror(-rc));
2175         else if (migration_flags & MIGRATION_VERBOSE)
2176                 printf("%s\n", name);
2177         if (data)
2178                 free(data);
2179         return rc;
2180 }
2181
2182 /**
2183  * Parse a string containing an target index list into an array of integers.
2184  *
2185  * The input string contains a comma delimited list of individual
2186  * indices and ranges, for example "1,2-4,7". Add the indices into the
2187  * \a tgts array and remove duplicates.
2188  *
2189  * \param[out] tgts             array to store indices in
2190  * \param[in] size              size of \a tgts array
2191  * \param[in] offset            starting index in \a tgts
2192  * \param[in] arg               string containing OST index list
2193  * \param[in/out] overstriping  index list may contain duplicates
2194  *
2195  * \retval positive    number of indices in \a tgts
2196  * \retval -EINVAL     unable to parse \a arg
2197  */
2198 static int parse_targets(__u32 *tgts, int size, int offset, char *arg,
2199                          unsigned long long *pattern)
2200 {
2201         int rc;
2202         int nr = offset;
2203         int slots = size - offset;
2204         char *ptr = NULL;
2205         bool overstriped = false;
2206         bool end_of_loop;
2207
2208         if (arg == NULL)
2209                 return -EINVAL;
2210
2211         end_of_loop = false;
2212         while (!end_of_loop) {
2213                 int start_index = 0;
2214                 int end_index = 0;
2215                 int i;
2216                 char *endptr = NULL;
2217
2218                 rc = -EINVAL;
2219
2220                 ptr = strchrnul(arg, ',');
2221
2222                 end_of_loop = *ptr == '\0';
2223                 *ptr = '\0';
2224
2225                 start_index = strtol(arg, &endptr, 0);
2226                 if (endptr == arg) /* no data at all */
2227                         break;
2228                 if (*endptr != '-' && *endptr != '\0') /* has invalid data */
2229                         break;
2230
2231                 end_index = start_index;
2232                 if (*endptr == '-') {
2233                         end_index = strtol(endptr + 1, &endptr, 0);
2234                         if (*endptr != '\0')
2235                                 break;
2236                         if (end_index < start_index)
2237                                 break;
2238                 }
2239
2240                 for (i = start_index; i <= end_index && slots > 0; i++) {
2241                         int j;
2242
2243                         /* remove duplicate */
2244                         for (j = 0; j < offset; j++) {
2245                                 if (tgts[j] == i && pattern &&
2246                                     *pattern == LLAPI_LAYOUT_OVERSTRIPING)
2247                                         overstriped = true;
2248                                 else if (tgts[j] == i)
2249                                         return -EINVAL;
2250                         }
2251
2252                         j = offset;
2253
2254                         if (j == offset) { /* check complete */
2255                                 tgts[nr++] = i;
2256                                 --slots;
2257                         }
2258                 }
2259
2260                 if (slots == 0 && i < end_index)
2261                         break;
2262
2263                 *ptr = ',';
2264                 arg = ++ptr;
2265                 offset = nr;
2266                 rc = 0;
2267         }
2268         if (!end_of_loop && ptr != NULL)
2269                 *ptr = ',';
2270
2271         if (!overstriped && pattern)
2272                 *pattern = LLAPI_LAYOUT_DEFAULT;
2273
2274         return rc < 0 ? rc : nr;
2275 }
2276
2277 struct lfs_setstripe_args {
2278         unsigned long long       lsa_comp_end;
2279         unsigned long long       lsa_stripe_size;
2280         unsigned long long       lsa_extension_size;
2281         long long                lsa_stripe_count;
2282         long long                lsa_stripe_off;
2283         __u32                    lsa_comp_flags;
2284         __u32                    lsa_comp_neg_flags;
2285         unsigned long long       lsa_pattern;
2286         unsigned int             lsa_mirror_count;
2287         int                      lsa_nr_tgts;
2288         bool                     lsa_first_comp;
2289         bool                     lsa_extension_comp;
2290         __u32                   *lsa_tgts;
2291         char                    *lsa_pool_name;
2292 };
2293
2294 static inline void setstripe_args_init(struct lfs_setstripe_args *lsa)
2295 {
2296         unsigned int mirror_count = lsa->lsa_mirror_count;
2297         bool first_comp = lsa->lsa_first_comp;
2298
2299         memset(lsa, 0, sizeof(*lsa));
2300
2301         lsa->lsa_stripe_size = LLAPI_LAYOUT_DEFAULT;
2302         lsa->lsa_stripe_count = LLAPI_LAYOUT_DEFAULT;
2303         lsa->lsa_stripe_off = LLAPI_LAYOUT_DEFAULT;
2304         lsa->lsa_pattern = LLAPI_LAYOUT_RAID0;
2305         lsa->lsa_pool_name = NULL;
2306
2307         lsa->lsa_mirror_count = mirror_count;
2308         lsa->lsa_first_comp = first_comp;
2309 }
2310
2311 /**
2312  * setstripe_args_init_inherit() - Initialize and inherit stripe options.
2313  * @lsa: Stripe options to be initialized and inherited.
2314  *
2315  * This function initializes stripe options in @lsa and inherit
2316  * stripe_size, stripe_count and OST pool_name options.
2317  *
2318  * Return: void.
2319  */
2320 static inline void setstripe_args_init_inherit(struct lfs_setstripe_args *lsa)
2321 {
2322         unsigned long long stripe_size;
2323         long long stripe_count;
2324         char *pool_name = NULL;
2325
2326         stripe_size = lsa->lsa_stripe_size;
2327         stripe_count = lsa->lsa_stripe_count;
2328         pool_name = lsa->lsa_pool_name;
2329
2330         setstripe_args_init(lsa);
2331
2332         lsa->lsa_stripe_size = stripe_size;
2333         lsa->lsa_stripe_count = stripe_count;
2334         lsa->lsa_pool_name = pool_name;
2335 }
2336
2337 static inline bool setstripe_args_specified(struct lfs_setstripe_args *lsa)
2338 {
2339         return (lsa->lsa_stripe_size != LLAPI_LAYOUT_DEFAULT ||
2340                 lsa->lsa_stripe_count != LLAPI_LAYOUT_DEFAULT ||
2341                 lsa->lsa_stripe_off != LLAPI_LAYOUT_DEFAULT ||
2342                 lsa->lsa_pattern != LLAPI_LAYOUT_RAID0 ||
2343                 lsa->lsa_comp_end != 0);
2344 }
2345
2346 /**
2347  * comp_args_to_layout() - Create or extend a composite layout.
2348  * @composite:       Pointer to the composite layout.
2349  * @lsa:             Stripe options for the new component.
2350  *
2351  * This function creates or extends a composite layout by adding a new
2352  * component with stripe options from @lsa.
2353  *
2354  * Return: 0 on success or an error code on failure.
2355  */
2356 static int comp_args_to_layout(struct llapi_layout **composite,
2357                                struct lfs_setstripe_args *lsa,
2358                                bool set_extent)
2359 {
2360         struct llapi_layout *layout = *composite;
2361         uint64_t prev_end = 0;
2362         uint64_t size;
2363         int i = 0, rc;
2364
2365 new_comp:
2366         if (layout == NULL) {
2367                 layout = llapi_layout_alloc();
2368                 if (layout == NULL) {
2369                         fprintf(stderr, "Alloc llapi_layout failed. %s\n",
2370                                 strerror(errno));
2371                         errno = ENOMEM;
2372                         return -1;
2373                 }
2374                 *composite = layout;
2375                 lsa->lsa_first_comp = true;
2376         } else {
2377                 uint64_t start;
2378
2379                 /* Get current component extent, current component
2380                  * must be the tail component. */
2381                 rc = llapi_layout_comp_extent_get(layout, &start, &prev_end);
2382                 if (rc) {
2383                         fprintf(stderr, "Get comp extent failed. %s\n",
2384                                 strerror(errno));
2385                         return rc;
2386                 }
2387
2388                 if (lsa->lsa_first_comp)
2389                         prev_end = 0;
2390
2391                 if (lsa->lsa_first_comp)
2392                         rc = llapi_layout_add_first_comp(layout);
2393                 else
2394                         rc = llapi_layout_comp_add(layout);
2395                 if (rc) {
2396                         fprintf(stderr, "Add component failed. %s\n",
2397                                 strerror(errno));
2398                         return rc;
2399                 }
2400         }
2401
2402         rc = llapi_layout_comp_flags_set(layout, lsa->lsa_comp_flags);
2403         if (rc) {
2404                 fprintf(stderr, "Set flags 0x%x failed: %s\n",
2405                         lsa->lsa_comp_flags, strerror(errno));
2406                 return rc;
2407         }
2408
2409         if (set_extent) {
2410                 uint64_t comp_end = lsa->lsa_comp_end;
2411
2412                 /* The extendable component is 0-length, so it can be removed
2413                  * if there is insufficient space to extend it. */
2414                 if (lsa->lsa_extension_comp)
2415                         comp_end = prev_end;
2416
2417                 rc = llapi_layout_comp_extent_set(layout, prev_end,
2418                                                   comp_end);
2419                 if (rc) {
2420                         fprintf(stderr, "Set extent [%lu, %lu) failed. %s\n",
2421                                 prev_end, comp_end, strerror(errno));
2422                         return rc;
2423                 }
2424         }
2425         /* reset lsa_first_comp */
2426         lsa->lsa_first_comp = false;
2427
2428         /* Data-on-MDT component setting */
2429         if (lsa->lsa_pattern == LLAPI_LAYOUT_MDT) {
2430                 /* In case of Data-on-MDT patterns the only extra option
2431                  * applicable is stripe size option. */
2432                 if (lsa->lsa_stripe_count != LLAPI_LAYOUT_DEFAULT) {
2433                         fprintf(stderr, "Option 'stripe-count' can't be "
2434                                 "specified with Data-on-MDT component: %lld\n",
2435                                 lsa->lsa_stripe_count);
2436                         errno = EINVAL;
2437                         return -1;
2438                 }
2439                 if (lsa->lsa_stripe_size != LLAPI_LAYOUT_DEFAULT) {
2440                         fprintf(stderr, "Option 'stripe-size' can't be "
2441                                 "specified with Data-on-MDT component: %llu\n",
2442                                 lsa->lsa_stripe_size);
2443                         errno = EINVAL;
2444                         return -1;
2445                 }
2446                 if (lsa->lsa_nr_tgts != 0) {
2447                         fprintf(stderr, "Option 'ost-list' can't be specified "
2448                                 "with Data-on-MDT component: '%i'\n",
2449                                 lsa->lsa_nr_tgts);
2450                         errno = EINVAL;
2451                         return -1;
2452                 }
2453                 if (lsa->lsa_stripe_off != LLAPI_LAYOUT_DEFAULT) {
2454                         fprintf(stderr, "Option 'stripe-offset' can't be "
2455                                 "specified with Data-on-MDT component: %lld\n",
2456                                 lsa->lsa_stripe_off);
2457                         errno = EINVAL;
2458                         return -1;
2459                 }
2460                 if (lsa->lsa_pool_name != 0) {
2461                         fprintf(stderr, "Option 'pool' can't be specified "
2462                                 "with Data-on-MDT component: '%s'\n",
2463                                 lsa->lsa_pool_name);
2464                         errno = EINVAL;
2465                         return -1;
2466                 }
2467
2468                 rc = llapi_layout_pattern_set(layout, lsa->lsa_pattern);
2469                 if (rc) {
2470                         fprintf(stderr, "Set stripe pattern %#llx failed. %s\n",
2471                                 lsa->lsa_pattern,
2472                                 strerror(errno));
2473                         return rc;
2474                 }
2475                 /* Data-on-MDT component has always single stripe up to end */
2476                 lsa->lsa_stripe_size = lsa->lsa_comp_end;
2477         } else if (lsa->lsa_pattern == LLAPI_LAYOUT_OVERSTRIPING) {
2478                 rc = llapi_layout_pattern_set(layout, lsa->lsa_pattern);
2479                 if (rc) {
2480                         fprintf(stderr, "Set stripe pattern %#llx failed. %s\n",
2481                                 lsa->lsa_pattern,
2482                                 strerror(errno));
2483                         return rc;
2484                 }
2485         }
2486
2487         size = lsa->lsa_comp_flags & LCME_FL_EXTENSION ?
2488                 lsa->lsa_extension_size : lsa->lsa_stripe_size;
2489
2490         if (lsa->lsa_comp_flags & LCME_FL_EXTENSION)
2491                 rc = llapi_layout_extension_size_set(layout, size);
2492         else
2493                 rc = llapi_layout_stripe_size_set(layout, size);
2494
2495         if (rc) {
2496                 fprintf(stderr, "Set stripe size %lu failed: %s\n",
2497                         size, strerror(errno));
2498                 return rc;
2499         }
2500
2501         rc = llapi_layout_stripe_count_set(layout, lsa->lsa_stripe_count);
2502         if (rc) {
2503                 fprintf(stderr, "Set stripe count %lld failed: %s\n",
2504                         lsa->lsa_stripe_count, strerror(errno));
2505                 return rc;
2506         }
2507
2508         if (lsa->lsa_pool_name != NULL) {
2509                 rc = llapi_layout_pool_name_set(layout, lsa->lsa_pool_name);
2510                 if (rc) {
2511                         fprintf(stderr, "Set pool name: %s failed. %s\n",
2512                                 lsa->lsa_pool_name, strerror(errno));
2513                         return rc;
2514                 }
2515         } else {
2516                 rc = llapi_layout_pool_name_set(layout, "");
2517                 if (rc) {
2518                         fprintf(stderr, "Clear pool name failed: %s\n",
2519                                 strerror(errno));
2520                         return rc;
2521                 }
2522         }
2523
2524         if (lsa->lsa_nr_tgts > 0) {
2525                 if (lsa->lsa_stripe_count > 0 &&
2526                     lsa->lsa_stripe_count != LLAPI_LAYOUT_DEFAULT &&
2527                     lsa->lsa_stripe_count != LLAPI_LAYOUT_WIDE &&
2528                     lsa->lsa_nr_tgts != lsa->lsa_stripe_count) {
2529                         fprintf(stderr, "stripe_count(%lld) != nr_tgts(%d)\n",
2530                                 lsa->lsa_stripe_count,
2531                                 lsa->lsa_nr_tgts);
2532                         errno = EINVAL;
2533                         return -1;
2534                 }
2535                 for (i = 0; i < lsa->lsa_nr_tgts; i++) {
2536                         rc = llapi_layout_ost_index_set(layout, i,
2537                                                         lsa->lsa_tgts[i]);
2538                         if (rc)
2539                                 break;
2540                 }
2541         } else if (lsa->lsa_stripe_off != LLAPI_LAYOUT_DEFAULT &&
2542                    lsa->lsa_stripe_off != -1) {
2543                 rc = llapi_layout_ost_index_set(layout, 0, lsa->lsa_stripe_off);
2544         }
2545         if (rc) {
2546                 fprintf(stderr, "Set ost index %d failed. %s\n",
2547                         i, strerror(errno));
2548                 return rc;
2549         }
2550
2551         /* Create the second, virtual component of extension space */
2552         if (lsa->lsa_extension_comp) {
2553                 lsa->lsa_comp_flags |= LCME_FL_EXTENSION;
2554                 lsa->lsa_extension_comp = false;
2555                 goto new_comp;
2556         }
2557
2558         return rc;
2559 }
2560
2561 static int build_component(struct llapi_layout **layout,
2562                            struct lfs_setstripe_args *lsa, bool set_extent)
2563 {
2564         int rc;
2565
2566         rc = comp_args_to_layout(layout, lsa, set_extent);
2567         if (rc)
2568                 return rc;
2569
2570         if (lsa->lsa_mirror_count > 0) {
2571                 rc = llapi_layout_mirror_count_set(*layout,
2572                                                    lsa->lsa_mirror_count);
2573                 if (rc)
2574                         return rc;
2575
2576                 rc = llapi_layout_flags_set(*layout, LCM_FL_RDONLY);
2577                 if (rc)
2578                         return rc;
2579                 lsa->lsa_mirror_count = 0;
2580         }
2581
2582         return rc;
2583 }
2584
2585 static int build_layout_from_yaml_node(struct cYAML *node,
2586                                        struct llapi_layout **layout,
2587                                        struct lfs_setstripe_args *lsa,
2588                                        __u32 *osts)
2589 {
2590         char *string;
2591         int rc = 0;
2592
2593         while (node) {
2594                 if (node->cy_type == CYAML_TYPE_OBJECT) {
2595                         /* go deep to sub blocks */
2596                         rc = build_layout_from_yaml_node(node->cy_child, layout,
2597                                                          lsa, osts);
2598                         if (rc)
2599                                 return rc;
2600                 } else {
2601                         if (node->cy_string == NULL)
2602                                 return -EINVAL;
2603
2604                         string = node->cy_string;
2605                         /* skip leading lmm_ if present, to simplify parsing */
2606                         if (strncmp(string, "lmm_", 4) == 0)
2607                                 string += 4;
2608
2609                         if (node->cy_type == CYAML_TYPE_STRING) {
2610                                 if (!strcmp(string, "lcme_extent.e_end")) {
2611                                         if (!strcmp(node->cy_valuestring, "EOF") ||
2612                                             !strcmp(node->cy_valuestring, "eof"))
2613                                                 lsa->lsa_comp_end = LUSTRE_EOF;
2614                                 } else if (!strcmp(string, "pool")) {
2615                                         lsa->lsa_pool_name = node->cy_valuestring;
2616                                 } else if (!strcmp(string, "pattern")) {
2617                                         if (!strcmp(node->cy_valuestring, "mdt"))
2618                                                 lsa->lsa_pattern = LLAPI_LAYOUT_MDT;
2619                                         if (!strcmp(node->cy_valuestring,
2620                                                     "raid0,overstriped"))
2621                                                 lsa->lsa_pattern =
2622                                                         LLAPI_LAYOUT_OVERSTRIPING;
2623                                 } else if (!strcmp(string, "lcme_flags")) {
2624                                         rc = comp_str2flags(node->cy_valuestring,
2625                                                             &lsa->lsa_comp_flags,
2626                                                             &lsa->lsa_comp_neg_flags);
2627                                         if (rc)
2628                                                 return rc;
2629                                         /* Only template flags have meaning in
2630                                          * the layout for a new file
2631                                          */
2632                                         lsa->lsa_comp_flags &= LCME_TEMPLATE_FLAGS;
2633                                 }
2634                         } else if (node->cy_type == CYAML_TYPE_NUMBER) {
2635                                 if (!strcmp(string, "lcm_mirror_count")) {
2636                                         lsa->lsa_mirror_count = node->cy_valueint;
2637                                 } else if (!strcmp(string, "lcme_extent.e_start")) {
2638                                         if (node->cy_valueint != 0 || *layout != NULL) {
2639                                                 rc = build_component(layout, lsa, true);
2640                                                 if (rc)
2641                                                         return rc;
2642                                         }
2643
2644                                         if (node->cy_valueint == 0)
2645                                                 lsa->lsa_first_comp = true;
2646
2647                                         /* initialize lsa */
2648                                         setstripe_args_init(lsa);
2649                                         lsa->lsa_tgts = osts;
2650                                 } else if (!strcmp(string, "lcme_extent.e_end")) {
2651                                         if (node->cy_valueint == -1)
2652                                                 lsa->lsa_comp_end = LUSTRE_EOF;
2653                                         else
2654                                                 lsa->lsa_comp_end = node->cy_valueint;
2655                                 } else if (!strcmp(string, "stripe_count")) {
2656                                         lsa->lsa_stripe_count = node->cy_valueint;
2657                                 } else if (!strcmp(string, "stripe_size")) {
2658                                         lsa->lsa_stripe_size = node->cy_valueint;
2659                                 } else if (!strcmp(string, "stripe_offset")) {
2660                                         lsa->lsa_stripe_off = node->cy_valueint;
2661                                 } else if (!strcmp(string, "l_ost_idx")) {
2662                                         osts[lsa->lsa_nr_tgts] = node->cy_valueint;
2663                                         lsa->lsa_nr_tgts++;
2664                                 }
2665                         }
2666                 }
2667                 node = node->cy_next;
2668         }
2669
2670         return rc;
2671 }
2672
2673 static int lfs_comp_create_from_yaml(char *template,
2674                                      struct llapi_layout **layout,
2675                                      struct lfs_setstripe_args *lsa,
2676                                      __u32 *osts)
2677 {
2678         struct cYAML *tree = NULL, *err_rc = NULL;
2679         int rc = 0;
2680
2681         tree = cYAML_build_tree(template, NULL, 0, &err_rc, false);
2682         if (!tree) {
2683                 fprintf(stderr, "%s: cannot parse YAML file %s\n",
2684                         progname, template);
2685                 cYAML_build_error(-EINVAL, -1, "yaml", "from comp yaml",
2686                                   "can't parse", &err_rc);
2687                 cYAML_print_tree2file(stderr, err_rc);
2688                 cYAML_free_tree(err_rc);
2689                 rc = -EINVAL;
2690                 goto err;
2691         }
2692
2693         /* initialize lsa for plain file */
2694         setstripe_args_init(lsa);
2695         lsa->lsa_tgts = osts;
2696
2697         rc = build_layout_from_yaml_node(tree, layout, lsa, osts);
2698         if (rc) {
2699                 fprintf(stderr, "%s: cannot build layout from YAML file %s.\n",
2700                         progname, template);
2701                 goto err;
2702         } else {
2703                 rc = build_component(layout, lsa, *layout != NULL);
2704         }
2705         /* clean clean lsa */
2706         setstripe_args_init(lsa);
2707
2708 err:
2709         if (tree)
2710                 cYAML_free_tree(tree);
2711         return rc;
2712 }
2713
2714 /**
2715  * Get the extension size from the next (SEL) component and extend the
2716  * current component on it. The start of the next component is to be
2717  * adjusted as well.
2718  *
2719  * \param[in] layout    the current layout
2720  * \param[in] start     the start of the current component
2721  * \param[in,out] end   the end of the current component
2722  * \param[in] offset    the offset to adjust the end position to instead of
2723  *                      extension size
2724  *
2725  * \retval 0            - extended successfully
2726  * \retval < 0          - error
2727  */
2728 static int layout_extend_comp(struct llapi_layout *layout,
2729                               uint64_t start, uint64_t *end,
2730                               uint64_t offset)
2731 {
2732         uint64_t size, next_start, next_end;
2733         int rc;
2734
2735         rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_NEXT);
2736         if (rc < 0) {
2737                 fprintf(stderr, "%s setstripe: cannot move component cursor: "
2738                         "%s\n", progname, strerror(errno));
2739                 return rc;
2740         }
2741
2742         /* Even if the @size will not be used below, this will fail if
2743          * this is not a SEL component - a good confirmation we are
2744          * working on right components. */
2745         rc = llapi_layout_extension_size_get(layout, &size);
2746         if (rc < 0) {
2747                 fprintf(stderr, "%s setstripe: cannot get component ext size: "
2748                         "%s\n", progname, strerror(errno));
2749                 return rc;
2750         }
2751
2752         rc = llapi_layout_comp_extent_get(layout, &next_start, &next_end);
2753         if (rc) {
2754                 fprintf(stderr, "%s setstripe: cannot get extent: %s\n",
2755                         progname, strerror(errno));
2756                 return rc;
2757         }
2758
2759         next_start += offset ?: size;
2760         rc = llapi_layout_comp_extent_set(layout, next_start, next_end);
2761         if (rc) {
2762                 fprintf(stderr, "%s setstripe: cannot set extent: %s\n",
2763                         progname, strerror(errno));
2764                 return rc;
2765         }
2766
2767         rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_PREV);
2768         if (rc < 0) {
2769                 fprintf(stderr, "%s setstripe: cannot move component cursor: "
2770                         "%s\n", progname, strerror(errno));
2771                 return rc;
2772         }
2773
2774         *end += offset ?: size;
2775         rc = llapi_layout_comp_extent_set(layout, start, *end);
2776         if (rc) {
2777                 fprintf(stderr, "%s setstripe: cannot set extent: %s\n",
2778                         progname, strerror(errno));
2779                 return rc;
2780         }
2781
2782         return 0;
2783 }
2784
2785 /**
2786  * In 'lfs setstripe --component-add' mode, we need to fetch the extent
2787  * end of the last component in the existing file, and adjust the
2788  * first extent start of the components to be added accordingly.
2789  *
2790  * In the create mode, we need to check if the first component is an extendable
2791  * SEL component and extend its length to the extension size (first component
2792  * of the PFL file is initialised at the create time, cannot be 0-lenght.
2793  */
2794 static int layout_adjust_first_extent(char *fname, struct llapi_layout *layout,
2795                                       bool comp_add)
2796 {
2797         struct llapi_layout *head;
2798         uint64_t start = 0, prev_end = 0;
2799         uint64_t end;
2800         int rc, ret = 0;
2801
2802         if (layout == NULL)
2803                 return 0;
2804
2805         errno = 0;
2806         while (comp_add) {
2807                 head = llapi_layout_get_by_path(fname, 0);
2808                 if (head == NULL) {
2809                         fprintf(stderr,
2810                                 "%s setstripe: cannot read layout from '%s': "
2811                                 "%s\n", progname, fname, strerror(errno));
2812                         return -EINVAL;
2813                 } else if (errno == ENODATA) {
2814                         /* file without LOVEA, this component-add will be turned
2815                          * into a component-create. */
2816                         llapi_layout_free(head);
2817                         ret = -ENODATA;
2818
2819                         /* the new layout will be added to an empty one, it
2820                          * still needs to be adjusted below */
2821                         comp_add = 0;
2822                         break;
2823                 } else if (!llapi_layout_is_composite(head)) {
2824                         fprintf(stderr, "%s setstripe: '%s' not a composite "
2825                                 "file\n", progname, fname);
2826                         llapi_layout_free(head);
2827                         return -EINVAL;
2828                 }
2829
2830                 rc = llapi_layout_comp_extent_get(head, &start, &prev_end);
2831                 if (rc) {
2832                         fprintf(stderr, "%s setstripe: cannot get prev "
2833                                 "extent: %s\n", progname, strerror(errno));
2834                         llapi_layout_free(head);
2835                         return rc;
2836                 }
2837
2838                 llapi_layout_free(head);
2839                 break;
2840         }
2841
2842         /* Make sure we use the first component of the layout to be added. */
2843         rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_FIRST);
2844         if (rc < 0) {
2845                 fprintf(stderr,
2846                         "%s setstripe: cannot move component cursor: %s\n",
2847                         progname, strerror(errno));
2848                 return rc;
2849         }
2850
2851         rc = llapi_layout_comp_extent_get(layout, &start, &end);
2852         if (rc) {
2853                 fprintf(stderr, "%s setstripe: cannot get extent: %s\n",
2854                         progname, strerror(errno));
2855                 return rc;
2856         }
2857
2858         if (start == 0 && end == 0) {
2859                 rc = layout_extend_comp(layout, start, &end,
2860                                         comp_add ? prev_end : 0);
2861                 if (rc)
2862                         return rc;
2863         }
2864
2865         if (start > prev_end || end < prev_end) {
2866                 fprintf(stderr, "%s setstripe: first extent [%lu, %lu) not "
2867                         "adjacent with extent end %lu\n",
2868                         progname, start, end, prev_end);
2869                 return -EINVAL;
2870         }
2871
2872         rc = llapi_layout_comp_extent_set(layout, prev_end, end);
2873         if (rc) {
2874                 fprintf(stderr, "%s setstripe: cannot set component extent "
2875                         "[%lu, %lu): %s\n",
2876                         progname, prev_end, end, strerror(errno));
2877                 return rc;
2878         }
2879
2880         return ret;
2881 }
2882
2883 static int mirror_adjust_first_extents(struct mirror_args *list)
2884 {
2885         int rc = 0;
2886
2887         if (list == NULL)
2888                 return 0;
2889
2890         while (list != NULL) {
2891                 rc = layout_adjust_first_extent(NULL, list->m_layout, false);
2892                 if (rc)
2893                         break;
2894                 list = list->m_next;
2895         }
2896
2897         return rc;
2898 }
2899
2900 static inline bool arg_is_eof(char *arg)
2901 {
2902         return !strncmp(arg, "-1", strlen("-1")) ||
2903                !strncmp(arg, "EOF", strlen("EOF")) ||
2904                !strncmp(arg, "eof", strlen("eof"));
2905 }
2906
2907 /**
2908  * lfs_mirror_alloc() - Allocate a mirror argument structure.
2909  *
2910  * Return: Valid mirror_args pointer on success and
2911  *         NULL if memory allocation fails.
2912  */
2913 static struct mirror_args *lfs_mirror_alloc(void)
2914 {
2915         struct mirror_args *mirror = NULL;
2916
2917         while (1) {
2918                 mirror = calloc(1, sizeof(*mirror));
2919                 if (mirror != NULL)
2920                         break;
2921
2922                 sleep(1);
2923         }
2924
2925         return mirror;
2926 }
2927
2928 /**
2929  * lfs_mirror_free() - Free memory allocated for a mirror argument
2930  *                     structure.
2931  * @mirror: Previously allocated mirror argument structure by
2932  *          lfs_mirror_alloc().
2933  *
2934  * Free memory allocated for @mirror.
2935  *
2936  * Return: void.
2937  */
2938 static void lfs_mirror_free(struct mirror_args *mirror)
2939 {
2940         if (mirror->m_layout != NULL)
2941                 llapi_layout_free(mirror->m_layout);
2942         free(mirror);
2943 }
2944
2945 /**
2946  * lfs_mirror_list_free() - Free memory allocated for a mirror list.
2947  * @mirror_list: Previously allocated mirror list.
2948  *
2949  * Free memory allocated for @mirror_list.
2950  *
2951  * Return: void.
2952  */
2953 static void lfs_mirror_list_free(struct mirror_args *mirror_list)
2954 {
2955         struct mirror_args *next_mirror = NULL;
2956
2957         while (mirror_list != NULL) {
2958                 next_mirror = mirror_list->m_next;
2959                 lfs_mirror_free(mirror_list);
2960                 mirror_list = next_mirror;
2961         }
2962 }
2963
2964 enum {
2965         LFS_POOL_OPT = 3,
2966         LFS_COMP_COUNT_OPT,
2967         LFS_COMP_START_OPT,
2968         LFS_COMP_FLAGS_OPT,
2969         LFS_COMP_DEL_OPT,
2970         LFS_COMP_SET_OPT,
2971         LFS_COMP_ADD_OPT,
2972         LFS_COMP_NO_VERIFY_OPT,
2973         LFS_PROJID_OPT,
2974         LFS_LAYOUT_FLAGS_OPT, /* used for mirror and foreign flags */
2975         LFS_MIRROR_ID_OPT,
2976         LFS_MIRROR_STATE_OPT,
2977         LFS_LAYOUT_COPY,
2978         LFS_MIRROR_INDEX_OPT,
2979         LFS_LAYOUT_FOREIGN_OPT,
2980         LFS_MODE_OPT,
2981         LFS_NEWERXY_OPT,
2982 };
2983
2984 /* functions */
2985 static int lfs_setstripe_internal(int argc, char **argv,
2986                                   enum setstripe_origin opc)
2987 {
2988         struct lfs_setstripe_args        lsa = { 0 };
2989         struct llapi_stripe_param       *param = NULL;
2990         struct find_param                migrate_mdt_param = {
2991                 .fp_max_depth = -1,
2992                 .fp_mdt_index = -1,
2993         };
2994         char                            *fname;
2995         int                              result = 0;
2996         int                              result2 = 0;
2997         char                            *end;
2998         int                              c;
2999         int                              delete = 0;
3000         unsigned long long               size_units = 1;
3001         bool                             migrate_mode = false;
3002         bool                             migrate_mdt_mode = false;
3003         bool                             setstripe_mode = false;
3004         bool                             migration_block = false;
3005         __u64                            migration_flags = 0;
3006         __u32                            tgts[LOV_MAX_STRIPE_COUNT] = { 0 };
3007         int                              comp_del = 0, comp_set = 0;
3008         int                              comp_add = 0;
3009         __u32                            comp_id = 0;
3010         struct llapi_layout             *layout = NULL;
3011         struct llapi_layout             **lpp = &layout;
3012         bool                             mirror_mode = false;
3013         bool                             has_m_file = false;
3014         __u32                            mirror_count = 0;
3015         enum mirror_flags                mirror_flags = 0;
3016         struct mirror_args              *mirror_list = NULL;
3017         struct mirror_args              *new_mirror = NULL;
3018         struct mirror_args              *last_mirror = NULL;
3019         __u16                            mirror_id = 0;
3020         char                             cmd[PATH_MAX];
3021         bool from_yaml = false;
3022         bool from_copy = false;
3023         char *template = NULL;
3024         bool foreign_mode = false;
3025         char *xattr = NULL;
3026         uint32_t type = LU_FOREIGN_TYPE_NONE, flags = 0;
3027         char *mode_opt = NULL;
3028         mode_t previous_umask = 0;
3029         mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
3030
3031         struct option long_opts[] = {
3032 /* find { .val = '0',   .name = "null",         .has_arg = no_argument }, */
3033 /* find { .val = 'A',   .name = "atime",        .has_arg = required_argument }*/
3034         /* --block is only valid in migrate mode */
3035         { .val = 'b',   .name = "block",        .has_arg = no_argument },
3036         { .val = LFS_COMP_ADD_OPT,
3037                         .name = "comp-add",     .has_arg = no_argument },
3038         { .val = LFS_COMP_ADD_OPT,
3039                         .name = "component-add", .has_arg = no_argument },
3040         { .val = LFS_COMP_DEL_OPT,
3041                         .name = "comp-del",     .has_arg = no_argument },
3042         { .val = LFS_COMP_DEL_OPT,
3043                         .name = "component-del", .has_arg = no_argument },
3044         { .val = LFS_COMP_FLAGS_OPT,
3045                         .name = "comp-flags",   .has_arg = required_argument },
3046         { .val = LFS_COMP_FLAGS_OPT,
3047                         .name = "component-flags",
3048                                                 .has_arg = required_argument },
3049         { .val = LFS_COMP_SET_OPT,
3050                         .name = "comp-set",     .has_arg = no_argument },
3051         { .val = LFS_COMP_SET_OPT,
3052                         .name = "component-set",
3053                                                 .has_arg = no_argument},
3054         { .val = LFS_COMP_NO_VERIFY_OPT,
3055                         .name = "no-verify",    .has_arg = no_argument},
3056         { .val = LFS_LAYOUT_FLAGS_OPT,
3057                         .name = "flags",        .has_arg = required_argument},
3058         { .val = LFS_LAYOUT_FOREIGN_OPT,
3059                         .name = "foreign",      .has_arg = optional_argument},
3060         { .val = LFS_MIRROR_ID_OPT,
3061                         .name = "mirror-id",    .has_arg = required_argument},
3062         { .val = LFS_MODE_OPT,
3063                         .name = "mode",         .has_arg = required_argument},
3064         { .val = LFS_LAYOUT_COPY,
3065                         .name = "copy",         .has_arg = required_argument},
3066         { .val = 'c',   .name = "stripe-count", .has_arg = required_argument},
3067         { .val = 'c',   .name = "stripe_count", .has_arg = required_argument},
3068         { .val = 'c',   .name = "mdt-count",    .has_arg = required_argument},
3069         { .val = 'C',   .name = "overstripe-count",
3070                                                 .has_arg = required_argument},
3071         { .val = 'd',   .name = "delete",       .has_arg = no_argument},
3072         { .val = 'd',   .name = "destroy",      .has_arg = no_argument},
3073         /* --non-direct is only valid in migrate mode */
3074         { .val = 'D',   .name = "non-direct",   .has_arg = no_argument },
3075         { .val = 'E',   .name = "comp-end",     .has_arg = required_argument},
3076         { .val = 'E',   .name = "component-end",
3077                                                 .has_arg = required_argument},
3078         { .val = 'f',   .name = "file",         .has_arg = required_argument },
3079 /* find { .val = 'F',   .name = "fid",          .has_arg = no_argument }, */
3080 /* find { .val = 'g',   .name = "gid",          .has_arg = no_argument }, */
3081 /* find { .val = 'G',   .name = "group",        .has_arg = required_argument }*/
3082 /* find { .val = 'h',   .name = "help",         .has_arg = no_argument }, */
3083         { .val = 'H',   .name = "mdt-hash",     .has_arg = required_argument},
3084         { .val = 'i',   .name = "stripe-index", .has_arg = required_argument},
3085         { .val = 'i',   .name = "stripe_index", .has_arg = required_argument},
3086         { .val = 'I',   .name = "comp-id",      .has_arg = required_argument},
3087         { .val = 'I',   .name = "component-id", .has_arg = required_argument},
3088 /* find { .val = 'l',   .name = "lazy",         .has_arg = no_argument }, */
3089         { .val = 'L',   .name = "layout",       .has_arg = required_argument },
3090         { .val = 'm',   .name = "mdt",          .has_arg = required_argument},
3091         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument},
3092         { .val = 'm',   .name = "mdt_index",    .has_arg = required_argument},
3093         /* --non-block is only valid in migrate mode */
3094         { .val = 'n',   .name = "non-block",    .has_arg = no_argument },
3095         { .val = 'N',   .name = "mirror-count", .has_arg = optional_argument},
3096         { .val = 'o',   .name = "ost",          .has_arg = required_argument },
3097 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
3098         { .val = 'o',   .name = "ost-list",     .has_arg = required_argument },
3099         { .val = 'o',   .name = "ost_list",     .has_arg = required_argument },
3100 #endif
3101         { .val = 'p',   .name = "pool",         .has_arg = required_argument },
3102 /* find { .val = 'P',   .name = "print",        .has_arg = no_argument }, */
3103 /* getstripe { .val = 'q', .name = "quiet",     .has_arg = no_argument }, */
3104 /* getstripe { .val = 'r', .name = "recursive", .has_arg = no_argument }, */
3105 /* getstripe { .val = 'R', .name = "raw",       .has_arg = no_argument }, */
3106         { .val = 'S',   .name = "stripe-size",  .has_arg = required_argument },
3107         { .val = 'S',   .name = "stripe_size",  .has_arg = required_argument },
3108 /* find { .val = 't',   .name = "type",         .has_arg = required_argument }*/
3109 /* dirstripe { .val = 'T', .name = "mdt-count", .has_arg = required_argument }*/
3110 /* find { .val = 'u',   .name = "uid",          .has_arg = required_argument }*/
3111 /* find { .val = 'U',   .name = "user",         .has_arg = required_argument }*/
3112         /* --verbose is only valid in migrate mode */
3113         { .val = 'v',   .name = "verbose",      .has_arg = no_argument},
3114         { .val = 'x',   .name = "xattr",        .has_arg = required_argument },
3115         { .val = 'y',   .name = "yaml",         .has_arg = required_argument },
3116         { .val = 'z',   .name = "ext-size",     .has_arg = required_argument},
3117         { .val = 'z',   .name = "extension-size", .has_arg = required_argument},
3118         { .name = NULL } };
3119
3120         setstripe_args_init(&lsa);
3121
3122         migrate_mode = (opc == SO_MIGRATE);
3123         mirror_mode = (opc == SO_MIRROR_CREATE || opc == SO_MIRROR_EXTEND);
3124         setstripe_mode = (opc == SO_SETSTRIPE);
3125         if (opc == SO_MIRROR_DELETE) {
3126                 delete = 1;
3127                 mirror_flags = MF_DESTROY;
3128         }
3129
3130         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
3131         progname = cmd;
3132         while ((c = getopt_long(argc, argv,
3133                                 "bc:C:dDE:f:H:i:I:m:N::no:p:L:s:S:vx:y:z:",
3134                                 long_opts, NULL)) >= 0) {
3135                 size_units = 1;
3136                 switch (c) {
3137                 case 0:
3138                         /* Long options. */