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