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