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