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