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