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