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