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