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