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