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