Whamcloud - gitweb
29cb88c2060a04ccb09c3c0c7f0620d5f3341c94
[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 'notify'|<block-grace>]\n"
516          "                [--inode-grace 'notify'|<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.\n\n"
540          "      When setting the grace time, 'notify' can be used as grace to\n"
541          "      be notified after the quota is over soft limit but prevents\n"
542          "      the soft limit from becoming the hard limit."},
543         {"quota", lfs_quota, 0, "Display disk usage and limits.\n"
544          "usage: quota [-q] [-v] [-h] [-o <obd_uuid>|-i <mdt_idx>|-I "
545                        "<ost_idx>]\n"
546          "             [<-u|-g|-p> <uname>|<uid>|<gname>|<gid>|<projid>] <filesystem>\n"
547          "       quota [-o <obd_uuid>|-i <mdt_idx>|-I <ost_idx>] -t <-u|-g|-p> <filesystem>\n"
548         "        quota [-q] [-v] [h] <-U|-G|-P> <filesystem>"},
549         {"project", lfs_project, 0,
550          "Change or list project attribute for specified file or directory.\n"
551          "usage: project [-d|-r] <file|directory...>\n"
552          "         list project ID and flags on file(s) or directories\n"
553          "       project [-p id] [-s] [-r] <file|directory...>\n"
554          "         set project ID and/or inherit flag for specified file(s) or directories\n"
555          "       project -c [-d|-r [-p id] [-0]] <file|directory...>\n"
556          "         check project ID and flags on file(s) or directories, print outliers\n"
557          "       project -C [-r] [-k] <file|directory...>\n"
558          "         clear the project inherit flag and ID on the file or directory\n"
559         },
560 #endif
561         {"flushctx", lfs_flushctx, 0, "Flush security context for current user.\n"
562          "usage: flushctx [-k] [mountpoint...]"},
563         {"changelog", lfs_changelog, 0,
564          "Show the metadata changes on an MDT."
565          "\nusage: changelog <mdtname> [startrec [endrec]]"},
566         {"changelog_clear", lfs_changelog_clear, 0,
567          "Indicate that old changelog records up to <endrec> are no longer of "
568          "interest to consumer <id>, allowing the system to free up space.\n"
569          "An <endrec> of 0 means all records.\n"
570          "usage: changelog_clear <mdtname> <id> <endrec>"},
571         {"fid2path", lfs_fid2path, 0,
572          "Resolve the full path(s) for given FID(s). For a specific hardlink "
573          "specify link number <linkno>.\n"
574          "usage: fid2path [-c] [--link|-l <linkno>] <fsname|root> <fid> ..."},
575         {"path2fid", lfs_path2fid, 0, "Display the fid(s) for a given path(s).\n"
576          "usage: path2fid [--parents] <path> ..."},
577         {"rmfid", lfs_rmfid, 0, "Remove file(s) by FID(s)\n"
578          "usage: rmfid <fsname|rootpath> <fid> ..."},
579         {"data_version", lfs_data_version, 0, "Display file data version for "
580          "a given path.\n" "usage: data_version -[n|r|w] <path>"},
581         {"hsm_state", lfs_hsm_state, 0, "Display the HSM information (states, "
582          "undergoing actions) for given files.\n usage: hsm_state <file> ..."},
583         {"hsm_set", lfs_hsm_set, 0, "Set HSM user flag on specified files.\n"
584          "usage: hsm_set [--norelease] [--noarchive] [--dirty] [--exists] "
585          "[--archived] [--lost] [--archive-id NUM] <file> ..."},
586         {"hsm_clear", lfs_hsm_clear, 0, "Clear HSM user flag on specified "
587          "files.\n"
588          "usage: hsm_clear [--norelease] [--noarchive] [--dirty] [--exists] "
589          "[--archived] [--lost] <file> ..."},
590         {"hsm_action", lfs_hsm_action, 0, "Display current HSM request for "
591          "given files.\n" "usage: hsm_action <file> ..."},
592         {"hsm_archive", lfs_hsm_archive, 0,
593          "Archive file to external storage.\n"
594          "usage: hsm_archive [--filelist FILELIST] [--data DATA] [--archive NUM] "
595          "<file> ..."},
596         {"hsm_restore", lfs_hsm_restore, 0,
597          "Restore file from external storage.\n"
598          "usage: hsm_restore [--filelist FILELIST] [--data DATA] <file> ..."},
599         {"hsm_release", lfs_hsm_release, 0,
600          "Release files from Lustre.\n"
601          "usage: hsm_release [--filelist FILELIST] [--data DATA] <file> ..."},
602         {"hsm_remove", lfs_hsm_remove, 0,
603          "Remove file copy from external storage.\n"
604          "usage: hsm_remove [--filelist FILELIST] [--data DATA] "
605          "[--archive NUM]\n"
606          "                  (FILE [FILE ...] | "
607          "--mntpath MOUNTPATH FID [FID ...])\n"
608          "\n"
609          "Note: To remove an archived copy of a file already deleted from a "
610          "Lustre FS, the\n"
611          "--mntpath option and a list of FIDs must be specified"
612         },
613         {"hsm_cancel", lfs_hsm_cancel, 0,
614          "Cancel requests related to specified files.\n"
615          "usage: hsm_cancel [--filelist FILELIST] [--data DATA] <file> ..."},
616         {"swap_layouts", lfs_swap_layouts, 0, "Swap layouts between 2 files.\n"
617          "usage: swap_layouts <path1> <path2>"},
618         {"migrate", lfs_setstripe_migrate, 0,
619          "migrate a directory between MDTs.\n"
620          "usage: migrate [--mdt-count|-c] <stripe_count>\n"
621          "               [--mdt-hash|-H] <hash_type>\n"
622          "               [--mdt-index|-m] <start_mdt_index>\n"
623          "               [--verbose|-v]\n"
624          "               <directory>\n"
625          "\tmdt:        MDTs to stripe over, if only one MDT is specified\n"
626          "                      it's the MDT index of first stripe\n"
627          "\tmdt_count:  number of MDTs to stripe a directory over\n"
628          "\tmdt_hash:   hash type of the striped directory. mdt types:\n"
629          "                      fnv_1a_64 FNV-1a hash algorithm (default)\n"
630          "                      all_char  sum of characters % MDT_COUNT\n"
631          "\n"
632          "migrate file objects from one OST "
633          "layout\nto another (may be not safe with concurent writes).\n"
634          "usage: migrate  "
635          "[--stripe-count|-c] <stripe_count>\n"
636          "[--overstripe-count|-C] <stripe_count>\n"
637          "              [--stripe-index|-i] <start_ost_index>\n"
638          "              [--stripe-size|-S] <stripe_size>\n"
639          "              [--pool|-p] <pool_name>\n"
640          "              [--ost|-o] <ost_indices>\n"
641          "              [--block|-b]\n"
642          "              [--non-block|-n]\n"
643          "              [--non-direct|-D]\n"
644          "              <file|directory>\n"
645          "\tstripe_count:     number of OSTs to stripe a file over\n"
646          "\t              Using -C instead of -c allows overstriping, which\n"
647          "\t              will place more than one stripe per OST if\n"
648          "\t              stripe_count is greater than the number of OSTs\n"
649          "\tstripe_ost_index: index of the first OST to stripe a file over\n"
650          "\tstripe_size:      number of bytes to store before moving to the next OST\n"
651          "\tpool_name:        name of the predefined pool of OSTs\n"
652          "\tost_indices:      OSTs to stripe over, in order\n"
653          "\tblock:        Block file access during data migration (default)\n"
654          "\tnon-block:    Abort migrations if concurrent access is detected\n"
655          "\tnon-direct:       do not use direct I/O to copy file contents.\n"},
656         {"mv", lfs_mv, 0,
657          "To move directories between MDTs. This command is deprecated, "
658          "use \"migrate\" instead.\n"
659          "usage: mv <directory|filename> [--mdt-index|-m] <mdt_index> "
660          "[--verbose|-v]\n"},
661         {"ladvise", lfs_ladvise, 0,
662          "Provide servers with advice about access patterns for a file.\n"
663          "usage: ladvise [--advice|-a ADVICE] [--start|-s START[kMGT]]\n"
664          "               [--background|-b] [--unset|-u]\n\n"
665          "               {[--end|-e END[kMGT]] | [--length|-l LENGTH[kMGT]]}\n"
666          "               {[--mode|-m [READ,WRITE]}\n"
667          "               <file> ...\n"},
668         {"mirror", lfs_mirror, mirror_cmdlist,
669          "lfs commands used to manage files with mirrored components:\n"
670          "lfs mirror create - create a mirrored file or directory\n"
671          "lfs mirror extend - add mirror(s) to an existing file\n"
672          "lfs mirror split  - split a mirror from an existing mirrored file\n"
673          "lfs mirror resync - resynchronize out-of-sync mirrored file(s)\n"
674          "lfs mirror read   - read a mirror content of a mirrored file\n"
675          "lfs mirror write  - write to a mirror of a mirrored file\n"
676          "lfs mirror copy   - copy a mirror to other mirror(s) of a file\n"
677          "lfs mirror verify - verify mirrored file(s)\n"},
678         {"getsom", lfs_getsom, 0, "To list the SOM info for a given file.\n"
679          "usage: getsom [-s] [-b] [-f] <path>\n"
680          "\t-s: Only show the size value of the SOM data for a given file\n"
681          "\t-b: Only show the blocks value of the SOM data for a given file\n"
682          "\t-f: Only show the flags value of the SOM data for a given file\n"},
683         {"heat_get", lfs_heat_get, 0,
684          "To get heat of files.\n"
685          "usage: heat_get <file> ...\n"},
686         {"heat_set", lfs_heat_set, 0,
687          "To set heat flags of files.\n"
688          "usage: heat_set [--clear|-c] [--off|-o] [--on|-O] <file> ...\n"
689          "\t--clear|-c: Clear file heat for given files\n"
690          "\t--off|-o:   Turn off file heat for given files\n"
691          "\t--on|-O:    Turn on file heat for given files\n"},
692         {"pcc", lfs_pcc, pcc_cmdlist,
693          "lfs commands used to interact with PCC features:\n"
694          "lfs pcc attach - attach given files to Persistent Client Cache\n"
695          "lfs pcc attach_fid - attach given files into PCC by FID(s)\n"
696          "lfs pcc state  - display the PCC state for given files\n"
697          "lfs pcc detach - detach given files from Persistent Client Cache\n"
698          "lfs pcc detach_fid - detach given files from PCC by FID(s)\n"},
699         {"help", Parser_help, 0, "help"},
700         {"exit", Parser_quit, 0, "quit"},
701         {"quit", Parser_quit, 0, "quit"},
702         {"--version", Parser_version, 0,
703          "output build version of the utility and exit"},
704         {"--list-commands", lfs_list_commands, 0,
705          "list commands supported by the utility and exit"},
706         { 0, 0, 0, NULL }
707 };
708
709
710 static int check_hashtype(const char *hashtype)
711 {
712         int i;
713
714         for (i = LMV_HASH_TYPE_ALL_CHARS; i < LMV_HASH_TYPE_MAX; i++)
715                 if (strcmp(hashtype, mdt_hash_name[i]) == 0)
716                         return i;
717
718         return 0;
719 }
720
721 static uint32_t check_foreign_type_name(const char *foreign_type_name)
722 {
723         uint32_t i;
724
725         for (i = 0; i < LU_FOREIGN_TYPE_UNKNOWN; i++) {
726                 if (lu_foreign_types[i].lft_name == NULL)
727                         break;
728                 if (strcmp(foreign_type_name,
729                            lu_foreign_types[i].lft_name) == 0)
730                         return lu_foreign_types[i].lft_type;
731         }
732
733         return LU_FOREIGN_TYPE_UNKNOWN;
734 }
735
736 static const char *error_loc = "syserror";
737
738 enum {
739         MIGRATION_NONBLOCK      = 0x0001,
740         MIGRATION_MIRROR        = 0x0002,
741         MIGRATION_NONDIRECT     = 0x0004,
742         MIGRATION_VERBOSE       = 0x0008,
743 };
744
745 static int lfs_component_create(char *fname, int open_flags, mode_t open_mode,
746                                 struct llapi_layout *layout);
747
748 static int
749 migrate_open_files(const char *name, __u64 migration_flags,
750                    const struct llapi_stripe_param *param,
751                    struct llapi_layout *layout, int *fd_src, int *fd_tgt)
752 {
753         int                      fd = -1;
754         int                      fdv = -1;
755         int                      rflags;
756         int                      mdt_index;
757         int                      random_value;
758         char                     parent[PATH_MAX];
759         char                     volatile_file[PATH_MAX];
760         char                    *ptr;
761         int                      rc;
762         struct stat              st;
763         struct stat              stv;
764
765         if (param == NULL && layout == NULL) {
766                 error_loc = "layout information";
767                 return -EINVAL;
768         }
769
770         /* search for file directory pathname */
771         if (strlen(name) > sizeof(parent) - 1) {
772                 error_loc = "source file name";
773                 return -ERANGE;
774         }
775
776         strncpy(parent, name, sizeof(parent));
777         ptr = strrchr(parent, '/');
778         if (ptr == NULL) {
779                 if (getcwd(parent, sizeof(parent)) == NULL) {
780                         error_loc = "getcwd";
781                         return -errno;
782                 }
783         } else {
784                 if (ptr == parent) /* leading '/' */
785                         ptr = parent + 1;
786                 *ptr = '\0';
787         }
788
789         /* open file, direct io */
790         /* even if the file is only read, WR mode is nedeed to allow
791          * layout swap on fd */
792         rflags = O_RDWR;
793         if (!(migration_flags & MIGRATION_NONDIRECT))
794                 rflags |= O_DIRECT;
795         fd = open(name, rflags);
796         if (fd < 0) {
797                 rc = -errno;
798                 error_loc = "cannot open source file";
799                 return rc;
800         }
801
802         rc = llapi_file_fget_mdtidx(fd, &mdt_index);
803         if (rc < 0) {
804                 error_loc = "cannot get MDT index";
805                 goto out;
806         }
807
808         do {
809                 int open_flags = O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW;
810                 mode_t open_mode = S_IRUSR | S_IWUSR;
811
812                 random_value = random();
813                 rc = snprintf(volatile_file, sizeof(volatile_file),
814                               "%s/%s:%.4X:%.4X", parent, LUSTRE_VOLATILE_HDR,
815                               mdt_index, random_value);
816                 if (rc >= sizeof(volatile_file)) {
817                         rc = -ENAMETOOLONG;
818                         break;
819                 }
820
821                 /* create, open a volatile file, use caching (ie no directio) */
822                 if (param != NULL)
823                         fdv = llapi_file_open_param(volatile_file, open_flags,
824                                                     open_mode, param);
825                 else
826                         fdv = lfs_component_create(volatile_file, open_flags,
827                                                    open_mode, layout);
828         } while (fdv < 0 && (rc = fdv) == -EEXIST);
829
830         if (rc < 0) {
831                 error_loc = "cannot create volatile file";
832                 goto out;
833         }
834
835         /* In case the MDT does not support creation of volatile files
836          * we should try to unlink it. */
837         (void)unlink(volatile_file);
838
839         /* Not-owner (root?) special case.
840          * Need to set owner/group of volatile file like original.
841          * This will allow to pass related check during layout_swap.
842          */
843         rc = fstat(fd, &st);
844         if (rc != 0) {
845                 rc = -errno;
846                 error_loc = "cannot stat source file";
847                 goto out;
848         }
849
850         rc = fstat(fdv, &stv);
851         if (rc != 0) {
852                 rc = -errno;
853                 error_loc = "cannot stat volatile";
854                 goto out;
855         }
856
857         if (st.st_uid != stv.st_uid || st.st_gid != stv.st_gid) {
858                 rc = fchown(fdv, st.st_uid, st.st_gid);
859                 if (rc != 0) {
860                         rc = -errno;
861                         error_loc = "cannot change ownwership of volatile";
862                         goto out;
863                 }
864         }
865
866 out:
867         if (rc < 0) {
868                 if (fd > 0)
869                         close(fd);
870                 if (fdv > 0)
871                         close(fdv);
872         } else {
873                 *fd_src = fd;
874                 *fd_tgt = fdv;
875                 error_loc = NULL;
876         }
877         return rc;
878 }
879
880 static int migrate_copy_data(int fd_src, int fd_dst, int (*check_file)(int))
881 {
882         struct llapi_layout *layout;
883         size_t   buf_size = 4 * 1024 * 1024;
884         void    *buf = NULL;
885         ssize_t  rsize = -1;
886         ssize_t  wsize = 0;
887         size_t   rpos = 0;
888         size_t   wpos = 0;
889         off_t    bufoff = 0;
890         int      rc;
891
892         layout = llapi_layout_get_by_fd(fd_src, 0);
893         if (layout != NULL) {
894                 uint64_t stripe_size;
895
896                 rc = llapi_layout_stripe_size_get(layout, &stripe_size);
897                 if (rc == 0)
898                         buf_size = stripe_size;
899
900                 llapi_layout_free(layout);
901         }
902
903         /* Use a page-aligned buffer for direct I/O */
904         rc = posix_memalign(&buf, getpagesize(), buf_size);
905         if (rc != 0)
906                 return -rc;
907
908         while (1) {
909                 /* read new data only if we have written all
910                  * previously read data */
911                 if (wpos == rpos) {
912                         if (check_file) {
913                                 rc = check_file(fd_src);
914                                 if (rc < 0)
915                                         break;
916                         }
917
918                         rsize = read(fd_src, buf, buf_size);
919                         if (rsize < 0) {
920                                 rc = -errno;
921                                 break;
922                         }
923                         rpos += rsize;
924                         bufoff = 0;
925                 }
926                 /* eof ? */
927                 if (rsize == 0)
928                         break;
929
930                 wsize = write(fd_dst, buf + bufoff, rpos - wpos);
931                 if (wsize < 0) {
932                         rc = -errno;
933                         break;
934                 }
935                 wpos += wsize;
936                 bufoff += wsize;
937         }
938
939         if (rc == 0) {
940                 rc = fsync(fd_dst);
941                 if (rc < 0)
942                         rc = -errno;
943         }
944
945         free(buf);
946         return rc;
947 }
948
949 static int migrate_copy_timestamps(int fd, int fdv)
950 {
951         struct stat st;
952
953         if (fstat(fd, &st) == 0) {
954                 struct timeval tv[2] = {
955                         {.tv_sec = st.st_atime},
956                         {.tv_sec = st.st_mtime}
957                 };
958
959                 return futimes(fdv, tv);
960         }
961
962         return -errno;
963 }
964
965 static int migrate_block(int fd, int fdv)
966 {
967         __u64   dv1;
968         int     gid;
969         int     rc;
970         int     rc2;
971
972         rc = llapi_get_data_version(fd, &dv1, LL_DV_RD_FLUSH);
973         if (rc < 0) {
974                 error_loc = "cannot get dataversion";
975                 return rc;
976         }
977
978         do
979                 gid = random();
980         while (gid == 0);
981
982         /* The grouplock blocks all concurrent accesses to the file.
983          * It has to be taken after llapi_get_data_version as it would
984          * block it too. */
985         rc = llapi_group_lock(fd, gid);
986         if (rc < 0) {
987                 error_loc = "cannot get group lock";
988                 return rc;
989         }
990
991         rc = migrate_copy_data(fd, fdv, NULL);
992         if (rc < 0) {
993                 error_loc = "data copy failed";
994                 goto out_unlock;
995         }
996
997         /* Make sure we keep original atime/mtime values */
998         rc = migrate_copy_timestamps(fd, fdv);
999         if (rc < 0) {
1000                 error_loc = "timestamp copy failed";
1001                 goto out_unlock;
1002         }
1003
1004         /* swap layouts
1005          * for a migration we need to check data version on file did
1006          * not change.
1007          *
1008          * Pass in gid=0 since we already own grouplock. */
1009         rc = llapi_fswap_layouts_grouplock(fd, fdv, dv1, 0, 0,
1010                                            SWAP_LAYOUTS_CHECK_DV1);
1011         if (rc == -EAGAIN) {
1012                 error_loc = "file changed";
1013                 goto out_unlock;
1014         } else if (rc < 0) {
1015                 error_loc = "cannot swap layout";
1016                 goto out_unlock;
1017         }
1018
1019 out_unlock:
1020         rc2 = llapi_group_unlock(fd, gid);
1021         if (rc2 < 0 && rc == 0) {
1022                 error_loc = "unlock group lock";
1023                 rc = rc2;
1024         }
1025
1026         return rc;
1027 }
1028
1029 /**
1030  * Internal helper for migrate_copy_data(). Check lease and report error if
1031  * need be.
1032  *
1033  * \param[in]  fd           File descriptor on which to check the lease.
1034  *
1035  * \retval 0       Migration can keep on going.
1036  * \retval -errno  Error occurred, abort migration.
1037  */
1038 static int check_lease(int fd)
1039 {
1040         int rc;
1041
1042         rc = llapi_lease_check(fd);
1043         if (rc > 0)
1044                 return 0; /* llapi_check_lease returns > 0 on success. */
1045
1046         return -EBUSY;
1047 }
1048
1049 static int migrate_nonblock(int fd, int fdv)
1050 {
1051         __u64   dv1;
1052         __u64   dv2;
1053         int     rc;
1054
1055         rc = llapi_get_data_version(fd, &dv1, LL_DV_RD_FLUSH);
1056         if (rc < 0) {
1057                 error_loc = "cannot get data version";
1058                 return rc;
1059         }
1060
1061         rc = migrate_copy_data(fd, fdv, check_lease);
1062         if (rc < 0) {
1063                 error_loc = "data copy failed";
1064                 return rc;
1065         }
1066
1067         rc = llapi_get_data_version(fd, &dv2, LL_DV_RD_FLUSH);
1068         if (rc != 0) {
1069                 error_loc = "cannot get data version";
1070                 return rc;
1071         }
1072
1073         if (dv1 != dv2) {
1074                 rc = -EAGAIN;
1075                 error_loc = "source file changed";
1076                 return rc;
1077         }
1078
1079         /* Make sure we keep original atime/mtime values */
1080         rc = migrate_copy_timestamps(fd, fdv);
1081         if (rc < 0) {
1082                 error_loc = "timestamp copy failed";
1083                 return rc;
1084         }
1085
1086         return 0;
1087 }
1088
1089 static int lfs_component_set(char *fname, int comp_id,
1090                              __u32 flags, __u32 neg_flags)
1091 {
1092         __u32 ids[2];
1093         __u32 flags_array[2];
1094         size_t count = 0;
1095         int rc;
1096
1097         if (flags) {
1098                 ids[count] = comp_id;
1099                 flags_array[count] = flags;
1100                 ++count;
1101         }
1102
1103         if (neg_flags) {
1104                 if (neg_flags & LCME_FL_STALE) {
1105                         fprintf(stderr, "%s: cannot clear 'stale' flags from "
1106                                 "component. Please use lfs-mirror-resync(1) "
1107                                 "instead\n", progname);
1108                         return -EINVAL;
1109                 }
1110
1111                 ids[count] = comp_id;
1112                 flags_array[count] = neg_flags | LCME_FL_NEG;
1113                 ++count;
1114         }
1115
1116         rc = llapi_layout_file_comp_set(fname, ids, flags_array, count);
1117         if (rc) {
1118                 if (errno == EUCLEAN) {
1119                         rc = -errno;
1120                         fprintf(stderr,
1121                                 "%s: cannot set 'stale' flag on component '%#x' of the last non-stale mirror of '%s'\n",
1122                                 progname, comp_id, fname);
1123                 } else {
1124                         fprintf(stderr,
1125                                 "%s: cannot change the flags of component '%#x' of file '%s': %x / ^(%x)\n",
1126                                 progname, comp_id, fname, flags, neg_flags);
1127                 }
1128         }
1129
1130         return rc;
1131 }
1132
1133 static int lfs_component_del(char *fname, __u32 comp_id,
1134                              __u32 flags, __u32 neg_flags)
1135 {
1136         int     rc = 0;
1137
1138         if (flags && neg_flags)
1139                 return -EINVAL;
1140
1141         if (!flags && neg_flags)
1142                 flags = neg_flags | LCME_FL_NEG;
1143
1144         if ((flags && comp_id) || (!flags && !comp_id))
1145                 return -EINVAL;
1146
1147         if (flags) {
1148                 if (flags & ~LCME_KNOWN_FLAGS) {
1149                         fprintf(stderr,
1150                                 "%s setstripe: unknown flags %#x\n",
1151                                 progname, flags);
1152                         return -EINVAL;
1153                 }
1154         } else if (comp_id > LCME_ID_MAX) {
1155                 fprintf(stderr, "%s setstripe: invalid component id %u\n",
1156                         progname, comp_id);
1157                 return -EINVAL;
1158         }
1159
1160         rc = llapi_layout_file_comp_del(fname, comp_id, flags);
1161         if (rc)
1162                 fprintf(stderr,
1163                         "%s setstripe: cannot delete component %#x from '%s': %s\n",
1164                         progname, comp_id, fname, strerror(errno));
1165         return rc;
1166 }
1167
1168 static int lfs_component_add(char *fname, struct llapi_layout *layout)
1169 {
1170         int     rc;
1171
1172         if (layout == NULL)
1173                 return -EINVAL;
1174
1175         rc = llapi_layout_file_comp_add(fname, layout);
1176         if (rc)
1177                 fprintf(stderr, "Add layout component(s) to %s failed. %s\n",
1178                         fname, strerror(errno));
1179         return rc;
1180 }
1181
1182 static int lfs_component_create(char *fname, int open_flags, mode_t open_mode,
1183                                 struct llapi_layout *layout)
1184 {
1185         struct stat     st;
1186         int     fd;
1187
1188         if (layout == NULL)
1189                 return -EINVAL;
1190
1191         fd = lstat(fname, &st);
1192         if (fd == 0 && S_ISDIR(st.st_mode))
1193                 open_flags = O_DIRECTORY | O_RDONLY;
1194
1195         fd = llapi_layout_file_open(fname, open_flags, open_mode, layout);
1196         if (fd < 0)
1197                 fprintf(stderr, "%s: cannot %s '%s': %s\n", progname,
1198                         S_ISDIR(st.st_mode) ?
1199                                 "set default composite layout for" :
1200                                 "create composite file",
1201                         fname, strerror(errno));
1202         return fd;
1203 }
1204
1205 static int lfs_migrate(char *name, __u64 migration_flags,
1206                        struct llapi_stripe_param *param,
1207                        struct llapi_layout *layout)
1208 {
1209         struct llapi_layout *existing;
1210         uint64_t dom_new, dom_cur;
1211         int fd = -1;
1212         int fdv = -1;
1213         int rc;
1214
1215         rc = migrate_open_files(name, migration_flags, param, layout,
1216                                 &fd, &fdv);
1217         if (rc < 0)
1218                 goto out;
1219
1220         rc = llapi_layout_dom_size(layout, &dom_new);
1221         if (rc) {
1222                 error_loc = "cannot get new layout DoM size";
1223                 goto out;
1224         }
1225         /* special case for migration to DOM layout*/
1226         existing = llapi_layout_get_by_fd(fd, 0);
1227         if (!existing) {
1228                 error_loc = "cannot get existing layout";
1229                 goto out;
1230         }
1231
1232         rc = llapi_layout_dom_size(existing, &dom_cur);
1233         if (rc) {
1234                 error_loc = "cannot get current layout DoM size";
1235                 goto out;
1236         }
1237
1238         /* if file has DoM layout already then migration is possible to
1239          * the new layout with the same DoM component via swap layout,
1240          * if new layout used bigger DOM size, then mirroring is used
1241          */
1242         if (dom_new > dom_cur) {
1243                 rc = lfs_migrate_to_dom(fd, fdv, name, migration_flags, param,
1244                                         layout);
1245                 if (rc)
1246                         error_loc = "cannot migrate to DOM layout";
1247                 goto out_closed;
1248         }
1249
1250         if (!(migration_flags & MIGRATION_NONBLOCK)) {
1251                 /* Blocking mode (forced if servers do not support file lease).
1252                  * It is also the default mode, since we cannot distinguish
1253                  * between a broken lease and a server that does not support
1254                  * atomic swap/close (LU-6785) */
1255                 rc = migrate_block(fd, fdv);
1256                 goto out;
1257         }
1258
1259         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
1260         if (rc < 0) {
1261                 error_loc = "cannot get lease";
1262                 goto out;
1263         }
1264
1265         rc = migrate_nonblock(fd, fdv);
1266         if (rc < 0) {
1267                 llapi_lease_release(fd);
1268                 goto out;
1269         }
1270
1271         /* Atomically put lease, swap layouts and close.
1272          * for a migration we need to check data version on file did
1273          * not change. */
1274         rc = llapi_fswap_layouts(fd, fdv, 0, 0, SWAP_LAYOUTS_CLOSE);
1275         if (rc < 0) {
1276                 error_loc = "cannot swap layout";
1277                 goto out;
1278         }
1279
1280 out:
1281         if (fd >= 0)
1282                 close(fd);
1283
1284         if (fdv >= 0)
1285                 close(fdv);
1286 out_closed:
1287         if (rc < 0)
1288                 fprintf(stderr, "error: %s: %s: %s: %s\n",
1289                         progname, name, error_loc, strerror(-rc));
1290         else if (migration_flags & MIGRATION_VERBOSE)
1291                 printf("%s\n", name);
1292
1293         return rc;
1294 }
1295
1296 static int comp_str2flags(char *string, __u32 *flags, __u32 *neg_flags)
1297 {
1298         char *name;
1299
1300         if (string == NULL)
1301                 return -EINVAL;
1302
1303         *flags = 0;
1304         *neg_flags = 0;
1305         for (name = strtok(string, ","); name; name = strtok(NULL, ",")) {
1306                 bool found = false;
1307                 int i;
1308
1309                 for (i = 0; i < ARRAY_SIZE(comp_flags_table); i++) {
1310                         __u32 comp_flag = comp_flags_table[i].cfn_flag;
1311                         const char *comp_name = comp_flags_table[i].cfn_name;
1312
1313                         if (strcmp(name, comp_name) == 0) {
1314                                 *flags |= comp_flag;
1315                                 found = true;
1316                         } else if (strncmp(name, "^", 1) == 0 &&
1317                                    strcmp(name + 1, comp_name) == 0) {
1318                                 *neg_flags |= comp_flag;
1319                                 found = true;
1320                         }
1321                 }
1322                 if (!found) {
1323                         llapi_printf(LLAPI_MSG_ERROR,
1324                                      "%s: component flag '%s' not supported\n",
1325                                      progname, name);
1326                         return -EINVAL;
1327                 }
1328         }
1329
1330         if (!*flags && !*neg_flags)
1331                 return -EINVAL;
1332
1333         /* don't allow to set and exclude the same flag */
1334         if (*flags & *neg_flags)
1335                 return -EINVAL;
1336
1337         return 0;
1338 }
1339
1340 static int mirror_str2state(char *string, __u16 *state, __u16 *neg_state)
1341 {
1342         if (string == NULL)
1343                 return -EINVAL;
1344
1345         *state = 0;
1346         *neg_state = 0;
1347
1348         if (strncmp(string, "^", 1) == 0) {
1349                 *neg_state = llapi_layout_string_flags(string + 1);
1350                 if (*neg_state != 0)
1351                         return 0;
1352         } else {
1353                 *state = llapi_layout_string_flags(string);
1354                 if (*state != 0)
1355                         return 0;
1356         }
1357
1358         llapi_printf(LLAPI_MSG_ERROR,
1359                      "%s: mirrored file state '%s' not supported\n",
1360                      progname, string);
1361         return -EINVAL;
1362 }
1363
1364 /**
1365  * struct mirror_args - Command-line arguments for mirror(s).
1366  * @m_count:  Number of mirrors to be created with this layout.
1367  * @m_flags:  Mirror level flags, only 'prefer' is supported.
1368  * @m_layout: Mirror layout.
1369  * @m_file:   A victim file. Its layout will be split and used as a mirror.
1370  * @m_next:   Point to the next node of the list.
1371  *
1372  * Command-line arguments for mirror(s) will be parsed and stored in
1373  * a linked list that consists of this structure.
1374  */
1375 struct mirror_args {
1376         __u32                   m_count;
1377         __u32                   m_flags;
1378         struct llapi_layout     *m_layout;
1379         const char              *m_file;
1380         struct mirror_args      *m_next;
1381 };
1382
1383 /**
1384  * enum mirror_flags - Flags for extending a mirrored file.
1385  * @MF_NO_VERIFY: Indicates not to verify the mirror(s) from victim file(s)
1386  *             in case the victim file(s) contains the same data as the
1387  *             original mirrored file.
1388  * @MF_DESTROY: Indicates to delete the mirror from the mirrored file.
1389  * @MF_COMP_ID: specified component id instead of mirror id
1390  *
1391  * Flags for extending a mirrored file.
1392  */
1393 enum mirror_flags {
1394         MF_NO_VERIFY    = 0x1,
1395         MF_DESTROY      = 0x2,
1396         MF_COMP_ID      = 0x4,
1397         MF_COMP_POOL    = 0x8,
1398 };
1399
1400 /**
1401  * mirror_create_sanity_check() - Check mirror list.
1402  * @list:  A linked list that stores the mirror arguments.
1403  *
1404  * This function does a sanity check on @list for creating
1405  * a mirrored file.
1406  *
1407  * Return: 0 on success or a negative error code on failure.
1408  */
1409 static int mirror_create_sanity_check(const char *fname,
1410                                       struct mirror_args *list)
1411 {
1412         int rc = 0;
1413         bool has_m_file = false;
1414         bool has_m_layout = false;
1415
1416         if (list == NULL)
1417                 return -EINVAL;
1418
1419         if (fname) {
1420                 struct llapi_layout *layout;
1421
1422                 layout = llapi_layout_get_by_path(fname, 0);
1423                 if (!layout) {
1424                         fprintf(stderr,
1425                                 "error: %s: file '%s' couldn't get layout\n",
1426                                 progname, fname);
1427                         return -ENODATA;
1428                 }
1429
1430                 rc = llapi_layout_sanity(layout, false, true);
1431
1432                 llapi_layout_free(layout);
1433
1434                 if (rc) {
1435                         llapi_layout_sanity_perror(rc);
1436                         return rc;
1437                 }
1438         }
1439
1440         while (list != NULL) {
1441                 if (list->m_file != NULL) {
1442                         has_m_file = true;
1443                         llapi_layout_free(list->m_layout);
1444
1445                         list->m_layout =
1446                                 llapi_layout_get_by_path(list->m_file, 0);
1447                         if (list->m_layout == NULL) {
1448                                 fprintf(stderr,
1449                                         "error: %s: file '%s' has no layout\n",
1450                                         progname, list->m_file);
1451                                 return -ENODATA;
1452                         }
1453                 } else {
1454                         has_m_layout = true;
1455                         if (list->m_layout == NULL) {
1456                                 fprintf(stderr, "error: %s: no mirror layout\n",
1457                                         progname);
1458                                 return -EINVAL;
1459                         }
1460                 }
1461
1462                 rc = llapi_layout_sanity(list->m_layout, false, true);
1463                 if (rc) {
1464                         llapi_layout_sanity_perror(rc);
1465                         return rc;
1466                 }
1467
1468                 list = list->m_next;
1469         }
1470
1471         if (has_m_file && has_m_layout) {
1472                 fprintf(stderr,
1473                         "error: %s: -f <victim_file> option should not be specified with setstripe options\n",
1474                         progname);
1475                 return -EINVAL;
1476         }
1477
1478         return 0;
1479 }
1480
1481 static int mirror_set_flags(struct llapi_layout *layout, void *cbdata)
1482 {
1483         __u32 mirror_flags = *(__u32 *)cbdata;
1484         uint32_t flags;
1485         int rc;
1486
1487         rc = llapi_layout_comp_flags_get(layout, &flags);
1488         if (rc < 0)
1489                 return rc;
1490
1491         if (!flags) {
1492                 rc = llapi_layout_comp_flags_set(layout, mirror_flags);
1493                 if (rc)
1494                         return rc;
1495         }
1496
1497         return LLAPI_LAYOUT_ITER_CONT;
1498 }
1499
1500 /**
1501  * mirror_create() - Create a mirrored file.
1502  * @fname:        The file to be created.
1503  * @mirror_list:  A linked list that stores the mirror arguments.
1504  *
1505  * This function creates a mirrored file @fname with the mirror(s)
1506  * from @mirror_list.
1507  *
1508  * Return: 0 on success or a negative error code on failure.
1509  */
1510 static int mirror_create(char *fname, struct mirror_args *mirror_list)
1511 {
1512         struct llapi_layout *layout = NULL;
1513         struct mirror_args *cur_mirror = NULL;
1514         uint16_t mirror_count = 0;
1515         int i = 0;
1516         int rc = 0;
1517
1518         rc = mirror_create_sanity_check(NULL, mirror_list);
1519         if (rc)
1520                 return rc;
1521
1522         cur_mirror = mirror_list;
1523         while (cur_mirror != NULL) {
1524                 rc = llapi_layout_comp_iterate(cur_mirror->m_layout,
1525                                                mirror_set_flags,
1526                                                &cur_mirror->m_flags);
1527                 if (rc) {
1528                         rc = -errno;
1529                         fprintf(stderr, "%s: failed to set mirror flags\n",
1530                                 progname);
1531                         goto error;
1532                 }
1533
1534                 for (i = 0; i < cur_mirror->m_count; i++) {
1535                         rc = llapi_layout_merge(&layout, cur_mirror->m_layout);
1536                         if (rc) {
1537                                 rc = -errno;
1538                                 fprintf(stderr, "error: %s: "
1539                                         "merge layout failed: %s\n",
1540                                         progname, strerror(errno));
1541                                 goto error;
1542                         }
1543                 }
1544                 mirror_count += cur_mirror->m_count;
1545                 cur_mirror = cur_mirror->m_next;
1546         }
1547
1548         if (layout == NULL) {
1549                 fprintf(stderr, "error: %s: layout is NULL\n", progname);
1550                 return -EINVAL;
1551         }
1552
1553         rc = llapi_layout_mirror_count_set(layout, mirror_count);
1554         if (rc) {
1555                 rc = -errno;
1556                 fprintf(stderr, "error: %s: set mirror count failed: %s\n",
1557                         progname, strerror(errno));
1558                 goto error;
1559         }
1560
1561         rc = lfs_component_create(fname, O_CREAT | O_WRONLY, 0666,
1562                                   layout);
1563         if (rc >= 0) {
1564                 close(rc);
1565                 rc = 0;
1566         }
1567
1568 error:
1569         llapi_layout_free(layout);
1570         return rc;
1571 }
1572
1573 /**
1574  * Compare files and check lease on @fd.
1575  *
1576  * \retval bytes number of bytes are the same
1577  */
1578 static ssize_t mirror_file_compare(int fd, int fdv)
1579 {
1580         const size_t buflen = 4 * 1024 * 1024; /* 4M */
1581         void *buf;
1582         ssize_t bytes_done = 0;
1583         ssize_t bytes_read = 0;
1584
1585         buf = malloc(buflen * 2);
1586         if (!buf)
1587                 return -ENOMEM;
1588
1589         while (1) {
1590                 if (!llapi_lease_check(fd)) {
1591                         bytes_done = -EBUSY;
1592                         break;
1593                 }
1594
1595                 bytes_read = read(fd, buf, buflen);
1596                 if (bytes_read <= 0)
1597                         break;
1598
1599                 if (bytes_read != read(fdv, buf + buflen, buflen))
1600                         break;
1601
1602                 /* XXX: should compute the checksum on each buffer and then
1603                  * compare checksum to avoid cache collision */
1604                 if (memcmp(buf, buf + buflen, bytes_read))
1605                         break;
1606
1607                 bytes_done += bytes_read;
1608         }
1609
1610         free(buf);
1611
1612         return bytes_done;
1613 }
1614
1615 static int mirror_extend_file(const char *fname, const char *victim_file,
1616                               enum mirror_flags mirror_flags)
1617 {
1618         int fd = -1;
1619         int fdv = -1;
1620         struct stat stbuf;
1621         struct stat stbuf_v;
1622         struct ll_ioc_lease *data = NULL;
1623         int rc;
1624
1625         fd = open(fname, O_RDWR);
1626         if (fd < 0) {
1627                 error_loc = "open source file";
1628                 rc = -errno;
1629                 goto out;
1630         }
1631
1632         fdv = open(victim_file, O_RDWR);
1633         if (fdv < 0) {
1634                 error_loc = "open target file";
1635                 rc = -errno;
1636                 goto out;
1637         }
1638
1639         if (fstat(fd, &stbuf) || fstat(fdv, &stbuf_v)) {
1640                 error_loc = "stat source or target file";
1641                 rc = -errno;
1642                 goto out;
1643         }
1644
1645         if (stbuf.st_dev != stbuf_v.st_dev) {
1646                 error_loc = "stat source and target file";
1647                 rc = -EXDEV;
1648                 goto out;
1649         }
1650
1651         /* mirrors should be of the same size */
1652         if (stbuf.st_size != stbuf_v.st_size) {
1653                 error_loc = "file sizes don't match";
1654                 rc = -EINVAL;
1655                 goto out;
1656         }
1657
1658         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
1659         if (rc < 0) {
1660                 error_loc = "cannot get lease";
1661                 goto out;
1662         }
1663
1664         if (!(mirror_flags & MF_NO_VERIFY)) {
1665                 ssize_t ret;
1666                 /* mirrors should have the same contents */
1667                 ret = mirror_file_compare(fd, fdv);
1668                 if (ret != stbuf.st_size) {
1669                         error_loc = "file busy or contents don't match";
1670                         rc = ret < 0 ? ret : -EINVAL;
1671                         goto out;
1672                 }
1673         }
1674
1675         /* Get rid of caching pages from clients */
1676         rc = llapi_file_flush(fd);
1677         if (rc < 0) {
1678                 error_loc = "cannot get data version";
1679                 goto out;
1680         }
1681
1682         rc = llapi_file_flush(fdv);
1683         if (rc < 0) {
1684                 error_loc = "cannot get data version";
1685                 goto out;
1686
1687         }
1688
1689         /* Make sure we keep original atime/mtime values */
1690         rc = migrate_copy_timestamps(fd, fdv);
1691         if (rc < 0) {
1692                 error_loc = "cannot copy timestamp";
1693                 goto out;
1694         }
1695
1696         /* Atomically put lease, merge layouts and close. */
1697         data = calloc(1, offsetof(typeof(*data), lil_ids[1]));
1698         if (!data) {
1699                 error_loc = "memory allocation";
1700                 goto out;
1701         }
1702         data->lil_mode = LL_LEASE_UNLCK;
1703         data->lil_flags = LL_LEASE_LAYOUT_MERGE;
1704         data->lil_count = 1;
1705         data->lil_ids[0] = fdv;
1706         rc = llapi_lease_set(fd, data);
1707         if (rc < 0) {
1708                 error_loc = "cannot merge layout";
1709                 goto out;
1710         } else if (rc == 0) {
1711                 rc = -EBUSY;
1712                 error_loc = "lost lease lock";
1713                 goto out;
1714         }
1715         rc = 0;
1716
1717 out:
1718         if (data)
1719                 free(data);
1720         if (fd >= 0)
1721                 close(fd);
1722         if (fdv >= 0)
1723                 close(fdv);
1724         if (!rc)
1725                 (void) unlink(victim_file);
1726         if (rc < 0)
1727                 fprintf(stderr, "error: %s: %s: %s: %s\n",
1728                         progname, fname, error_loc, strerror(-rc));
1729         return rc;
1730 }
1731
1732 static int mirror_extend_layout(char *name, struct llapi_layout *layout)
1733 {
1734         struct ll_ioc_lease *data = NULL;
1735         int fd = -1;
1736         int fdv = -1;
1737         int rc;
1738
1739         rc = migrate_open_files(name, 0, NULL, layout, &fd, &fdv);
1740         if (rc < 0)
1741                 goto out;
1742
1743         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
1744         if (rc < 0) {
1745                 error_loc = "cannot get lease";
1746                 goto out;
1747         }
1748
1749         rc = migrate_nonblock(fd, fdv);
1750         if (rc < 0) {
1751                 llapi_lease_release(fd);
1752                 goto out;
1753         }
1754
1755         /* Atomically put lease, merge layouts and close. */
1756         data = calloc(1, offsetof(typeof(*data), lil_ids[1]));
1757         if (!data) {
1758                 error_loc = "memory allocation";
1759                 goto out;
1760         }
1761         data->lil_mode = LL_LEASE_UNLCK;
1762         data->lil_flags = LL_LEASE_LAYOUT_MERGE;
1763         data->lil_count = 1;
1764         data->lil_ids[0] = fdv;
1765         rc = llapi_lease_set(fd, data);
1766         if (rc < 0) {
1767                 error_loc = "cannot merge layout";
1768                 goto out;
1769         } else if (rc == 0) {
1770                 rc = -EBUSY;
1771                 error_loc = "lost lease lock";
1772                 goto out;
1773         }
1774         rc = 0;
1775
1776 out:
1777         if (data)
1778                 free(data);
1779         if (fd >= 0)
1780                 close(fd);
1781         if (fdv >= 0)
1782                 close(fdv);
1783         if (rc < 0)
1784                 fprintf(stderr, "error: %s: %s: %s: %s\n",
1785                         progname, name, error_loc, strerror(-rc));
1786         return rc;
1787 }
1788
1789 static int mirror_extend(char *fname, struct mirror_args *mirror_list,
1790                          enum mirror_flags mirror_flags)
1791 {
1792         int rc;
1793
1794         rc = mirror_create_sanity_check(fname, mirror_list);
1795         if (rc)
1796                 return rc;
1797
1798         while (mirror_list) {
1799                 if (mirror_list->m_file != NULL) {
1800                         rc = mirror_extend_file(fname, mirror_list->m_file,
1801                                                 mirror_flags);
1802                 } else {
1803                         __u32 mirror_count = mirror_list->m_count;
1804
1805                         while (mirror_count > 0) {
1806                                 rc = mirror_extend_layout(fname,
1807                                                         mirror_list->m_layout);
1808                                 if (rc)
1809                                         break;
1810
1811                                 --mirror_count;
1812                         }
1813                 }
1814                 if (rc)
1815                         break;
1816
1817                 mirror_list = mirror_list->m_next;
1818         }
1819
1820         return rc;
1821 }
1822
1823 static int find_mirror_id(struct llapi_layout *layout, void *cbdata)
1824 {
1825         uint32_t id;
1826         int rc;
1827
1828         rc = llapi_layout_mirror_id_get(layout, &id);
1829         if (rc < 0)
1830                 return rc;
1831
1832         if ((__u16)id == *(__u16 *)cbdata)
1833                 return LLAPI_LAYOUT_ITER_STOP;
1834
1835         return LLAPI_LAYOUT_ITER_CONT;
1836 }
1837
1838 static int find_comp_id(struct llapi_layout *layout, void *cbdata)
1839 {
1840         uint32_t id;
1841         int rc;
1842
1843         rc = llapi_layout_comp_id_get(layout, &id);
1844         if (rc < 0)
1845                 return rc;
1846
1847         if (id == *(__u32 *)cbdata)
1848                 return LLAPI_LAYOUT_ITER_STOP;
1849
1850         return LLAPI_LAYOUT_ITER_CONT;
1851 }
1852
1853 struct pool_to_id_cbdata {
1854         const char *pool;
1855         __u32 id;
1856 };
1857 static int find_comp_id_by_pool(struct llapi_layout *layout, void *cbdata)
1858 {
1859         char buf[LOV_MAXPOOLNAME + 1];
1860         struct pool_to_id_cbdata *d = (void *)cbdata;
1861         uint32_t id;
1862         int rc;
1863
1864         rc = llapi_layout_pool_name_get(layout, buf, sizeof(buf));
1865         if (rc < 0)
1866                 return rc;
1867         if (strcmp(d->pool, buf))
1868                 return LLAPI_LAYOUT_ITER_CONT;
1869
1870         rc = llapi_layout_mirror_id_get(layout, &id);
1871         if (rc < 0)
1872                 return rc;
1873         d->id = id;
1874
1875         return LLAPI_LAYOUT_ITER_STOP;
1876 }
1877
1878 struct collect_ids_data {
1879         __u16   *cid_ids;
1880         int     cid_count;
1881         __u16   cid_exclude;
1882 };
1883
1884 static int collect_mirror_id(struct llapi_layout *layout, void *cbdata)
1885 {
1886         struct collect_ids_data *cid = cbdata;
1887         uint32_t id;
1888         int rc;
1889
1890         rc = llapi_layout_mirror_id_get(layout, &id);
1891         if (rc < 0)
1892                 return rc;
1893
1894         if ((__u16)id != cid->cid_exclude) {
1895                 int i;
1896
1897                 for (i = 0; i < cid->cid_count; i++) {
1898                         /* already collected the mirror id */
1899                         if (id == cid->cid_ids[i])
1900                                 return LLAPI_LAYOUT_ITER_CONT;
1901                 }
1902                 cid->cid_ids[cid->cid_count] = id;
1903                 cid->cid_count++;
1904         }
1905
1906         return LLAPI_LAYOUT_ITER_CONT;
1907 }
1908
1909 /**
1910  * last_non_stale_mirror() - Check if a mirror is the last non-stale mirror.
1911  * @mirror_id: Mirror id to be checked.
1912  * @layout:    Mirror component list.
1913  *
1914  * This function checks if a mirror with specified @mirror_id is the last
1915  * non-stale mirror of a layout @layout.
1916  *
1917  * Return: true or false.
1918  */
1919 static inline
1920 bool last_non_stale_mirror(__u16 mirror_id, struct llapi_layout *layout)
1921 {
1922         __u16 mirror_ids[128] = { 0 };
1923         struct collect_ids_data cid = { .cid_ids = mirror_ids,
1924                                         .cid_count = 0,
1925                                         .cid_exclude = mirror_id, };
1926         int i;
1927
1928         llapi_layout_comp_iterate(layout, collect_mirror_id, &cid);
1929
1930         for (i = 0; i < cid.cid_count; i++) {
1931                 struct llapi_resync_comp comp_array[1024] = { { 0 } };
1932                 int comp_size = 0;
1933
1934                 comp_size = llapi_mirror_find_stale(layout, comp_array,
1935                                                     ARRAY_SIZE(comp_array),
1936                                                     &mirror_ids[i], 1);
1937                 if (comp_size == 0)
1938                         return false;
1939         }
1940
1941         return true;
1942 }
1943
1944 static int mirror_split(const char *fname, __u32 id, const char *pool,
1945                         enum mirror_flags mflags, const char *victim_file)
1946 {
1947         struct llapi_layout *layout;
1948         char parent[PATH_MAX];
1949         char victim[PATH_MAX];
1950         int flags = O_CREAT | O_EXCL | O_LOV_DELAY_CREATE | O_NOFOLLOW;
1951         char *ptr;
1952         struct ll_ioc_lease *data;
1953         uint16_t mirror_count;
1954         int mdt_index;
1955         int fd, fdv;
1956         int rc;
1957
1958         /* check fname contains mirror with mirror_id/comp_id */
1959         layout = llapi_layout_get_by_path(fname, 0);
1960         if (!layout) {
1961                 fprintf(stderr,
1962                         "error %s: file '%s' couldn't get layout\n",
1963                         progname, fname);
1964                 return -EINVAL;
1965         }
1966
1967         rc = llapi_layout_sanity(layout, false, true);
1968         if (rc) {
1969                 llapi_layout_sanity_perror(rc);
1970                 goto free_layout;
1971         }
1972
1973         rc = llapi_layout_mirror_count_get(layout, &mirror_count);
1974         if (rc) {
1975                 fprintf(stderr,
1976                         "error %s: file '%s' couldn't get mirror count\n",
1977                         progname, fname);
1978                 goto free_layout;
1979         }
1980         if (mirror_count < 2) {
1981                 fprintf(stderr,
1982                         "error %s: file '%s' has %d component, cannot split\n",
1983                         progname, fname, mirror_count);
1984                 goto free_layout;
1985         }
1986
1987         if (mflags & MF_COMP_POOL) {
1988                 struct pool_to_id_cbdata data = { .pool = pool };
1989
1990                 rc = llapi_layout_comp_iterate(layout, find_comp_id_by_pool,
1991                                                &data);
1992                 id = data.id;
1993         } else if (mflags & MF_COMP_ID) {
1994                 rc = llapi_layout_comp_iterate(layout, find_comp_id, &id);
1995                 id = mirror_id_of(id);
1996         } else {
1997                 rc = llapi_layout_comp_iterate(layout, find_mirror_id, &id);
1998         }
1999         if (rc < 0) {
2000                 fprintf(stderr, "error %s: failed to iterate layout of '%s'\n",
2001                         progname, fname);
2002                 goto free_layout;
2003         } else if (rc == LLAPI_LAYOUT_ITER_CONT) {
2004                 fprintf(stderr,
2005                      "error %s: file '%s' does not contain mirror with id %u\n",
2006                         progname, fname, id);
2007                 goto free_layout;
2008         }
2009
2010         fd = open(fname, O_RDWR);
2011         if (fd < 0) {
2012                 fprintf(stderr,
2013                         "error %s: open file '%s' failed: %s\n",
2014                         progname, fname, strerror(errno));
2015                 goto free_layout;
2016         }
2017
2018         /* get victim file directory pathname */
2019         if (strlen(fname) > sizeof(parent) - 1) {
2020                 fprintf(stderr, "error %s: file name of '%s' too long\n",
2021                         progname, fname);
2022                 rc = -ERANGE;
2023                 goto close_fd;
2024         }
2025         strncpy(parent, fname, sizeof(parent));
2026         ptr = strrchr(parent, '/');
2027         if (ptr == NULL) {
2028                 if (getcwd(parent, sizeof(parent)) == NULL) {
2029                         fprintf(stderr, "error %s: getcwd failed: %s\n",
2030                                 progname, strerror(errno));
2031                         rc = -errno;
2032                         goto close_fd;
2033                 }
2034         } else {
2035                 if (ptr == parent)
2036                         ptr = parent + 1;
2037                 *ptr = '\0';
2038         }
2039
2040         rc = llapi_file_fget_mdtidx(fd, &mdt_index);
2041         if (rc < 0) {
2042                 fprintf(stderr, "%s: cannot get MDT index of '%s'\n",
2043                         progname, fname);
2044                 goto close_fd;
2045         }
2046
2047         if (victim_file == NULL) {
2048                 /* use a temp file to store the splitted layout */
2049                 if (mflags & MF_DESTROY) {
2050                         if (last_non_stale_mirror(id, layout)) {
2051                                 rc = -EUCLEAN;
2052                                 fprintf(stderr,
2053                                         "%s: cannot destroy the last non-stale mirror of file '%s'\n",
2054                                         progname, fname);
2055                                 goto close_fd;
2056                         }
2057
2058                         fdv = llapi_create_volatile_idx(parent, mdt_index,
2059                                                         O_LOV_DELAY_CREATE);
2060                 } else {
2061                         snprintf(victim, sizeof(victim), "%s.mirror~%u",
2062                                  fname, id);
2063                         fdv = open(victim, flags, S_IRUSR | S_IWUSR);
2064                 }
2065         } else {
2066                 /* user specified victim file */
2067                 fdv = open(victim_file, flags, S_IRUSR | S_IWUSR);
2068         }
2069
2070         if (fdv < 0) {
2071                 fprintf(stderr,
2072                         "error %s: create victim file failed: %s\n",
2073                         progname, strerror(errno));
2074                 goto close_fd;
2075         }
2076
2077         /* get lease lock of fname */
2078         rc = llapi_lease_acquire(fd, LL_LEASE_WRLCK);
2079         if (rc < 0) {
2080                 fprintf(stderr,
2081                         "error %s: cannot get lease of file '%s': %d\n",
2082                         progname, fname, rc);
2083                 goto close_victim;
2084         }
2085
2086         /* Atomatically put lease, split layouts and close. */
2087         data = malloc(offsetof(typeof(*data), lil_ids[2]));
2088         if (!data) {
2089                 rc = -ENOMEM;
2090                 goto close_victim;
2091         }
2092
2093         data->lil_mode = LL_LEASE_UNLCK;
2094         data->lil_flags = LL_LEASE_LAYOUT_SPLIT;
2095         data->lil_count = 2;
2096         data->lil_ids[0] = fdv;
2097         data->lil_ids[1] = id;
2098         rc = llapi_lease_set(fd, data);
2099         if (rc <= 0) {
2100                 if (rc == 0) /* lost lease lock */
2101                         rc = -EBUSY;
2102                 fprintf(stderr,
2103                         "error %s: cannot split '%s': %s\n",
2104                         progname, fname, strerror(-rc));
2105         } else {
2106                 rc = 0;
2107         }
2108         free(data);
2109
2110 close_victim:
2111         close(fdv);
2112 close_fd:
2113         close(fd);
2114 free_layout:
2115         llapi_layout_free(layout);
2116         return rc;
2117 }
2118
2119 static inline
2120 int lfs_mirror_resync_file(const char *fname, struct ll_ioc_lease *ioc,
2121                            __u16 *mirror_ids, int ids_nr);
2122
2123 static int lfs_migrate_to_dom(int fd, int fdv, char *name,
2124                               __u64 migration_flags,
2125                               struct llapi_stripe_param *param,
2126                               struct llapi_layout *layout)
2127 {
2128         struct ll_ioc_lease *data = NULL;
2129         int rc;
2130
2131         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
2132         if (rc < 0) {
2133                 error_loc = "cannot get lease";
2134                 goto out_close;
2135         }
2136
2137         /* Atomically put lease, merge layouts, resync and close. */
2138         data = calloc(1, offsetof(typeof(*data), lil_ids[1024]));
2139         if (!data) {
2140                 error_loc = "memory allocation";
2141                 goto out_close;
2142         }
2143         data->lil_mode = LL_LEASE_UNLCK;
2144         data->lil_flags = LL_LEASE_LAYOUT_MERGE;
2145         data->lil_count = 1;
2146         data->lil_ids[0] = fdv;
2147         rc = llapi_lease_set(fd, data);
2148         if (rc < 0) {
2149                 error_loc = "cannot merge layout";
2150                 goto out_close;
2151         } else if (rc == 0) {
2152                 rc = -EBUSY;
2153                 error_loc = "lost lease lock";
2154                 goto out_close;
2155         }
2156         close(fd);
2157         close(fdv);
2158
2159         rc = lfs_mirror_resync_file(name, data, NULL, 0);
2160         if (rc) {
2161                 error_loc = "cannot resync file";
2162                 goto out;
2163         }
2164
2165         /* delete first mirror now */
2166         rc = mirror_split(name, 1, NULL, MF_DESTROY, NULL);
2167         if (rc < 0)
2168                 error_loc = "cannot delete old layout";
2169         goto out;
2170
2171 out_close:
2172         close(fd);
2173         close(fdv);
2174 out:
2175         if (rc < 0)
2176                 fprintf(stderr, "error: %s: %s: %s: %s\n",
2177                         progname, name, error_loc, strerror(-rc));
2178         else if (migration_flags & MIGRATION_VERBOSE)
2179                 printf("%s\n", name);
2180         if (data)
2181                 free(data);
2182         return rc;
2183 }
2184
2185 /**
2186  * Parse a string containing an target index list into an array of integers.
2187  *
2188  * The input string contains a comma delimited list of individual
2189  * indices and ranges, for example "1,2-4,7". Add the indices into the
2190  * \a tgts array and remove duplicates.
2191  *
2192  * \param[out] tgts             array to store indices in
2193  * \param[in] size              size of \a tgts array
2194  * \param[in] offset            starting index in \a tgts
2195  * \param[in] arg               string containing OST index list
2196  * \param[in/out] overstriping  index list may contain duplicates
2197  *
2198  * \retval positive    number of indices in \a tgts
2199  * \retval -EINVAL     unable to parse \a arg
2200  */
2201 static int parse_targets(__u32 *tgts, int size, int offset, char *arg,
2202                          unsigned long long *pattern)
2203 {
2204         int rc;
2205         int nr = offset;
2206         int slots = size - offset;
2207         char *ptr = NULL;
2208         bool overstriped = false;
2209         bool end_of_loop;
2210
2211         if (arg == NULL)
2212                 return -EINVAL;
2213
2214         end_of_loop = false;
2215         while (!end_of_loop) {
2216                 int start_index = 0;
2217                 int end_index = 0;
2218                 int i;
2219                 char *endptr = NULL;
2220
2221                 rc = -EINVAL;
2222
2223                 ptr = strchrnul(arg, ',');
2224
2225                 end_of_loop = *ptr == '\0';
2226                 *ptr = '\0';
2227
2228                 start_index = strtol(arg, &endptr, 0);
2229                 if (endptr == arg) /* no data at all */
2230                         break;
2231                 if (*endptr != '-' && *endptr != '\0') /* has invalid data */
2232                         break;
2233
2234                 end_index = start_index;
2235                 if (*endptr == '-') {
2236                         end_index = strtol(endptr + 1, &endptr, 0);
2237                         if (*endptr != '\0')
2238                                 break;
2239                         if (end_index < start_index)
2240                                 break;
2241                 }
2242
2243                 for (i = start_index; i <= end_index && slots > 0; i++) {
2244                         int j;
2245
2246                         /* remove duplicate */
2247                         for (j = 0; j < offset; j++) {
2248                                 if (tgts[j] == i && pattern &&
2249                                     *pattern == LLAPI_LAYOUT_OVERSTRIPING)
2250                                         overstriped = true;
2251                                 else if (tgts[j] == i)
2252                                         return -EINVAL;
2253                         }
2254
2255                         j = offset;
2256
2257                         if (j == offset) { /* check complete */
2258                                 tgts[nr++] = i;
2259                                 --slots;
2260                         }
2261                 }
2262
2263                 if (slots == 0 && i < end_index)
2264                         break;
2265
2266                 *ptr = ',';
2267                 arg = ++ptr;
2268                 offset = nr;
2269                 rc = 0;
2270         }
2271         if (!end_of_loop && ptr != NULL)
2272                 *ptr = ',';
2273
2274         if (!overstriped && pattern)
2275                 *pattern = LLAPI_LAYOUT_DEFAULT;
2276
2277         return rc < 0 ? rc : nr;
2278 }
2279
2280 struct lfs_setstripe_args {
2281         unsigned long long       lsa_comp_end;
2282         unsigned long long       lsa_stripe_size;
2283         unsigned long long       lsa_extension_size;
2284         long long                lsa_stripe_count;
2285         long long                lsa_stripe_off;
2286         __u32                    lsa_comp_flags;
2287         __u32                    lsa_comp_neg_flags;
2288         unsigned long long       lsa_pattern;
2289         unsigned int             lsa_mirror_count;
2290         int                      lsa_nr_tgts;
2291         bool                     lsa_first_comp;
2292         bool                     lsa_extension_comp;
2293         __u32                   *lsa_tgts;
2294         char                    *lsa_pool_name;
2295 };
2296
2297 static inline void setstripe_args_init(struct lfs_setstripe_args *lsa)
2298 {
2299         unsigned int mirror_count = lsa->lsa_mirror_count;
2300         bool first_comp = lsa->lsa_first_comp;
2301
2302         memset(lsa, 0, sizeof(*lsa));
2303
2304         lsa->lsa_stripe_size = LLAPI_LAYOUT_DEFAULT;
2305         lsa->lsa_stripe_count = LLAPI_LAYOUT_DEFAULT;
2306         lsa->lsa_stripe_off = LLAPI_LAYOUT_DEFAULT;
2307         lsa->lsa_pattern = LLAPI_LAYOUT_RAID0;
2308         lsa->lsa_pool_name = NULL;
2309
2310         lsa->lsa_mirror_count = mirror_count;
2311         lsa->lsa_first_comp = first_comp;
2312 }
2313
2314 /**
2315  * setstripe_args_init_inherit() - Initialize and inherit stripe options.
2316  * @lsa: Stripe options to be initialized and inherited.
2317  *
2318  * This function initializes stripe options in @lsa and inherit
2319  * stripe_size, stripe_count and OST pool_name options.
2320  *
2321  * Return: void.
2322  */
2323 static inline void setstripe_args_init_inherit(struct lfs_setstripe_args *lsa)
2324 {
2325         unsigned long long stripe_size;
2326         long long stripe_count;
2327         char *pool_name = NULL;
2328
2329         stripe_size = lsa->lsa_stripe_size;
2330         stripe_count = lsa->lsa_stripe_count;
2331         pool_name = lsa->lsa_pool_name;
2332
2333         setstripe_args_init(lsa);
2334
2335         lsa->lsa_stripe_size = stripe_size;
2336         lsa->lsa_stripe_count = stripe_count;
2337         lsa->lsa_pool_name = pool_name;
2338 }
2339
2340 static inline bool setstripe_args_specified(struct lfs_setstripe_args *lsa)
2341 {
2342         return (lsa->lsa_stripe_size != LLAPI_LAYOUT_DEFAULT ||
2343                 lsa->lsa_stripe_count != LLAPI_LAYOUT_DEFAULT ||
2344                 lsa->lsa_stripe_off != LLAPI_LAYOUT_DEFAULT ||
2345                 lsa->lsa_pattern != LLAPI_LAYOUT_RAID0 ||
2346                 lsa->lsa_comp_end != 0);
2347 }
2348
2349 /**
2350  * comp_args_to_layout() - Create or extend a composite layout.
2351  * @composite:       Pointer to the composite layout.
2352  * @lsa:             Stripe options for the new component.
2353  *
2354  * This function creates or extends a composite layout by adding a new
2355  * component with stripe options from @lsa.
2356  *
2357  * Return: 0 on success or an error code on failure.
2358  */
2359 static int comp_args_to_layout(struct llapi_layout **composite,
2360                                struct lfs_setstripe_args *lsa,
2361                                bool set_extent)
2362 {
2363         struct llapi_layout *layout = *composite;
2364         uint64_t prev_end = 0;
2365         uint64_t size;
2366         int i = 0, rc;
2367
2368 new_comp:
2369         if (layout == NULL) {
2370                 layout = llapi_layout_alloc();
2371                 if (layout == NULL) {
2372                         fprintf(stderr, "Alloc llapi_layout failed. %s\n",
2373                                 strerror(errno));
2374                         errno = ENOMEM;
2375                         return -1;
2376                 }
2377                 *composite = layout;
2378                 lsa->lsa_first_comp = true;
2379         } else {
2380                 uint64_t start;
2381
2382                 /* Get current component extent, current component
2383                  * must be the tail component. */
2384                 rc = llapi_layout_comp_extent_get(layout, &start, &prev_end);
2385                 if (rc) {
2386                         fprintf(stderr, "Get comp extent failed. %s\n",
2387                                 strerror(errno));
2388                         return rc;
2389                 }
2390
2391                 if (lsa->lsa_first_comp)
2392                         prev_end = 0;
2393
2394                 if (lsa->lsa_first_comp)
2395                         rc = llapi_layout_add_first_comp(layout);
2396                 else
2397                         rc = llapi_layout_comp_add(layout);
2398                 if (rc) {
2399                         fprintf(stderr, "Add component failed. %s\n",
2400                                 strerror(errno));
2401                         return rc;
2402                 }
2403         }
2404
2405         rc = llapi_layout_comp_flags_set(layout, lsa->lsa_comp_flags);
2406         if (rc) {
2407                 fprintf(stderr, "Set flags 0x%x failed: %s\n",
2408                         lsa->lsa_comp_flags, strerror(errno));
2409                 return rc;
2410         }
2411
2412         if (set_extent) {
2413                 uint64_t comp_end = lsa->lsa_comp_end;
2414
2415                 /* The extendable component is 0-length, so it can be removed
2416                  * if there is insufficient space to extend it. */
2417                 if (lsa->lsa_extension_comp)
2418                         comp_end = prev_end;
2419
2420                 rc = llapi_layout_comp_extent_set(layout, prev_end,
2421                                                   comp_end);
2422                 if (rc) {
2423                         fprintf(stderr, "Set extent [%lu, %lu) failed. %s\n",
2424                                 prev_end, comp_end, strerror(errno));
2425                         return rc;
2426                 }
2427         }
2428         /* reset lsa_first_comp */
2429         lsa->lsa_first_comp = false;
2430
2431         /* Data-on-MDT component setting */
2432         if (lsa->lsa_pattern == LLAPI_LAYOUT_MDT) {
2433                 /* In case of Data-on-MDT patterns the only extra option
2434                  * applicable is stripe size option. */
2435                 if (lsa->lsa_stripe_count != LLAPI_LAYOUT_DEFAULT) {
2436                         fprintf(stderr, "Option 'stripe-count' can't be "
2437                                 "specified with Data-on-MDT component: %lld\n",
2438                                 lsa->lsa_stripe_count);
2439                         errno = EINVAL;
2440                         return -1;
2441                 }
2442                 if (lsa->lsa_stripe_size != LLAPI_LAYOUT_DEFAULT) {
2443                         fprintf(stderr, "Option 'stripe-size' can't be "
2444                                 "specified with Data-on-MDT component: %llu\n",
2445                                 lsa->lsa_stripe_size);
2446                         errno = EINVAL;
2447                         return -1;
2448                 }
2449                 if (lsa->lsa_nr_tgts != 0) {
2450                         fprintf(stderr, "Option 'ost-list' can't be specified "
2451                                 "with Data-on-MDT component: '%i'\n",
2452                                 lsa->lsa_nr_tgts);
2453                         errno = EINVAL;
2454                         return -1;
2455                 }
2456                 if (lsa->lsa_stripe_off != LLAPI_LAYOUT_DEFAULT) {
2457                         fprintf(stderr, "Option 'stripe-offset' can't be "
2458                                 "specified with Data-on-MDT component: %lld\n",
2459                                 lsa->lsa_stripe_off);
2460                         errno = EINVAL;
2461                         return -1;
2462                 }
2463                 if (lsa->lsa_pool_name != 0) {
2464                         fprintf(stderr, "Option 'pool' can't be specified "
2465                                 "with Data-on-MDT component: '%s'\n",
2466                                 lsa->lsa_pool_name);
2467                         errno = EINVAL;
2468                         return -1;
2469                 }
2470
2471                 rc = llapi_layout_pattern_set(layout, lsa->lsa_pattern);
2472                 if (rc) {
2473                         fprintf(stderr, "Set stripe pattern %#llx failed. %s\n",
2474                                 lsa->lsa_pattern,
2475                                 strerror(errno));
2476                         return rc;
2477                 }
2478                 /* Data-on-MDT component has always single stripe up to end */
2479                 lsa->lsa_stripe_size = lsa->lsa_comp_end;
2480         } else if (lsa->lsa_pattern == LLAPI_LAYOUT_OVERSTRIPING) {
2481                 rc = llapi_layout_pattern_set(layout, lsa->lsa_pattern);
2482                 if (rc) {
2483                         fprintf(stderr, "Set stripe pattern %#llx failed. %s\n",
2484                                 lsa->lsa_pattern,
2485                                 strerror(errno));
2486                         return rc;
2487                 }
2488         }
2489
2490         size = lsa->lsa_comp_flags & LCME_FL_EXTENSION ?
2491                 lsa->lsa_extension_size : lsa->lsa_stripe_size;
2492
2493         if (lsa->lsa_comp_flags & LCME_FL_EXTENSION)
2494                 rc = llapi_layout_extension_size_set(layout, size);
2495         else
2496                 rc = llapi_layout_stripe_size_set(layout, size);
2497
2498         if (rc) {
2499                 fprintf(stderr, "Set stripe size %lu failed: %s\n",
2500                         size, strerror(errno));
2501                 return rc;
2502         }
2503
2504         rc = llapi_layout_stripe_count_set(layout, lsa->lsa_stripe_count);
2505         if (rc) {
2506                 fprintf(stderr, "Set stripe count %lld failed: %s\n",
2507                         lsa->lsa_stripe_count, strerror(errno));
2508                 return rc;
2509         }
2510
2511         if (lsa->lsa_pool_name != NULL) {
2512                 rc = llapi_layout_pool_name_set(layout, lsa->lsa_pool_name);
2513                 if (rc) {
2514                         fprintf(stderr, "Set pool name: %s failed. %s\n",
2515                                 lsa->lsa_pool_name, strerror(errno));
2516                         return rc;
2517                 }
2518         } else {
2519                 rc = llapi_layout_pool_name_set(layout, "");
2520                 if (rc) {
2521                         fprintf(stderr, "Clear pool name failed: %s\n",
2522                                 strerror(errno));
2523                         return rc;
2524                 }
2525         }
2526
2527         if (lsa->lsa_nr_tgts > 0) {
2528                 if (lsa->lsa_stripe_count > 0 &&
2529                     lsa->lsa_stripe_count != LLAPI_LAYOUT_DEFAULT &&
2530                     lsa->lsa_stripe_count != LLAPI_LAYOUT_WIDE &&
2531                     lsa->lsa_nr_tgts != lsa->lsa_stripe_count) {
2532                         fprintf(stderr, "stripe_count(%lld) != nr_tgts(%d)\n",
2533                                 lsa->lsa_stripe_count,
2534                                 lsa->lsa_nr_tgts);
2535                         errno = EINVAL;
2536                         return -1;
2537                 }
2538                 for (i = 0; i < lsa->lsa_nr_tgts; i++) {
2539                         rc = llapi_layout_ost_index_set(layout, i,
2540                                                         lsa->lsa_tgts[i]);
2541                         if (rc)
2542                                 break;
2543                 }
2544         } else if (lsa->lsa_stripe_off != LLAPI_LAYOUT_DEFAULT &&
2545                    lsa->lsa_stripe_off != -1) {
2546                 rc = llapi_layout_ost_index_set(layout, 0, lsa->lsa_stripe_off);
2547         }
2548         if (rc) {
2549                 fprintf(stderr, "Set ost index %d failed. %s\n",
2550                         i, strerror(errno));
2551                 return rc;
2552         }
2553
2554         /* Create the second, virtual component of extension space */
2555         if (lsa->lsa_extension_comp) {
2556                 lsa->lsa_comp_flags |= LCME_FL_EXTENSION;
2557                 lsa->lsa_extension_comp = false;
2558                 goto new_comp;
2559         }
2560
2561         return rc;
2562 }
2563
2564 static int build_component(struct llapi_layout **layout,
2565                            struct lfs_setstripe_args *lsa, bool set_extent)
2566 {
2567         int rc;
2568
2569         rc = comp_args_to_layout(layout, lsa, set_extent);
2570         if (rc)
2571                 return rc;
2572
2573         if (lsa->lsa_mirror_count > 0) {
2574                 rc = llapi_layout_mirror_count_set(*layout,
2575                                                    lsa->lsa_mirror_count);
2576                 if (rc)
2577                         return rc;
2578
2579                 rc = llapi_layout_flags_set(*layout, LCM_FL_RDONLY);
2580                 if (rc)
2581                         return rc;
2582                 lsa->lsa_mirror_count = 0;
2583         }
2584
2585         return rc;
2586 }
2587
2588 static int build_layout_from_yaml_node(struct cYAML *node,
2589                                        struct llapi_layout **layout,
2590                                        struct lfs_setstripe_args *lsa,
2591                                        __u32 *osts)
2592 {
2593         char *string;
2594         int rc = 0;
2595
2596         while (node) {
2597                 if (node->cy_type == CYAML_TYPE_OBJECT) {
2598                         /* go deep to sub blocks */
2599                         rc = build_layout_from_yaml_node(node->cy_child, layout,
2600                                                          lsa, osts);
2601                         if (rc)
2602                                 return rc;
2603                 } else {
2604                         if (node->cy_string == NULL)
2605                                 return -EINVAL;
2606
2607                         string = node->cy_string;
2608                         /* skip leading lmm_ if present, to simplify parsing */
2609                         if (strncmp(string, "lmm_", 4) == 0)
2610                                 string += 4;
2611
2612                         if (node->cy_type == CYAML_TYPE_STRING) {
2613                                 if (!strcmp(string, "lcme_extent.e_end")) {
2614                                         if (!strcmp(node->cy_valuestring, "EOF") ||
2615                                             !strcmp(node->cy_valuestring, "eof"))
2616                                                 lsa->lsa_comp_end = LUSTRE_EOF;
2617                                 } else if (!strcmp(string, "pool")) {
2618                                         lsa->lsa_pool_name = node->cy_valuestring;
2619                                 } else if (!strcmp(string, "pattern")) {
2620                                         if (!strcmp(node->cy_valuestring, "mdt"))
2621                                                 lsa->lsa_pattern = LLAPI_LAYOUT_MDT;
2622                                         if (!strcmp(node->cy_valuestring,
2623                                                     "raid0,overstriped"))
2624                                                 lsa->lsa_pattern =
2625                                                         LLAPI_LAYOUT_OVERSTRIPING;
2626                                 } else if (!strcmp(string, "lcme_flags")) {
2627                                         rc = comp_str2flags(node->cy_valuestring,
2628                                                             &lsa->lsa_comp_flags,
2629                                                             &lsa->lsa_comp_neg_flags);
2630                                         if (rc)
2631                                                 return rc;
2632                                         /* Only template flags have meaning in
2633                                          * the layout for a new file
2634                                          */
2635                                         lsa->lsa_comp_flags &= LCME_TEMPLATE_FLAGS;
2636                                 }
2637                         } else if (node->cy_type == CYAML_TYPE_NUMBER) {
2638                                 if (!strcmp(string, "lcm_mirror_count")) {
2639                                         lsa->lsa_mirror_count = node->cy_valueint;
2640                                 } else if (!strcmp(string, "lcme_extent.e_start")) {
2641                                         if (node->cy_valueint != 0 || *layout != NULL) {
2642                                                 rc = build_component(layout, lsa, true);
2643                                                 if (rc)
2644                                                         return rc;
2645                                         }
2646
2647                                         if (node->cy_valueint == 0)
2648                                                 lsa->lsa_first_comp = true;
2649
2650                                         /* initialize lsa */
2651                                         setstripe_args_init(lsa);
2652                                         lsa->lsa_tgts = osts;
2653                                 } else if (!strcmp(string, "lcme_extent.e_end")) {
2654                                         if (node->cy_valueint == -1)
2655                                                 lsa->lsa_comp_end = LUSTRE_EOF;
2656                                         else
2657                                                 lsa->lsa_comp_end = node->cy_valueint;
2658                                 } else if (!strcmp(string, "stripe_count")) {
2659                                         lsa->lsa_stripe_count = node->cy_valueint;
2660                                 } else if (!strcmp(string, "stripe_size")) {
2661                                         lsa->lsa_stripe_size = node->cy_valueint;
2662                                 } else if (!strcmp(string, "stripe_offset")) {
2663                                         lsa->lsa_stripe_off = node->cy_valueint;
2664                                 } else if (!strcmp(string, "l_ost_idx")) {
2665                                         osts[lsa->lsa_nr_tgts] = node->cy_valueint;
2666                                         lsa->lsa_nr_tgts++;
2667                                 }
2668                         }
2669                 }
2670                 node = node->cy_next;
2671         }
2672
2673         return rc;
2674 }
2675
2676 static int lfs_comp_create_from_yaml(char *template,
2677                                      struct llapi_layout **layout,
2678                                      struct lfs_setstripe_args *lsa,
2679                                      __u32 *osts)
2680 {
2681         struct cYAML *tree = NULL, *err_rc = NULL;
2682         int rc = 0;
2683
2684         tree = cYAML_build_tree(template, NULL, 0, &err_rc, false);
2685         if (!tree) {
2686                 fprintf(stderr, "%s: cannot parse YAML file %s\n",
2687                         progname, template);
2688                 cYAML_build_error(-EINVAL, -1, "yaml", "from comp yaml",
2689                                   "can't parse", &err_rc);
2690                 cYAML_print_tree2file(stderr, err_rc);
2691                 cYAML_free_tree(err_rc);
2692                 rc = -EINVAL;
2693                 goto err;
2694         }
2695
2696         /* initialize lsa for plain file */
2697         setstripe_args_init(lsa);
2698         lsa->lsa_tgts = osts;
2699
2700         rc = build_layout_from_yaml_node(tree, layout, lsa, osts);
2701         if (rc) {
2702                 fprintf(stderr, "%s: cannot build layout from YAML file %s.\n",
2703                         progname, template);
2704                 goto err;
2705         } else {
2706                 rc = build_component(layout, lsa, *layout != NULL);
2707         }
2708         /* clean clean lsa */
2709         setstripe_args_init(lsa);
2710
2711 err:
2712         if (tree)
2713                 cYAML_free_tree(tree);
2714         return rc;
2715 }
2716
2717 /**
2718  * Get the extension size from the next (SEL) component and extend the
2719  * current component on it. The start of the next component is to be
2720  * adjusted as well.
2721  *
2722  * \param[in] layout    the current layout
2723  * \param[in] start     the start of the current component
2724  * \param[in,out] end   the end of the current component
2725  * \param[in] offset    the offset to adjust the end position to instead of
2726  *                      extension size
2727  *
2728  * \retval 0            - extended successfully
2729  * \retval < 0          - error
2730  */
2731 static int layout_extend_comp(struct llapi_layout *layout,
2732                               uint64_t start, uint64_t *end,
2733                               uint64_t offset)
2734 {
2735         uint64_t size, next_start, next_end;
2736         int rc;
2737
2738         rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_NEXT);
2739         if (rc < 0) {
2740                 fprintf(stderr, "%s setstripe: cannot move component cursor: "
2741                         "%s\n", progname, strerror(errno));
2742                 return rc;
2743         }
2744
2745         /* Even if the @size will not be used below, this will fail if
2746          * this is not a SEL component - a good confirmation we are
2747          * working on right components. */
2748         rc = llapi_layout_extension_size_get(layout, &size);
2749         if (rc < 0) {
2750                 fprintf(stderr, "%s setstripe: cannot get component ext size: "
2751                         "%s\n", progname, strerror(errno));
2752                 return rc;
2753         }
2754
2755         rc = llapi_layout_comp_extent_get(layout, &next_start, &next_end);
2756         if (rc) {
2757                 fprintf(stderr, "%s setstripe: cannot get extent: %s\n",
2758                         progname, strerror(errno));
2759                 return rc;
2760         }
2761
2762         next_start += offset ?: size;
2763         rc = llapi_layout_comp_extent_set(layout, next_start, next_end);
2764         if (rc) {
2765                 fprintf(stderr, "%s setstripe: cannot set extent: %s\n",
2766                         progname, strerror(errno));
2767                 return rc;
2768         }
2769
2770         rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_PREV);
2771         if (rc < 0) {
2772                 fprintf(stderr, "%s setstripe: cannot move component cursor: "
2773                         "%s\n", progname, strerror(errno));
2774                 return rc;
2775         }
2776
2777         *end += offset ?: size;
2778         rc = llapi_layout_comp_extent_set(layout, start, *end);
2779         if (rc) {
2780                 fprintf(stderr, "%s setstripe: cannot set extent: %s\n",
2781                         progname, strerror(errno));
2782                 return rc;
2783         }
2784
2785         return 0;
2786 }
2787
2788 /**
2789  * In 'lfs setstripe --component-add' mode, we need to fetch the extent
2790  * end of the last component in the existing file, and adjust the
2791  * first extent start of the components to be added accordingly.
2792  *
2793  * In the create mode, we need to check if the first component is an extendable
2794  * SEL component and extend its length to the extension size (first component
2795  * of the PFL file is initialised at the create time, cannot be 0-lenght.
2796  */
2797 static int layout_adjust_first_extent(char *fname, struct llapi_layout *layout,
2798                                       bool comp_add)
2799 {
2800         struct llapi_layout *head;
2801         uint64_t start = 0, prev_end = 0;
2802         uint64_t end;
2803         int rc, ret = 0;
2804
2805         if (layout == NULL)
2806                 return 0;
2807
2808         errno = 0;
2809         while (comp_add) {
2810                 head = llapi_layout_get_by_path(fname, 0);
2811                 if (head == NULL) {
2812                         fprintf(stderr,
2813                                 "%s setstripe: cannot read layout from '%s': "
2814                                 "%s\n", progname, fname, strerror(errno));
2815                         return -EINVAL;
2816                 } else if (errno == ENODATA) {
2817                         /* file without LOVEA, this component-add will be turned
2818                          * into a component-create. */
2819                         llapi_layout_free(head);
2820                         ret = -ENODATA;
2821
2822                         /* the new layout will be added to an empty one, it
2823                          * still needs to be adjusted below */
2824                         comp_add = 0;
2825                         break;
2826                 } else if (!llapi_layout_is_composite(head)) {
2827                         fprintf(stderr, "%s setstripe: '%s' not a composite "
2828                                 "file\n", progname, fname);
2829                         llapi_layout_free(head);
2830                         return -EINVAL;
2831                 }
2832
2833                 rc = llapi_layout_comp_extent_get(head, &start, &prev_end);
2834                 if (rc) {
2835                         fprintf(stderr, "%s setstripe: cannot get prev "
2836                                 "extent: %s\n", progname, strerror(errno));
2837                         llapi_layout_free(head);
2838                         return rc;
2839                 }
2840
2841                 llapi_layout_free(head);
2842                 break;
2843         }
2844
2845         /* Make sure we use the first component of the layout to be added. */
2846         rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_FIRST);
2847         if (rc < 0) {
2848                 fprintf(stderr,
2849                         "%s setstripe: cannot move component cursor: %s\n",
2850                         progname, strerror(errno));
2851                 return rc;
2852         }
2853
2854         rc = llapi_layout_comp_extent_get(layout, &start, &end);
2855         if (rc) {
2856                 fprintf(stderr, "%s setstripe: cannot get extent: %s\n",
2857                         progname, strerror(errno));
2858                 return rc;
2859         }
2860
2861         if (start == 0 && end == 0) {
2862                 rc = layout_extend_comp(layout, start, &end,
2863                                         comp_add ? prev_end : 0);
2864                 if (rc)
2865                         return rc;
2866         }
2867
2868         if (start > prev_end || end < prev_end) {
2869                 fprintf(stderr, "%s setstripe: first extent [%lu, %lu) not "
2870                         "adjacent with extent end %lu\n",
2871                         progname, start, end, prev_end);
2872                 return -EINVAL;
2873         }
2874
2875         rc = llapi_layout_comp_extent_set(layout, prev_end, end);
2876         if (rc) {
2877                 fprintf(stderr, "%s setstripe: cannot set component extent "
2878                         "[%lu, %lu): %s\n",
2879                         progname, prev_end, end, strerror(errno));
2880                 return rc;
2881         }
2882
2883         return ret;
2884 }
2885
2886 static int mirror_adjust_first_extents(struct mirror_args *list)
2887 {
2888         int rc = 0;
2889
2890         if (list == NULL)
2891                 return 0;
2892
2893         while (list != NULL) {
2894                 rc = layout_adjust_first_extent(NULL, list->m_layout, false);
2895                 if (rc)
2896                         break;
2897                 list = list->m_next;
2898         }
2899
2900         return rc;
2901 }
2902
2903 static inline bool arg_is_eof(char *arg)
2904 {
2905         return !strncmp(arg, "-1", strlen("-1")) ||
2906                !strncmp(arg, "EOF", strlen("EOF")) ||
2907                !strncmp(arg, "eof", strlen("eof"));
2908 }
2909
2910 /**
2911  * lfs_mirror_alloc() - Allocate a mirror argument structure.
2912  *
2913  * Return: Valid mirror_args pointer on success and
2914  *         NULL if memory allocation fails.
2915  */
2916 static struct mirror_args *lfs_mirror_alloc(void)
2917 {
2918         struct mirror_args *mirror = NULL;
2919
2920         while (1) {
2921                 mirror = calloc(1, sizeof(*mirror));
2922                 if (mirror != NULL)
2923                         break;
2924
2925                 sleep(1);
2926         }
2927
2928         return mirror;
2929 }
2930
2931 /**
2932  * lfs_mirror_free() - Free memory allocated for a mirror argument
2933  *                     structure.
2934  * @mirror: Previously allocated mirror argument structure by
2935  *          lfs_mirror_alloc().
2936  *
2937  * Free memory allocated for @mirror.
2938  *
2939  * Return: void.
2940  */
2941 static void lfs_mirror_free(struct mirror_args *mirror)
2942 {
2943         if (mirror->m_layout != NULL)
2944                 llapi_layout_free(mirror->m_layout);
2945         free(mirror);
2946 }
2947
2948 /**
2949  * lfs_mirror_list_free() - Free memory allocated for a mirror list.
2950  * @mirror_list: Previously allocated mirror list.
2951  *
2952  * Free memory allocated for @mirror_list.
2953  *
2954  * Return: void.
2955  */
2956 static void lfs_mirror_list_free(struct mirror_args *mirror_list)
2957 {
2958         struct mirror_args *next_mirror = NULL;
2959
2960         while (mirror_list != NULL) {
2961                 next_mirror = mirror_list->m_next;
2962                 lfs_mirror_free(mirror_list);
2963                 mirror_list = next_mirror;
2964         }
2965 }
2966
2967 enum {
2968         LFS_POOL_OPT = 3,
2969         LFS_COMP_COUNT_OPT,
2970         LFS_COMP_START_OPT,
2971         LFS_COMP_FLAGS_OPT,
2972         LFS_COMP_DEL_OPT,
2973         LFS_COMP_SET_OPT,
2974         LFS_COMP_ADD_OPT,
2975         LFS_COMP_NO_VERIFY_OPT,
2976         LFS_PROJID_OPT,
2977         LFS_LAYOUT_FLAGS_OPT, /* used for mirror and foreign flags */
2978         LFS_MIRROR_ID_OPT,
2979         LFS_MIRROR_STATE_OPT,
2980         LFS_LAYOUT_COPY,
2981         LFS_MIRROR_INDEX_OPT,
2982         LFS_LAYOUT_FOREIGN_OPT,
2983         LFS_MODE_OPT,
2984         LFS_NEWERXY_OPT,
2985 };
2986
2987 /* functions */
2988 static int lfs_setstripe_internal(int argc, char **argv,
2989                                   enum setstripe_origin opc)
2990 {
2991         struct lfs_setstripe_args        lsa = { 0 };
2992         struct llapi_stripe_param       *param = NULL;
2993         struct find_param                migrate_mdt_param = {
2994                 .fp_max_depth = -1,
2995                 .fp_mdt_index = -1,
2996         };
2997         char                            *fname;
2998         int                              result = 0;
2999         int                              result2 = 0;
3000         char                            *end;
3001         int                              c;
3002         int                              delete = 0;
3003         unsigned long long               size_units = 1;
3004         bool                             migrate_mode = false;
3005         bool                             migrate_mdt_mode = false;
3006         bool                             setstripe_mode = false;
3007         bool                             migration_block = false;
3008         __u64                            migration_flags = 0;
3009         __u32                            tgts[LOV_MAX_STRIPE_COUNT] = { 0 };
3010         int                              comp_del = 0, comp_set = 0;
3011         int                              comp_add = 0;
3012         __u32                            comp_id = 0;
3013         struct llapi_layout             *layout = NULL;
3014         struct llapi_layout             **lpp = &layout;
3015         bool                             mirror_mode = false;
3016         bool                             has_m_file = false;
3017         __u32                            mirror_count = 0;
3018         enum mirror_flags                mirror_flags = 0;
3019         struct mirror_args              *mirror_list = NULL;
3020         struct mirror_args              *new_mirror = NULL;
3021         struct mirror_args              *last_mirror = NULL;
3022         __u16                            mirror_id = 0;
3023         char                             cmd[PATH_MAX];
3024         bool from_yaml = false;
3025         bool from_copy = false;
3026         char *template = NULL;
3027         bool foreign_mode = false;
3028         char *xattr = NULL;
3029         uint32_t type = LU_FOREIGN_TYPE_NONE, flags = 0;
3030         char *mode_opt = NULL;
3031         mode_t previous_umask = 0;
3032         mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
3033
3034         struct option long_opts[] = {
3035 /* find { .val = '0',   .name = "null",         .has_arg = no_argument }, */
3036 /* find { .val = 'A',   .name = "atime",        .has_arg = required_argument }*/
3037         /* --block is only valid in migrate mode */
3038         { .val = 'b',   .name = "block",        .has_arg = no_argument },
3039         { .val = LFS_COMP_ADD_OPT,
3040                         .name = "comp-add",     .has_arg = no_argument },
3041         { .val = LFS_COMP_ADD_OPT,
3042                         .name = "component-add", .has_arg = no_argument },
3043         { .val = LFS_COMP_DEL_OPT,
3044                         .name = "comp-del",     .has_arg = no_argument },
3045         { .val = LFS_COMP_DEL_OPT,
3046                         .name = "component-del", .has_arg = no_argument },
3047         { .val = LFS_COMP_FLAGS_OPT,
3048                         .name = "comp-flags",   .has_arg = required_argument },
3049         { .val = LFS_COMP_FLAGS_OPT,
3050                         .name = "component-flags",
3051                                                 .has_arg = required_argument },
3052         { .val = LFS_COMP_SET_OPT,
3053                         .name = "comp-set",     .has_arg = no_argument },
3054         { .val = LFS_COMP_SET_OPT,
3055                         .name = "component-set",
3056                                                 .has_arg = no_argument},
3057         { .val = LFS_COMP_NO_VERIFY_OPT,
3058                         .name = "no-verify",    .has_arg = no_argument},
3059         { .val = LFS_LAYOUT_FLAGS_OPT,
3060                         .name = "flags",        .has_arg = required_argument},
3061         { .val = LFS_LAYOUT_FOREIGN_OPT,
3062                         .name = "foreign",      .has_arg = optional_argument},
3063         { .val = LFS_MIRROR_ID_OPT,
3064                         .name = "mirror-id",    .has_arg = required_argument},
3065         { .val = LFS_MODE_OPT,
3066                         .name = "mode",         .has_arg = required_argument},
3067         { .val = LFS_LAYOUT_COPY,
3068                         .name = "copy",         .has_arg = required_argument},
3069         { .val = 'c',   .name = "stripe-count", .has_arg = required_argument},
3070         { .val = 'c',   .name = "stripe_count", .has_arg = required_argument},
3071         { .val = 'c',   .name = "mdt-count",    .has_arg = required_argument},
3072         { .val = 'C',   .name = "overstripe-count",
3073                                                 .has_arg = required_argument},
3074         { .val = 'd',   .name = "delete",       .has_arg = no_argument},
3075         { .val = 'd',   .name = "destroy",      .has_arg = no_argument},
3076         /* --non-direct is only valid in migrate mode */
3077         { .val = 'D',   .name = "non-direct",   .has_arg = no_argument },
3078         { .val = 'E',   .name = "comp-end",     .has_arg = required_argument},
3079         { .val = 'E',   .name = "component-end",
3080                                                 .has_arg = required_argument},
3081         { .val = 'f',   .name = "file",         .has_arg = required_argument },
3082 /* find { .val = 'F',   .name = "fid",          .has_arg = no_argument }, */
3083 /* find { .val = 'g',   .name = "gid",          .has_arg = no_argument }, */
3084 /* find { .val = 'G',   .name = "group",        .has_arg = required_argument }*/
3085 /* find { .val = 'h',   .name = "help",         .has_arg = no_argument }, */
3086         { .val = 'H',   .name = "mdt-hash",     .has_arg = required_argument},
3087         { .val = 'i',   .name = "stripe-index", .has_arg = required_argument},
3088         { .val = 'i',   .name = "stripe_index", .has_arg = required_argument},
3089         { .val = 'I',   .name = "comp-id",      .has_arg = required_argument},
3090         { .val = 'I',   .name = "component-id", .has_arg = required_argument},
3091 /* find { .val = 'l',   .name = "lazy",         .has_arg = no_argument }, */
3092         { .val = 'L',   .name = "layout",       .has_arg = required_argument },
3093         { .val = 'm',   .name = "mdt",          .has_arg = required_argument},
3094         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument},
3095         { .val = 'm',   .name = "mdt_index",    .has_arg = required_argument},
3096         /* --non-block is only valid in migrate mode */
3097         { .val = 'n',   .name = "non-block",    .has_arg = no_argument },
3098         { .val = 'N',   .name = "mirror-count", .has_arg = optional_argument},
3099         { .val = 'o',   .name = "ost",          .has_arg = required_argument },
3100 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
3101         { .val = 'o',   .name = "ost-list",     .has_arg = required_argument },
3102         { .val = 'o',   .name = "ost_list",     .has_arg = required_argument },
3103 #endif
3104         { .val = 'p',   .name = "pool",         .has_arg = required_argument },
3105 /* find { .val = 'P',   .name = "print",        .has_arg = no_argument }, */
3106 /* getstripe { .val = 'q', .name = "quiet",     .has_arg = no_argument }, */
3107 /* getstripe { .val = 'r', .name = "recursive", .has_arg = no_argument }, */
3108 /* getstripe { .val = 'R', .name = "raw",       .has_arg = no_argument }, */
3109         { .val = 'S',   .name = "stripe-size",  .has_arg = required_argument },
3110         { .val = 'S',   .name = "stripe_size",  .has_arg = required_argument },
3111 /* find { .val = 't',   .name = "type",         .has_arg = required_argument }*/
3112 /* dirstripe { .val = 'T', .name = "mdt-count", .has_arg = required_argument }*/
3113 /* find { .val = 'u',   .name = "uid",          .has_arg = required_argument }*/
3114 /* find { .val = 'U',   .name = "user",         .has_arg = required_argument }*/
3115         /* --verbose is only valid in migrate mode */
3116         { .val = 'v',   .name = "verbose",      .has_arg = no_argument},
3117         { .val = 'x',   .name = "xattr",        .has_arg = required_argument },
3118         { .val = 'y',   .name = "yaml",         .has_arg = required_argument },
3119         { .val = 'z',   .name = "ext-size",     .has_arg = required_argument},
3120         { .val = 'z',   .name = "extension-size", .has_arg = required_argument},
3121         { .name = NULL } };
3122
3123         setstripe_args_init(&lsa);
3124
3125         migrate_mode = (opc == SO_MIGRATE);
3126         mirror_mode = (opc == SO_MIRROR_CREATE || opc == SO_MIRROR_EXTEND);
3127         setstripe_mode = (opc == SO_SETSTRIPE);
3128         if (opc == SO_MIRROR_DELETE) {
3129                 delete = 1;
3130                 mirror_flags = MF_DESTROY;
3131         }
3132
3133         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
3134         progname = cmd;
3135         while ((c = getopt_long(argc, argv,
3136                                 "bc:C:dDE:f:H:i:I:m:N::no:p:L:s:S:vx:y:z:",
3137                                 long_opts, NULL)) >= 0) {
3138                 size_units = 1;
3139                 switch (c) {
3140                 case 0:
3141                         /* Long options. */
3142                         break;
3143                 case LFS_COMP_ADD_OPT:
3144                         comp_add = 1;
3145                         break;
3146                 case LFS_COMP_DEL_OPT:
3147                         comp_del = 1;
3148                         break;
3149                 case LFS_COMP_FLAGS_OPT:
3150                         result = comp_str2flags(optarg, &lsa.lsa_comp_flags,
3151                                                 &lsa.lsa_comp_neg_flags);
3152                         if (result != 0)
3153                                 goto usage_error;
3154                         if (mirror_mode && lsa.lsa_comp_neg_flags) {
3155                                 fprintf(stderr, "%s: inverted flags are not supported\n",
3156                                         progname);
3157                                 goto usage_error;
3158                         }
3159                         break;
3160                 case LFS_COMP_SET_OPT:
3161                         comp_set = 1;
3162                         break;
3163                 case LFS_COMP_NO_VERIFY_OPT:
3164                         mirror_flags |= MF_NO_VERIFY;
3165                         break;
3166                 case LFS_MIRROR_ID_OPT:
3167                         mirror_id = strtoul(optarg, &end, 0);
3168                         if (*end != '\0' || mirror_id == 0) {
3169                                 fprintf(stderr,
3170                                         "%s %s: invalid mirror ID '%s'\n",
3171                                         progname, argv[0], optarg);
3172                                 goto usage_error;
3173                         }
3174                         break;
3175                 case LFS_LAYOUT_FLAGS_OPT: {
3176                         uint32_t neg_flags;
3177
3178                         /* check for numeric flags (foreign and mirror cases) */
3179                         if (setstripe_mode && !mirror_mode && !last_mirror) {
3180                                 flags = strtoul(optarg, &end, 16);
3181                                 if (*end != '\0') {
3182                                         fprintf(stderr,
3183                                                 "%s %s: bad flags '%s'\n",
3184                                                 progname, argv[0], optarg);
3185                                         return CMD_HELP;
3186                                 }
3187                                 break;
3188                         }
3189
3190                         if (!mirror_mode || !last_mirror) {
3191                                 fprintf(stderr, "error: %s: --flags must be specified with --mirror-count|-N option\n",
3192                                         progname);
3193                                 goto usage_error;
3194                         }
3195
3196                         result = comp_str2flags(optarg, &last_mirror->m_flags,
3197                                                 &neg_flags);
3198                         if (result != 0)
3199                                 goto usage_error;
3200
3201                         if (neg_flags) {
3202                                 fprintf(stderr, "%s: inverted flags are not supported\n",
3203                                         progname);
3204                                 result = -EINVAL;
3205                                 goto usage_error;
3206                         }
3207                         if (last_mirror->m_flags & ~LCME_USER_MIRROR_FLAGS) {
3208                                 fprintf(stderr,
3209                                         "%s: unsupported mirror flags: %s\n",
3210                                         progname, optarg);
3211                                 result = -EINVAL;
3212                                 goto error;
3213                         }
3214                         break;
3215                 }
3216                 case LFS_LAYOUT_FOREIGN_OPT:
3217                         if (optarg != NULL) {
3218                                 /* check pure numeric */
3219                                 type = strtoul(optarg, &end, 0);
3220                                 if (*end) {
3221                                         /* check name */
3222                                         type = check_foreign_type_name(optarg);
3223                                         if (type == LU_FOREIGN_TYPE_UNKNOWN) {
3224                                                 fprintf(stderr,
3225                                                         "%s %s: unrecognized foreign type '%s'\n",
3226                                                         progname, argv[0],
3227                                                         optarg);
3228                                                 return CMD_HELP;
3229                                         }
3230                                 }
3231                         }
3232                         foreign_mode = true;
3233                         break;
3234                 case LFS_MODE_OPT:
3235                         mode_opt = optarg;
3236                         if (mode_opt != NULL) {
3237                                 mode = strtoul(mode_opt, &end, 8);
3238                                 if (*end != '\0') {
3239                                         fprintf(stderr,
3240                                                 "%s %s: bad mode '%s'\n",
3241                                                 progname, argv[0], mode_opt);
3242                                         return CMD_HELP;
3243                                 }
3244                                 previous_umask = umask(0);
3245                         }
3246                         break;
3247                 case LFS_LAYOUT_COPY:
3248                         from_copy = true;
3249                         template = optarg;
3250                         break;
3251                 case 'b':
3252                         if (!migrate_mode) {
3253                                 fprintf(stderr,
3254                                         "%s %s: -b|--block valid only for migrate command\n",
3255                                         progname, argv[0]);
3256                                 goto usage_error;
3257                         }
3258                         migration_block = true;
3259                         break;
3260                 case 'C':
3261                         if (lsa.lsa_pattern == LLAPI_LAYOUT_MDT) {
3262                                 fprintf(stderr,
3263                                         "%s %s: -C|--overstripe-count incompatible with DoM layout\n",
3264                                         progname, argv[0]);
3265                                 goto usage_error;
3266                         }
3267                         lsa.lsa_pattern = LLAPI_LAYOUT_OVERSTRIPING;
3268                         /* fall through */
3269                 case 'c':
3270                         lsa.lsa_stripe_count = strtoul(optarg, &end, 0);
3271                         if (*end != '\0') {
3272                                 fprintf(stderr,
3273                                         "%s %s: invalid stripe count '%s'\n",
3274                                         progname, argv[0], optarg);
3275                                 goto usage_error;
3276                         }
3277
3278                         if (lsa.lsa_stripe_count == -1)
3279                                 lsa.lsa_stripe_count = LLAPI_LAYOUT_WIDE;
3280                         break;
3281                 case 'd':
3282                         /* delete the default striping pattern */
3283                         delete = 1;
3284                         if (opc == SO_MIRROR_SPLIT) {
3285                                 if (has_m_file) {
3286                                         fprintf(stderr,
3287                                               "%s %s: -d cannot used with -f\n",
3288                                                 progname, argv[0]);
3289                                         goto usage_error;
3290                                 }
3291                                 mirror_flags |= MF_DESTROY;
3292                         }
3293                         break;
3294                 case 'D':
3295                         if (!migrate_mode) {
3296                                 fprintf(stderr,
3297                                         "%s %s: -D|--non-direct is valid "
3298                                         "only for migrate command\n",
3299                                         progname, argv[0]);
3300                                 goto usage_error;
3301                         }
3302                         migration_flags |= MIGRATION_NONDIRECT;
3303                         break;
3304                 case 'E':
3305                         if (lsa.lsa_comp_end != 0) {
3306                                 result = comp_args_to_layout(lpp, &lsa, true);
3307                                 if (result) {
3308                                         fprintf(stderr, "%s: invalid layout\n",
3309                                                 progname);
3310                                         goto usage_error;
3311                                 }
3312
3313                                 setstripe_args_init_inherit(&lsa);
3314                         }
3315
3316                         if (arg_is_eof(optarg)) {
3317                                 lsa.lsa_comp_end = LUSTRE_EOF;
3318                         } else {
3319                                 result = llapi_parse_size(optarg,
3320                                                         &lsa.lsa_comp_end,
3321                                                         &size_units, 0);
3322                                 if (result) {
3323                                         fprintf(stderr,
3324                                                 "%s %s: invalid component end '%s'\n",
3325                                                 progname, argv[0], optarg);
3326                                         goto usage_error;
3327                                 }
3328                         }
3329                         break;
3330                 case 'H':
3331                         if (!migrate_mode) {
3332                                 fprintf(stderr, "--mdt-hash is valid only for migrate command\n");
3333                                 return CMD_HELP;
3334                         }
3335
3336                         lsa.lsa_pattern = check_hashtype(optarg);
3337                         if (lsa.lsa_pattern == 0) {
3338                                 fprintf(stderr,
3339                                         "%s %s: bad stripe hash type '%s'\n",
3340                                         progname, argv[0], optarg);
3341                                 return CMD_HELP;
3342                         }
3343                         break;
3344                 case 'i':
3345                         lsa.lsa_stripe_off = strtol(optarg, &end, 0);
3346                         if (*end != '\0') {
3347                                 fprintf(stderr,
3348                                         "%s %s: invalid stripe offset '%s'\n",
3349                                         progname, argv[0], optarg);
3350                                 goto usage_error;
3351                         }
3352                         if (lsa.lsa_stripe_off == -1)
3353                                 lsa.lsa_stripe_off = LLAPI_LAYOUT_DEFAULT;
3354                         break;
3355                 case 'I':
3356                         comp_id = strtoul(optarg, &end, 0);
3357                         if (*end != '\0' || comp_id == 0 ||
3358                             comp_id > LCME_ID_MAX) {
3359                                 fprintf(stderr,
3360                                         "%s %s: invalid component ID '%s'\n",
3361                                         progname, argv[0], optarg);
3362                                 goto usage_error;
3363                         }
3364                         break;
3365                 case 'f':
3366                         if (opc != SO_MIRROR_EXTEND && opc != SO_MIRROR_SPLIT) {
3367                                 fprintf(stderr,
3368                                         "error: %s: invalid option: %s\n",
3369                                         progname, argv[optopt + 1]);
3370                                 goto usage_error;
3371                         }
3372                         if (opc == SO_MIRROR_EXTEND) {
3373                                 if (last_mirror == NULL) {
3374                                         fprintf(stderr,
3375                                 "error: %s: '-N' must exist in front of '%s'\n",
3376                                                 progname, argv[optopt + 1]);
3377                                         goto usage_error;
3378                                 }
3379                                 last_mirror->m_file = optarg;
3380                                 last_mirror->m_count = 1;
3381                         } else {
3382                                 /* mirror split */
3383                                 if (mirror_list == NULL)
3384                                         mirror_list = lfs_mirror_alloc();
3385                                 mirror_list->m_file = optarg;
3386                         }
3387                         has_m_file = true;
3388                         break;
3389                 case 'L':
3390                         if (strcmp(argv[optind - 1], "mdt") == 0) {
3391                                 /* Can be only the first component */
3392                                 if (layout != NULL) {
3393                                         result = -EINVAL;
3394                                         fprintf(stderr, "error: 'mdt' layout "
3395                                                 "can be only the first one\n");
3396                                         goto error;
3397                                 }
3398                                 if (lsa.lsa_comp_end > (1ULL << 30)) { /* 1Gb */
3399                                         result = -EFBIG;
3400                                         fprintf(stderr, "error: 'mdt' layout "
3401                                                 "size is too big\n");
3402                                         goto error;
3403                                 }
3404                                 lsa.lsa_pattern = LLAPI_LAYOUT_MDT;
3405                         } else if (strcmp(argv[optind - 1], "raid0") != 0) {
3406                                 result = -EINVAL;
3407                                 fprintf(stderr, "error: layout '%s' is "
3408                                         "unknown, supported layouts are: "
3409                                         "'mdt', 'raid0'\n", argv[optind]);
3410                                 goto error;
3411                         }
3412                         break;
3413                 case 'm':
3414                         if (!migrate_mode) {
3415                                 fprintf(stderr,
3416                                         "%s %s: -m|--mdt-index is valid only for migrate command\n",
3417                                         progname, argv[0]);
3418                                 goto usage_error;
3419                         }
3420                         migrate_mdt_mode = true;
3421                         lsa.lsa_nr_tgts = parse_targets(tgts,
3422                                                 sizeof(tgts) / sizeof(__u32),
3423                                                 lsa.lsa_nr_tgts, optarg, NULL);
3424                         if (lsa.lsa_nr_tgts < 0) {
3425                                 fprintf(stderr,
3426                                         "%s %s: invalid MDT target(s) '%s'\n",
3427                                         progname, argv[0], optarg);
3428                                 return CMD_HELP;
3429                         }
3430
3431                         lsa.lsa_tgts = tgts;
3432                         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
3433                                 lsa.lsa_stripe_off = tgts[0];
3434                         break;
3435                 case 'n':
3436                         if (!migrate_mode) {
3437                                 fprintf(stderr,
3438                                         "%s %s: -n|--non-block valid only for migrate command\n",
3439                                         progname, argv[0]);
3440                                 goto usage_error;
3441                         }
3442                         migration_flags |= MIGRATION_NONBLOCK;
3443                         break;
3444                 case 'N':
3445                         if (opc == SO_SETSTRIPE) {
3446                                 opc = SO_MIRROR_CREATE;
3447                                 mirror_mode = true;
3448                         }
3449                         mirror_count = 1;
3450                         if (optarg != NULL) {
3451                                 mirror_count = strtoul(optarg, &end, 0);
3452                                 if (*end != '\0' || mirror_count == 0) {
3453                                         fprintf(stderr,
3454                                                 "error: %s: bad mirror count: %s\n",
3455                                                 progname, optarg);
3456                                         result = -EINVAL;
3457                                         goto error;
3458                                 }
3459                         }
3460
3461                         new_mirror = lfs_mirror_alloc();
3462                         new_mirror->m_count = mirror_count;
3463
3464                         if (mirror_list == NULL)
3465                                 mirror_list = new_mirror;
3466
3467                         if (last_mirror != NULL) {
3468                                 /* wrap up last mirror */
3469                                 if (lsa.lsa_comp_end == 0)
3470                                         lsa.lsa_comp_end = LUSTRE_EOF;
3471
3472                                 result = comp_args_to_layout(lpp, &lsa, true);
3473                                 if (result) {
3474                                         lfs_mirror_free(new_mirror);
3475                                         goto error;
3476                                 }
3477
3478                                 setstripe_args_init_inherit(&lsa);
3479
3480                                 last_mirror->m_next = new_mirror;
3481                         }
3482
3483                         last_mirror = new_mirror;
3484                         lpp = &last_mirror->m_layout;
3485                         break;
3486                 case 'o':
3487 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
3488                         if (strcmp(argv[optind - 1], "--ost-list") == 0)
3489                                 fprintf(stderr, "warning: '--ost-list' is "
3490                                         "deprecated, use '--ost' instead\n");
3491 #endif
3492                         if (lsa.lsa_pattern == LLAPI_LAYOUT_MDT) {
3493                                 fprintf(stderr,
3494                                         "%s %s: -o|--ost incompatible with DoM layout\n",
3495                                         progname, argv[0]);
3496                                 goto usage_error;
3497                         }
3498                         /* -o allows overstriping, and must note it because
3499                          * parse_targets is shared with MDT striping, which
3500                          * does not allow duplicates
3501                          */
3502                         lsa.lsa_pattern = LLAPI_LAYOUT_OVERSTRIPING;
3503                         lsa.lsa_nr_tgts = parse_targets(tgts,
3504                                                 sizeof(tgts) / sizeof(__u32),
3505                                                 lsa.lsa_nr_tgts, optarg,
3506                                                 &lsa.lsa_pattern);
3507  &n