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