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