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