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