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