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