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