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