Whamcloud - gitweb
LU-13142 lod: cleanup layout checking
[fs/lustre-release.git] / lustre / utils / lfs.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2011, 2017, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  * Lustre is a trademark of Sun Microsystems, Inc.
31  *
32  * lustre/utils/lfs.c
33  *
34  * Author: Peter J. Braam <braam@clusterfs.com>
35  * Author: Phil Schwan <phil@clusterfs.com>
36  * Author: Robert Read <rread@clusterfs.com>
37  */
38
39 /* for O_DIRECTORY */
40 #ifndef _GNU_SOURCE
41 #define _GNU_SOURCE
42 #endif
43
44 #include <stdlib.h>
45 #include <stdio.h>
46 #include <inttypes.h>
47 #include <getopt.h>
48 #include <string.h>
49 #include <mntent.h>
50 #include <unistd.h>
51 #include <errno.h>
52 #include <err.h>
53 #include <pwd.h>
54 #include <grp.h>
55 #include <sys/ioctl.h>
56 #include <sys/quota.h>
57 #include <sys/time.h>
58 #include <sys/types.h>
59 #include <sys/stat.h>
60 #include <sys/param.h>
61 #include <sys/xattr.h>
62 #include <fcntl.h>
63 #include <dirent.h>
64 #include <time.h>
65 #include <ctype.h>
66 #include <zlib.h>
67 #include <libgen.h>
68 #include <asm/byteorder.h>
69 #include "lfs_project.h"
70
71 #include <libcfs/util/string.h>
72 #include <libcfs/util/ioctl.h>
73 #include <libcfs/util/parser.h>
74 #include <lustre/lustreapi.h>
75 #include <linux/lustre/lustre_ver.h>
76 #include <linux/lustre/lustre_param.h>
77 #include <linux/lnet/nidstr.h>
78 #include <cyaml.h>
79
80 #ifndef ARRAY_SIZE
81 # define ARRAY_SIZE(a) ((sizeof(a)) / (sizeof((a)[0])))
82 #endif /* !ARRAY_SIZE */
83
84 /* all functions */
85 static int lfs_find(int argc, char **argv);
86 static int lfs_getstripe(int argc, char **argv);
87 static int lfs_getdirstripe(int argc, char **argv);
88 static int lfs_setdirstripe(int argc, char **argv);
89 static int lfs_rmentry(int argc, char **argv);
90 static int lfs_osts(int argc, char **argv);
91 static int lfs_mdts(int argc, char **argv);
92 static int lfs_df(int argc, char **argv);
93 static int lfs_getname(int argc, char **argv);
94 static int lfs_check(int argc, char **argv);
95 #ifdef HAVE_SYS_QUOTA_H
96 static int lfs_setquota(int argc, char **argv);
97 static int lfs_quota(int argc, char **argv);
98 static int lfs_project(int argc, char **argv);
99 #endif
100 static int lfs_flushctx(int argc, char **argv);
101 static int lfs_poollist(int argc, char **argv);
102 static int lfs_changelog(int argc, char **argv);
103 static int lfs_changelog_clear(int argc, char **argv);
104 static int lfs_fid2path(int argc, char **argv);
105 static int lfs_path2fid(int argc, char **argv);
106 static int lfs_rmfid(int argc, char **argv);
107 static int lfs_data_version(int argc, char **argv);
108 static int lfs_hsm_state(int argc, char **argv);
109 static int lfs_hsm_set(int argc, char **argv);
110 static int lfs_hsm_clear(int argc, char **argv);
111 static int lfs_hsm_action(int argc, char **argv);
112 static int lfs_hsm_archive(int argc, char **argv);
113 static int lfs_hsm_restore(int argc, char **argv);
114 static int lfs_hsm_release(int argc, char **argv);
115 static int lfs_hsm_remove(int argc, char **argv);
116 static int lfs_hsm_cancel(int argc, char **argv);
117 static int lfs_swap_layouts(int argc, char **argv);
118 static int lfs_mv(int argc, char **argv);
119 static int lfs_ladvise(int argc, char **argv);
120 static int lfs_getsom(int argc, char **argv);
121 static int lfs_mirror(int argc, char **argv);
122 static int lfs_mirror_list_commands(int argc, char **argv);
123 static int lfs_list_commands(int argc, char **argv);
124 static inline int lfs_mirror_resync(int argc, char **argv);
125 static inline int lfs_mirror_verify(int argc, char **argv);
126 static inline int lfs_mirror_read(int argc, char **argv);
127 static inline int lfs_mirror_write(int argc, char **argv);
128 static inline int lfs_mirror_copy(int argc, char **argv);
129
130 enum setstripe_origin {
131         SO_SETSTRIPE,
132         SO_MIGRATE,
133         SO_MIGRATE_MDT,
134         SO_MIRROR_CREATE,
135         SO_MIRROR_EXTEND,
136         SO_MIRROR_SPLIT,
137 };
138 static int lfs_setstripe_internal(int argc, char **argv,
139                                   enum setstripe_origin opc);
140
141 static inline int lfs_setstripe(int argc, char **argv)
142 {
143         return lfs_setstripe_internal(argc, argv, SO_SETSTRIPE);
144 }
145 static inline int lfs_setstripe_migrate(int argc, char **argv)
146 {
147         return lfs_setstripe_internal(argc, argv, SO_MIGRATE);
148 }
149 static inline int lfs_mirror_create(int argc, char **argv)
150 {
151         return lfs_setstripe_internal(argc, argv, SO_MIRROR_CREATE);
152 }
153 static inline int lfs_mirror_extend(int argc, char **argv)
154 {
155         return lfs_setstripe_internal(argc, argv, SO_MIRROR_EXTEND);
156 }
157 static inline int lfs_mirror_split(int argc, char **argv)
158 {
159         return lfs_setstripe_internal(argc, argv, SO_MIRROR_SPLIT);
160 }
161
162 /* Setstripe and migrate share mostly the same parameters */
163 #define SSM_CMD_COMMON(cmd) \
164         "usage: "cmd" [--component-end|-E <comp_end>]\n"                \
165         "                 [--stripe-count|-c <stripe_count>]\n"         \
166         "                 [--stripe-index|-i <start_ost_idx>]\n"        \
167         "                 [--stripe-size|-S <stripe_size>]\n"           \
168         "                 [--layout|-L <pattern>]\n"                    \
169         "                 [--pool|-p <pool_name>]\n"                    \
170         "                 [--ost|-o <ost_indices>]\n"                   \
171         "                 [--yaml|-y <yaml_template_file>]\n"           \
172         "                 [--copy=<lustre_src>]\n"
173
174 #define SSM_HELP_COMMON \
175         "\tstripe_count: Number of OSTs to stripe over (0=fs default, -1 all)\n" \
176         "\tstart_ost_idx: OST index of first stripe (-1=default round robin)\n"\
177         "\tstripe_size:  Number of bytes on each OST (0=fs default)\n" \
178         "\t              Can be specified with K, M or G (for KB, MB, GB\n" \
179         "\t              respectively)\n"                               \
180         "\tpool_name:    Name of OST pool to use (default none)\n"      \
181         "\tlayout:       stripe pattern type: raid0, mdt (default raid0)\n"\
182         "\tost_indices:  List of OST indices, can be repeated multiple times\n"\
183         "\t              Indices be specified in a format of:\n"        \
184         "\t                -o <ost_1>,<ost_i>-<ost_j>,<ost_n>\n"        \
185         "\t              Or:\n"                                         \
186         "\t                -o <ost_1> -o <ost_i>-<ost_j> -o <ost_n>\n"  \
187         "\t              If --pool is set with --ost, then the OSTs\n"  \
188         "\t              must be the members of the pool.\n"            \
189         "\tcomp_end:     Extent end of component, start after previous end.\n"\
190         "\t              Can be specified with K, M or G (for KB, MB, GB\n" \
191         "\t              respectively, -1 for EOF). Must be a multiple of\n"\
192         "\t              stripe_size.\n"                                      \
193         "\tyaml_template_file:\n"                                             \
194         "\t              YAML layout template file, can't be used with -c,\n" \
195         "\t              -i, -S, -p, -o, or -E arguments.\n"                  \
196         "\tlustre_src:   Lustre file/dir whose layout info is used to set\n"  \
197         "\t              another lustre file or directory, can't used with\n" \
198         "\t              -c, -i, -S, -p, -o, or -E arguments.\n"
199
200 #define MIRROR_CREATE_HELP                                                     \
201         "\tmirror_count: Number of mirrors to be created with the upcoming\n"  \
202         "\t              setstripe layout options\n"                           \
203         "\t              It defaults to 1 if not specified; if specified,\n"   \
204         "\t              it must follow the option without a space.\n"         \
205         "\t              The option can also be repeated multiple times to\n"  \
206         "\t              separate mirrors that have different layouts.\n"      \
207         "\tsetstripe options: Mirror layout\n"                                 \
208         "\t              It can be a plain layout or a composite layout.\n"    \
209         "\t              If not specified, the stripe options inherited\n"     \
210         "\t              from the previous component will be used.\n"          \
211         "\tflags:        set flags to the component of the current mirror.\n"  \
212         "\t              Only \"prefer\" flag is supported so far.\n"
213
214 #define MIRROR_EXTEND_HELP                                                     \
215         MIRROR_CREATE_HELP                                                     \
216         "\tvictim_file:  The layout of victim_file will be split and used\n"   \
217         "\t              as a mirror added to the mirrored file.\n"            \
218         "\tno-verify:    This option indicates not to verify the mirror(s)\n"  \
219         "\t              from victim file(s) in case the victim file(s)\n"     \
220         "\t              contains the same data as the original mirrored\n"    \
221         "\t              file.\n"
222
223 #define MIRROR_EXTEND_USAGE                                                    \
224         "                 <--mirror-count|-N[mirror_count]>\n"                 \
225         "                 [setstripe options|-f <victim_file>]\n"              \
226         "                 [--no-verify]\n"
227
228 #define SETSTRIPE_USAGE                                                 \
229         SSM_CMD_COMMON("setstripe")                                     \
230         MIRROR_EXTEND_USAGE                                             \
231         "                 <directory|filename>\n"                       \
232         SSM_HELP_COMMON                                                 \
233         MIRROR_EXTEND_HELP
234
235 #define MIGRATE_USAGE                                                   \
236         SSM_CMD_COMMON("migrate  ")                                     \
237         "                 [--block|-b]\n"                               \
238         "                 [--non-block|-n]\n"                           \
239         "                 [--non-direct|-D]\n"                          \
240         "                 <filename>\n"                                 \
241         SSM_HELP_COMMON                                                 \
242         "\n"                                                            \
243         "\tblock:        Block file access during data migration (default)\n" \
244         "\tnon-block:    Abort migrations if concurrent access is detected\n" \
245         "\tnon-direct:   Do not use direct I/O to copy file contents\n" \
246
247 #define SETDIRSTRIPE_USAGE                                              \
248         "               [--mdt-count|-c stripe_count>\n"                \
249         "               [--mdt-index|-i mdt_index[,mdt_index,...]\n"    \
250         "               [--mdt-hash|-H mdt_hash]\n"                     \
251         "               [--default|-D] [--mode|-m mode] <dir>\n"        \
252         "\tstripe_count: stripe count of the striped directory\n"       \
253         "\tmdt_index: MDT index of first stripe\n"                      \
254         "\tmdt_hash:  hash type of the striped directory. mdt types:\n" \
255         "       fnv_1a_64 FNV-1a hash algorithm (default)\n"            \
256         "       all_char  sum of characters % MDT_COUNT (not recommended)\n" \
257         "\tdefault_stripe: set default dirstripe of the directory\n"    \
258         "\tmode: the mode of the directory\n"
259
260 /**
261  * command_t mirror_cmdlist - lfs mirror commands.
262  */
263 command_t mirror_cmdlist[] = {
264         { .pc_name = "create", .pc_func = lfs_mirror_create,
265           .pc_help = "Create a mirrored file.\n"
266                 "usage: lfs mirror create "
267                 "<--mirror-count|-N[mirror_count]> "
268                 "[setstripe options] ... <filename|directory>\n"
269           MIRROR_CREATE_HELP },
270         { .pc_name = "extend", .pc_func = lfs_mirror_extend,
271           .pc_help = "Extend a mirrored file.\n"
272                 "usage: lfs mirror extend "
273                 "<--mirror-count|-N[mirror_count]> [--no-verify] "
274                 "[setstripe options|-f <victim_file>] ... <filename>\n"
275           MIRROR_EXTEND_HELP },
276         { .pc_name = "split", .pc_func = lfs_mirror_split,
277           .pc_help = "Split a mirrored file.\n"
278         "usage: lfs mirror split <--mirror-id <mirror_id> |\n"
279         "\t             <--component-id|-I <comp_id>|-p <pool>> [--destroy|-d]\n"
280         "\t             [-f <new_file>] <mirrored file>\n"
281         "\tmirror_id:   The numerical unique identifier for a mirror. It\n"
282         "\t             can be fetched by lfs getstripe command.\n"
283         "\tcomp_id:     Unique component ID within a mirror.\n"
284         "\tpool:        Components on specified pool.\n"
285         "\tnew_file:    This option indicates the layout of the split\n"
286         "\t             mirror will be stored into. If not specified,\n"
287         "\t             a new file named <mirrored_file>.mirror~<mirror_id>\n"
288         "\t             will be used.\n" },
289         { .pc_name = "read", .pc_func = lfs_mirror_read,
290           .pc_help = "Read the content of a specified mirror of a file.\n"
291                 "usage: lfs mirror read <--mirror-id|-N <mirror_id> "
292                 "[--outfile|-o <output_file>] <mirrored_file>\n" },
293         { .pc_name = "write", .pc_func = lfs_mirror_write,
294           .pc_help = "Write to a specified mirror of a file.\n"
295                 "usage: lfs mirror write <--mirror-id|-N <mirror_id> "
296                 "[--inputfile|-i <input_file>] <mirrored_file>\n" },
297         { .pc_name = "copy", .pc_func = lfs_mirror_copy,
298           .pc_help = "Copy a specified mirror to other mirror(s) of a file.\n"
299                 "usage: lfs mirror copy <--read-mirror|-i <id0>> "
300                 "<--write-mirror|-o <id1,id2>> <mirrored_file>\n" },
301         { .pc_name = "resync", .pc_func = lfs_mirror_resync,
302           .pc_help = "Resynchronizes out-of-sync mirrored file(s).\n"
303                 "usage: lfs mirror resync [--only <mirror_id[,...]>] "
304                 "<mirrored file> [<mirrored file2>...]\n"},
305         { .pc_name = "verify", .pc_func = lfs_mirror_verify,
306           .pc_help = "Verify mirrored file(s).\n"
307                 "usage: lfs mirror verify "
308                 "[--only <mirror_id,mirror_id2[,...]>] "
309                 "[--verbose|-v] <mirrored_file> [<mirrored_file2> ...]\n"},
310         { .pc_name = "list-commands", .pc_func = lfs_mirror_list_commands,
311           .pc_help = "list commands supported by lfs mirror"},
312         { .pc_name = "help", .pc_func = Parser_help, .pc_help = "help" },
313         { .pc_name = "exit", .pc_func = Parser_quit, .pc_help = "quit" },
314         { .pc_name = "quit", .pc_func = Parser_quit, .pc_help = "quit" },
315         { .pc_help = NULL }
316 };
317
318 /* all available commands */
319 command_t cmdlist[] = {
320         {"setstripe", lfs_setstripe, 0,
321          "To create a file with specified striping/composite layout, or\n"
322          "create/replace the default layout on an existing directory:\n"
323          SSM_CMD_COMMON("setstripe")
324          "                 <directory|filename>\n"
325          " or\n"
326          "To add component(s) to an existing composite file:\n"
327          SSM_CMD_COMMON("setstripe --component-add")
328          SSM_HELP_COMMON
329          "To totally delete the default striping from an existing directory:\n"
330          "usage: setstripe -d <directory>\n"
331          " or\n"
332          "To create a mirrored file or set s default mirror layout on a directory:\n"
333          "usage: setstripe -N[mirror_count] [STRIPE_OPTIONS] <directory|filename>\n"
334          " or\n"
335          "To delete the last component(s) from an existing composite file\n"
336          "(note that this will also delete any data in those components):\n"
337          "usage: setstripe --component-del [--component-id|-I <comp_id>]\n"
338          "                               [--component-flags|-F <comp_flags>]\n"
339          "                               <filename>\n"
340          "\tcomp_id:     Unique component ID to delete\n"
341          "\tcomp_flags:  'init' indicating all instantiated components\n"
342          "\t             '^init' indicating all uninstantiated components\n"
343          "\t-I and -F cannot be specified at the same time\n"},
344         {"getstripe", lfs_getstripe, 0,
345          "To list the layout pattern for a given file or files in a\n"
346          "directory or recursively for all files in a directory tree.\n"
347          "usage: getstripe [--ost|-O <uuid>] [--quiet|-q] [--verbose|-v]\n"
348          "                 [--stripe-count|-c] [--stripe-index|-i] [--fid|-F]\n"
349          "                 [--pool|-p] [--stripe-size|-S] [--directory|-d]\n"
350          "                 [--mdt-index|-m] [--recursive|-r] [--raw|-R]\n"
351          "                 [--layout|-L] [--generation|-g] [--yaml|-y]\n"
352          "                 [--component-id[=comp_id]|-I[comp_id]]\n"
353          "                 [--component-flags[=comp_flags]]\n"
354          "                 [--component-count]\n"
355          "                 [--component-start[=[+-]comp_start]]\n"
356          "                 [--component-end[=[+-]comp_end]|-E[[+-]comp_end]]\n"
357          "                 [[!] --mirror-index=[+-]<index> |\n"
358          "                  [!] --mirror-id=[+-]<id>]\n"
359          "                 <directory|filename> ..."},
360         {"setdirstripe", lfs_setdirstripe, 0,
361          "To create a striped directory on a specified MDT. This can only\n"
362          "be done on MDT0 with the right of administrator.\n"
363          "usage: setdirstripe [OPTION] <directory>\n"
364          SETDIRSTRIPE_USAGE},
365         {"getdirstripe", lfs_getdirstripe, 0,
366          "To list the layout pattern info for a given directory\n"
367          "or recursively for all directories in a directory tree.\n"
368          "usage: getdirstripe [--mdt-count|-c] [--mdt-index|-m|-i]\n"
369          "                    [--mdt-hash|-H] [--obd|-O <uuid>]\n"
370          "                    [--recursive|-r] [--yaml|-y]\n"
371          "                    [--default|-D] <dir> ..."},
372         {"mkdir", lfs_setdirstripe, 0,
373          "To create a striped directory on a specified MDT. This can only\n"
374          "be done on MDT0 with the right of administrator.\n"
375          "usage: mkdir [OPTION] <directory>\n"
376          SETDIRSTRIPE_USAGE},
377         {"rm_entry", lfs_rmentry, 0,
378          "To remove the name entry of the remote directory. Note: This\n"
379          "command will only delete the name entry, i.e. the remote directory\n"
380          "will become inaccessable after this command. This can only be done\n"
381          "by the administrator\n"
382          "usage: rm_entry <dir>\n"},
383         {"pool_list", lfs_poollist, 0,
384          "List pools or pool OSTs\n"
385          "usage: pool_list <fsname>[.<pool>] | <pathname>\n"},
386         {"find", lfs_find, 0,
387          "find files matching given attributes recursively in directory tree.\n"
388          "usage: find <directory|filename> ...\n"
389          "     [[!] --atime|-A [+-]N] [[!] --ctime|-C [+-]N]\n"
390          "     [[!] --mtime|-M [+-]N] [--maxdepth|-D N] [[!] --blocks|-b N]\n"
391          "     [[!] --mdt-index|--mdt|-m <uuid|index,...>]\n"
392          "     [[!] --name|-n <pattern>] [[!] --ost|-O <uuid|index,...>]\n"
393          "     [--print|-P] [--print0|-0] [[!] --size|-s [+-]N[bkMGTPE]]\n"
394          "     [[!] --stripe-count|-c [+-]<stripes>]\n"
395          "     [[!] --stripe-index|-i <index,...>]\n"
396          "     [[!] --stripe-size|-S [+-]N[kMGT]] [[!] --type|-t <filetype>]\n"
397          "     [[!] --gid|-g|--group|-G <gid>|<gname>]\n"
398          "     [[!] --uid|-u|--user|-U <uid>|<uname>] [[!] --pool <pool>]\n"
399          "     [[!] --projid <projid>]\n"
400          "     [[!] --layout|-L released,raid0,mdt]\n"
401          "     [[!] --component-count [+-]<comp_cnt>]\n"
402          "     [[!] --component-start [+-]N[kMGTPE]]\n"
403          "     [[!] --component-end|-E [+-]N[kMGTPE]]\n"
404          "     [[!] --component-flags <comp_flags>]\n"
405          "     [[!] --mirror-count|-N [+-]<n>]\n"
406          "     [[!] --mirror-state <[^]state>]\n"
407          "     [[!] --mdt-count|-T [+-]<stripes>]\n"
408          "     [[!] --mdt-hash|-H <hashtype>\n"
409          "\t !: used before an option indicates 'NOT' requested attribute\n"
410          "\t -: used before a value indicates less than requested value\n"
411          "\t +: used before a value indicates more than requested value\n"
412          "\thashtype:   hash type of the striped directory.\n"
413          "\t            fnv_1a_64 FNV-1a hash algorithm\n"
414          "\t            all_char  sum of characters % MDT_COUNT\n"},
415         {"check", lfs_check, 0,
416          "Display the status of MDS or OSTs (as specified in the command)\n"
417          "or all the servers (MDS and OSTs).\n"
418          "usage: check <osts|mds|servers>"},
419         {"osts", lfs_osts, 0, "list OSTs connected to client "
420          "[for specified path only]\n" "usage: osts [path]"},
421         {"mdts", lfs_mdts, 0, "list MDTs connected to client "
422          "[for specified path only]\n" "usage: mdts [path]"},
423         {"df", lfs_df, 0,
424          "report filesystem disk space usage or inodes usage"
425          "of each MDS and all OSDs or a batch belonging to a specific pool .\n"
426          "Usage: df [-i] [-h] [--lazy|-l] [--pool|-p <fsname>[.<pool>] [path]"},
427         {"getname", lfs_getname, 0, "list instances and specified mount points "
428          "[for specified path only]\n"
429          "Usage: getname [-h]|[path ...] "},
430 #ifdef HAVE_SYS_QUOTA_H
431         {"setquota", lfs_setquota, 0, "Set filesystem quotas.\n"
432          "usage: setquota <-u|-g|-p> <uname>|<uid>|<gname>|<gid>|<projid>\n"
433          "                -b <block-softlimit> -B <block-hardlimit>\n"
434          "                -i <inode-softlimit> -I <inode-hardlimit> <filesystem>\n"
435          "       setquota <-u|--user|-g|--group|-p|--projid> <uname>|<uid>|<gname>|<gid>|<projid>\n"
436          "                [--block-softlimit <block-softlimit>]\n"
437          "                [--block-hardlimit <block-hardlimit>]\n"
438          "                [--inode-softlimit <inode-softlimit>]\n"
439          "                [--inode-hardlimit <inode-hardlimit>] <filesystem>\n"
440          "       setquota [-t] <-u|--user|-g|--group|-p|--projid>\n"
441          "                [--block-grace <block-grace>]\n"
442          "                [--inode-grace <inode-grace>] <filesystem>\n"
443          "       setquota <-U|-G|-P>\n"
444          "                -b <block-softlimit> -B <block-hardlimit>\n"
445          "                -i <inode-softlimit> -I <inode-hardlimit> <filesystem>\n"
446          "       setquota <-U|--default-usr|-G|--default-grp|-P|--default-prj>\n"
447          "                [--block-softlimit <block-softlimit>]\n"
448          "                [--block-hardlimit <block-hardlimit>]\n"
449          "                [--inode-softlimit <inode-softlimit>]\n"
450          "                [--inode-hardlimit <inode-hardlimit>] <filesystem>\n"
451          "       setquota <-u|-g|-p> <uname>|<uid>|<gname>|<gid>|<projid>\n"
452          "                <-d|--default>\n"
453          "       -b can be used instead of --block-softlimit/--block-grace\n"
454          "       -B can be used instead of --block-hardlimit\n"
455          "       -i can be used instead of --inode-softlimit/--inode-grace\n"
456          "       -I can be used instead of --inode-hardlimit\n"
457          "       -d can be used instead of --default\n\n"
458          "Note: The total quota space will be split into many qunits and\n"
459          "      balanced over all server targets, the minimal qunit size is\n"
460          "      1M bytes for block space and 1K inodes for inode space.\n\n"
461          "      The maximum quota grace time is 2^48 - 1 seconds.\n\n"
462          "      Quota space rebalancing process will stop when this mininum\n"
463          "      value is reached. As a result, quota exceeded can be returned\n"
464          "      while many targets still have 1MB or 1K inodes of spare\n"
465          "      quota space."},
466         {"quota", lfs_quota, 0, "Display disk usage and limits.\n"
467          "usage: quota [-q] [-v] [-h] [-o <obd_uuid>|-i <mdt_idx>|-I "
468                        "<ost_idx>]\n"
469          "             [<-u|-g|-p> <uname>|<uid>|<gname>|<gid>|<projid>] <filesystem>\n"
470          "       quota [-o <obd_uuid>|-i <mdt_idx>|-I <ost_idx>] -t <-u|-g|-p> <filesystem>\n"
471         "        quota [-q] [-v] [h] <-U|-G|-P> <filesystem>"},
472         {"project", lfs_project, 0,
473          "Change or list project attribute for specified file or directory.\n"
474          "usage: project [-d|-r] <file|directory...>\n"
475          "         list project ID and flags on file(s) or directories\n"
476          "       project [-p id] [-s] [-r] <file|directory...>\n"
477          "         set project ID and/or inherit flag for specified file(s) or directories\n"
478          "       project -c [-d|-r [-p id] [-0]] <file|directory...>\n"
479          "         check project ID and flags on file(s) or directories, print outliers\n"
480          "       project -C [-r] [-k] <file|directory...>\n"
481          "         clear the project inherit flag and ID on the file or directory\n"
482         },
483 #endif
484         {"flushctx", lfs_flushctx, 0, "Flush security context for current user.\n"
485          "usage: flushctx [-k] [mountpoint...]"},
486         {"changelog", lfs_changelog, 0,
487          "Show the metadata changes on an MDT."
488          "\nusage: changelog <mdtname> [startrec [endrec]]"},
489         {"changelog_clear", lfs_changelog_clear, 0,
490          "Indicate that old changelog records up to <endrec> are no longer of "
491          "interest to consumer <id>, allowing the system to free up space.\n"
492          "An <endrec> of 0 means all records.\n"
493          "usage: changelog_clear <mdtname> <id> <endrec>"},
494         {"fid2path", lfs_fid2path, 0,
495          "Resolve the full path(s) for given FID(s). For a specific hardlink "
496          "specify link number <linkno>.\n"
497         /* "For a historical link name, specify changelog record <recno>.\n" */
498          "usage: fid2path [--link <linkno>] <fsname|rootpath> <fid> ..."
499                 /* [ --rec <recno> ] */ },
500         {"path2fid", lfs_path2fid, 0, "Display the fid(s) for a given path(s).\n"
501          "usage: path2fid [--parents] <path> ..."},
502         {"rmfid", lfs_rmfid, 0, "Remove file(s) by FID(s)\n"
503          "usage: rmfid <fsname|rootpath> <fid> ..."},
504         {"data_version", lfs_data_version, 0, "Display file data version for "
505          "a given path.\n" "usage: data_version -[n|r|w] <path>"},
506         {"hsm_state", lfs_hsm_state, 0, "Display the HSM information (states, "
507          "undergoing actions) for given files.\n usage: hsm_state <file> ..."},
508         {"hsm_set", lfs_hsm_set, 0, "Set HSM user flag on specified files.\n"
509          "usage: hsm_set [--norelease] [--noarchive] [--dirty] [--exists] "
510          "[--archived] [--lost] [--archive-id NUM] <file> ..."},
511         {"hsm_clear", lfs_hsm_clear, 0, "Clear HSM user flag on specified "
512          "files.\n"
513          "usage: hsm_clear [--norelease] [--noarchive] [--dirty] [--exists] "
514          "[--archived] [--lost] <file> ..."},
515         {"hsm_action", lfs_hsm_action, 0, "Display current HSM request for "
516          "given files.\n" "usage: hsm_action <file> ..."},
517         {"hsm_archive", lfs_hsm_archive, 0,
518          "Archive file to external storage.\n"
519          "usage: hsm_archive [--filelist FILELIST] [--data DATA] [--archive NUM] "
520          "<file> ..."},
521         {"hsm_restore", lfs_hsm_restore, 0,
522          "Restore file from external storage.\n"
523          "usage: hsm_restore [--filelist FILELIST] [--data DATA] <file> ..."},
524         {"hsm_release", lfs_hsm_release, 0,
525          "Release files from Lustre.\n"
526          "usage: hsm_release [--filelist FILELIST] [--data DATA] <file> ..."},
527         {"hsm_remove", lfs_hsm_remove, 0,
528          "Remove file copy from external storage.\n"
529          "usage: hsm_remove [--filelist FILELIST] [--data DATA] "
530          "[--archive NUM]\n"
531          "                  (FILE [FILE ...] | "
532          "--mntpath MOUNTPATH FID [FID ...])\n"
533          "\n"
534          "Note: To remove an archived copy of a file already deleted from a "
535          "Lustre FS, the\n"
536          "--mntpath option and a list of FIDs must be specified"
537         },
538         {"hsm_cancel", lfs_hsm_cancel, 0,
539          "Cancel requests related to specified files.\n"
540          "usage: hsm_cancel [--filelist FILELIST] [--data DATA] <file> ..."},
541         {"swap_layouts", lfs_swap_layouts, 0, "Swap layouts between 2 files.\n"
542          "usage: swap_layouts <path1> <path2>"},
543         {"migrate", lfs_setstripe_migrate, 0,
544          "migrate a directory between MDTs.\n"
545          "usage: migrate [--mdt|-m] <start_mdt_index>\n"
546          "               [--mdt-count|-c] <stripe_count>\n"
547          "               [--mdt-hash|-H] <hash_type>\n"
548          "               [--verbose|-v]\n"
549          "               <directory>\n"
550          "\tmdt:        MDTs to stripe over, if only one MDT is specified\n"
551          "                      it's the MDT index of first stripe\n"
552          "\tmdt_count:  number of MDTs to stripe a directory over\n"
553          "\tmdt_hash:   hash type of the striped directory. mdt types:\n"
554          "                      fnv_1a_64 FNV-1a hash algorithm (default)\n"
555          "                      all_char  sum of characters % MDT_COUNT\n"
556          "\n"
557          "migrate file objects from one OST "
558          "layout\nto another (may be not safe with concurent writes).\n"
559          "usage: migrate  "
560          "[--stripe-count|-c] <stripe_count>\n"
561          "              [--stripe-index|-i] <start_ost_index>\n"
562          "              [--stripe-size|-S] <stripe_size>\n"
563          "              [--pool|-p] <pool_name>\n"
564          "              [--ost|-o] <ost_indices>\n"
565          "              [--block|-b]\n"
566          "              [--non-block|-n]\n"
567          "              [--non-direct|-D]\n"
568          "              <file|directory>\n"
569          "\tstripe_count:     number of OSTs to stripe a file over\n"
570          "\tstripe_ost_index: index of the first OST to stripe a file over\n"
571          "\tstripe_size:      number of bytes to store before moving to the next OST\n"
572          "\tpool_name:        name of the predefined pool of OSTs\n"
573          "\tost_indices:      OSTs to stripe over, in order\n"
574          "\tblock:            wait for the operation to return before continuing\n"
575          "\tnon-block:        do not wait for the operation to return\n"
576          "\tnon-direct:       do not use direct I/O to copy file contents.\n"},
577         {"mv", lfs_mv, 0,
578          "To move directories between MDTs. This command is deprecated, "
579          "use \"migrate\" instead.\n"
580          "usage: mv <directory|filename> [--mdt-index|-m] <mdt_index> "
581          "[--verbose|-v]\n"},
582         {"ladvise", lfs_ladvise, 0,
583          "Provide servers with advice about access patterns for a file.\n"
584          "usage: ladvise [--advice|-a ADVICE] [--start|-s START[kMGT]]\n"
585          "               [--background|-b] [--unset|-u]\n\n"
586          "               {[--end|-e END[kMGT]] | [--length|-l LENGTH[kMGT]]}\n"
587          "               {[--mode|-m [READ,WRITE]}\n"
588          "               <file> ...\n"},
589         {"mirror", lfs_mirror, mirror_cmdlist,
590          "lfs commands used to manage files with mirrored components:\n"
591          "lfs mirror create - create a mirrored file or directory\n"
592          "lfs mirror extend - add mirror(s) to an existing file\n"
593          "lfs mirror split  - split a mirror from an existing mirrored file\n"
594          "lfs mirror resync - resynchronize out-of-sync mirrored file(s)\n"
595          "lfs mirror read   - read a mirror content of a mirrored file\n"
596          "lfs mirror write  - write to a mirror of a mirrored file\n"
597          "lfs mirror copy   - copy a mirror to other mirror(s) of a file\n"
598          "lfs mirror verify - verify mirrored file(s)\n"},
599         {"getsom", lfs_getsom, 0, "To list the SOM info for a given file.\n"
600          "usage: getsom [-s] [-b] [-f] <path>\n"
601          "\t-s: Only show the size value of the SOM data for a given file\n"
602          "\t-b: Only show the blocks value of the SOM data for a given file\n"
603          "\t-f: Only show the flags value of the SOM data for a given file\n"},
604         {"help", Parser_help, 0, "help"},
605         {"exit", Parser_quit, 0, "quit"},
606         {"quit", Parser_quit, 0, "quit"},
607         {"--version", Parser_version, 0,
608          "output build version of the utility and exit"},
609         {"--list-commands", lfs_list_commands, 0,
610          "list commands supported by the utility and exit"},
611         { 0, 0, 0, NULL }
612 };
613
614
615 static int check_hashtype(const char *hashtype)
616 {
617         int i;
618
619         for (i = LMV_HASH_TYPE_ALL_CHARS; i < LMV_HASH_TYPE_MAX; i++)
620                 if (strcmp(hashtype, mdt_hash_name[i]) == 0)
621                         return i;
622
623         return 0;
624 }
625
626
627 static const char *error_loc = "syserror";
628
629 enum {
630         MIGRATION_NONBLOCK      = 1 << 0,
631         MIGRATION_MIRROR        = 1 << 1,
632         MIGRATION_NONDIRECT     = 1 << 2,
633 };
634
635 static int lfs_component_create(char *fname, int open_flags, mode_t open_mode,
636                                 struct llapi_layout *layout);
637
638 static int
639 migrate_open_files(const char *name, __u64 migration_flags,
640                    const struct llapi_stripe_param *param,
641                    struct llapi_layout *layout, int *fd_src, int *fd_tgt)
642 {
643         int                      fd = -1;
644         int                      fdv = -1;
645         int                      rflags;
646         int                      mdt_index;
647         int                      random_value;
648         char                     parent[PATH_MAX];
649         char                     volatile_file[PATH_MAX];
650         char                    *ptr;
651         int                      rc;
652         struct stat              st;
653         struct stat              stv;
654
655         if (param == NULL && layout == NULL) {
656                 error_loc = "layout information";
657                 return -EINVAL;
658         }
659
660         /* search for file directory pathname */
661         if (strlen(name) > sizeof(parent) - 1) {
662                 error_loc = "source file name";
663                 return -ERANGE;
664         }
665
666         strncpy(parent, name, sizeof(parent));
667         ptr = strrchr(parent, '/');
668         if (ptr == NULL) {
669                 if (getcwd(parent, sizeof(parent)) == NULL) {
670                         error_loc = "getcwd";
671                         return -errno;
672                 }
673         } else {
674                 if (ptr == parent) /* leading '/' */
675                         ptr = parent + 1;
676                 *ptr = '\0';
677         }
678
679         /* open file, direct io */
680         /* even if the file is only read, WR mode is nedeed to allow
681          * layout swap on fd */
682         rflags = O_RDWR;
683         if (!(migration_flags & MIGRATION_NONDIRECT))
684                 rflags |= O_DIRECT;
685         fd = open(name, rflags);
686         if (fd < 0) {
687                 rc = -errno;
688                 error_loc = "cannot open source file";
689                 return rc;
690         }
691
692         rc = llapi_file_fget_mdtidx(fd, &mdt_index);
693         if (rc < 0) {
694                 error_loc = "cannot get MDT index";
695                 goto out;
696         }
697
698         do {
699                 int open_flags = O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW;
700                 mode_t open_mode = S_IRUSR | S_IWUSR;
701
702                 random_value = random();
703                 rc = snprintf(volatile_file, sizeof(volatile_file),
704                               "%s/%s:%.4X:%.4X", parent, LUSTRE_VOLATILE_HDR,
705                               mdt_index, random_value);
706                 if (rc >= sizeof(volatile_file)) {
707                         rc = -ENAMETOOLONG;
708                         break;
709                 }
710
711                 /* create, open a volatile file, use caching (ie no directio) */
712                 if (param != NULL)
713                         fdv = llapi_file_open_param(volatile_file, open_flags,
714                                                     open_mode, param);
715                 else
716                         fdv = lfs_component_create(volatile_file, open_flags,
717                                                    open_mode, layout);
718         } while (fdv < 0 && (rc = fdv) == -EEXIST);
719
720         if (rc < 0) {
721                 error_loc = "cannot create volatile file";
722                 goto out;
723         }
724
725         /* In case the MDT does not support creation of volatile files
726          * we should try to unlink it. */
727         (void)unlink(volatile_file);
728
729         /* Not-owner (root?) special case.
730          * Need to set owner/group of volatile file like original.
731          * This will allow to pass related check during layout_swap.
732          */
733         rc = fstat(fd, &st);
734         if (rc != 0) {
735                 rc = -errno;
736                 error_loc = "cannot stat source file";
737                 goto out;
738         }
739
740         rc = fstat(fdv, &stv);
741         if (rc != 0) {
742                 rc = -errno;
743                 error_loc = "cannot stat volatile";
744                 goto out;
745         }
746
747         if (st.st_uid != stv.st_uid || st.st_gid != stv.st_gid) {
748                 rc = fchown(fdv, st.st_uid, st.st_gid);
749                 if (rc != 0) {
750                         rc = -errno;
751                         error_loc = "cannot change ownwership of volatile";
752                         goto out;
753                 }
754         }
755
756 out:
757         if (rc < 0) {
758                 if (fd > 0)
759                         close(fd);
760                 if (fdv > 0)
761                         close(fdv);
762         } else {
763                 *fd_src = fd;
764                 *fd_tgt = fdv;
765                 error_loc = NULL;
766         }
767         return rc;
768 }
769
770 static int migrate_copy_data(int fd_src, int fd_dst, int (*check_file)(int))
771 {
772         struct llapi_layout *layout;
773         size_t   buf_size = 4 * 1024 * 1024;
774         void    *buf = NULL;
775         ssize_t  rsize = -1;
776         ssize_t  wsize = 0;
777         size_t   rpos = 0;
778         size_t   wpos = 0;
779         off_t    bufoff = 0;
780         int      rc;
781
782         layout = llapi_layout_get_by_fd(fd_src, 0);
783         if (layout != NULL) {
784                 uint64_t stripe_size;
785
786                 rc = llapi_layout_stripe_size_get(layout, &stripe_size);
787                 if (rc == 0)
788                         buf_size = stripe_size;
789
790                 llapi_layout_free(layout);
791         }
792
793         /* Use a page-aligned buffer for direct I/O */
794         rc = posix_memalign(&buf, getpagesize(), buf_size);
795         if (rc != 0)
796                 return -rc;
797
798         while (1) {
799                 /* read new data only if we have written all
800                  * previously read data */
801                 if (wpos == rpos) {
802                         if (check_file) {
803                                 rc = check_file(fd_src);
804                                 if (rc < 0)
805                                         break;
806                         }
807
808                         rsize = read(fd_src, buf, buf_size);
809                         if (rsize < 0) {
810                                 rc = -errno;
811                                 break;
812                         }
813                         rpos += rsize;
814                         bufoff = 0;
815                 }
816                 /* eof ? */
817                 if (rsize == 0)
818                         break;
819
820                 wsize = write(fd_dst, buf + bufoff, rpos - wpos);
821                 if (wsize < 0) {
822                         rc = -errno;
823                         break;
824                 }
825                 wpos += wsize;
826                 bufoff += wsize;
827         }
828
829         if (rc == 0) {
830                 rc = fsync(fd_dst);
831                 if (rc < 0)
832                         rc = -errno;
833         }
834
835         free(buf);
836         return rc;
837 }
838
839 static int migrate_copy_timestamps(int fd, int fdv)
840 {
841         struct stat st;
842
843         if (fstat(fd, &st) == 0) {
844                 struct timeval tv[2] = {
845                         {.tv_sec = st.st_atime},
846                         {.tv_sec = st.st_mtime}
847                 };
848
849                 return futimes(fdv, tv);
850         }
851
852         return -errno;
853 }
854
855 static int migrate_block(int fd, int fdv)
856 {
857         __u64   dv1;
858         int     gid;
859         int     rc;
860         int     rc2;
861
862         rc = llapi_get_data_version(fd, &dv1, LL_DV_RD_FLUSH);
863         if (rc < 0) {
864                 error_loc = "cannot get dataversion";
865                 return rc;
866         }
867
868         do
869                 gid = random();
870         while (gid == 0);
871
872         /* The grouplock blocks all concurrent accesses to the file.
873          * It has to be taken after llapi_get_data_version as it would
874          * block it too. */
875         rc = llapi_group_lock(fd, gid);
876         if (rc < 0) {
877                 error_loc = "cannot get group lock";
878                 return rc;
879         }
880
881         rc = migrate_copy_data(fd, fdv, NULL);
882         if (rc < 0) {
883                 error_loc = "data copy failed";
884                 goto out_unlock;
885         }
886
887         /* Make sure we keep original atime/mtime values */
888         rc = migrate_copy_timestamps(fd, fdv);
889         if (rc < 0) {
890                 error_loc = "timestamp copy failed";
891                 goto out_unlock;
892         }
893
894         /* swap layouts
895          * for a migration we need to check data version on file did
896          * not change.
897          *
898          * Pass in gid=0 since we already own grouplock. */
899         rc = llapi_fswap_layouts_grouplock(fd, fdv, dv1, 0, 0,
900                                            SWAP_LAYOUTS_CHECK_DV1);
901         if (rc == -EAGAIN) {
902                 error_loc = "file changed";
903                 goto out_unlock;
904         } else if (rc < 0) {
905                 error_loc = "cannot swap layout";
906                 goto out_unlock;
907         }
908
909 out_unlock:
910         rc2 = llapi_group_unlock(fd, gid);
911         if (rc2 < 0 && rc == 0) {
912                 error_loc = "unlock group lock";
913                 rc = rc2;
914         }
915
916         return rc;
917 }
918
919 /**
920  * Internal helper for migrate_copy_data(). Check lease and report error if
921  * need be.
922  *
923  * \param[in]  fd           File descriptor on which to check the lease.
924  *
925  * \retval 0       Migration can keep on going.
926  * \retval -errno  Error occurred, abort migration.
927  */
928 static int check_lease(int fd)
929 {
930         int rc;
931
932         rc = llapi_lease_check(fd);
933         if (rc > 0)
934                 return 0; /* llapi_check_lease returns > 0 on success. */
935
936         return -EBUSY;
937 }
938
939 static int migrate_nonblock(int fd, int fdv)
940 {
941         __u64   dv1;
942         __u64   dv2;
943         int     rc;
944
945         rc = llapi_get_data_version(fd, &dv1, LL_DV_RD_FLUSH);
946         if (rc < 0) {
947                 error_loc = "cannot get data version";
948                 return rc;
949         }
950
951         rc = migrate_copy_data(fd, fdv, check_lease);
952         if (rc < 0) {
953                 error_loc = "data copy failed";
954                 return rc;
955         }
956
957         rc = llapi_get_data_version(fd, &dv2, LL_DV_RD_FLUSH);
958         if (rc != 0) {
959                 error_loc = "cannot get data version";
960                 return rc;
961         }
962
963         if (dv1 != dv2) {
964                 rc = -EAGAIN;
965                 error_loc = "source file changed";
966                 return rc;
967         }
968
969         /* Make sure we keep original atime/mtime values */
970         rc = migrate_copy_timestamps(fd, fdv);
971         if (rc < 0) {
972                 error_loc = "timestamp copy failed";
973                 return rc;
974         }
975
976         return 0;
977 }
978
979 static int lfs_component_set(char *fname, int comp_id,
980                              __u32 flags, __u32 neg_flags)
981 {
982         __u32 ids[2];
983         __u32 flags_array[2];
984         size_t count = 0;
985         int rc;
986
987         if (flags) {
988                 ids[count] = comp_id;
989                 flags_array[count] = flags;
990                 ++count;
991         }
992
993         if (neg_flags) {
994                 ids[count] = comp_id;
995                 flags_array[count] = neg_flags | LCME_FL_NEG;
996                 ++count;
997         }
998
999         rc = llapi_layout_file_comp_set(fname, ids, flags_array, count);
1000         if (rc) {
1001                 if (errno == EUCLEAN) {
1002                         rc = -errno;
1003                         fprintf(stderr,
1004                                 "%s: cannot set 'stale' flag on component '%#x' of the last non-stale mirror of '%s'\n",
1005                                 progname, comp_id, fname);
1006                 } else {
1007                         fprintf(stderr,
1008                                 "%s: cannot change the flags of component '%#x' of file '%s': %x / ^(%x)\n",
1009                                 progname, comp_id, fname, flags, neg_flags);
1010                 }
1011         }
1012
1013         return rc;
1014 }
1015
1016 static int lfs_component_del(char *fname, __u32 comp_id,
1017                              __u32 flags, __u32 neg_flags)
1018 {
1019         int     rc = 0;
1020
1021         if (flags && neg_flags)
1022                 return -EINVAL;
1023
1024         if (!flags && neg_flags)
1025                 flags = neg_flags | LCME_FL_NEG;
1026
1027         if ((flags && comp_id) || (!flags && !comp_id))
1028                 return -EINVAL;
1029
1030         /* LCME_FL_INIT is the only supported flag in PFL */
1031         if (flags) {
1032                 if (flags & ~LCME_KNOWN_FLAGS) {
1033                         fprintf(stderr,
1034                                 "%s setstripe: unknown flags %#x\n",
1035                                 progname, flags);
1036                         return -EINVAL;
1037                 }
1038         } else if (comp_id > LCME_ID_MAX) {
1039                 fprintf(stderr, "%s setstripe: invalid component id %u\n",
1040                         progname, comp_id);
1041                 return -EINVAL;
1042         }
1043
1044         rc = llapi_layout_file_comp_del(fname, comp_id, flags);
1045         if (rc)
1046                 fprintf(stderr,
1047                         "%s setstripe: cannot delete component %#x from '%s': %s\n",
1048                         progname, comp_id, fname, strerror(errno));
1049         return rc;
1050 }
1051
1052 static int lfs_component_add(char *fname, struct llapi_layout *layout)
1053 {
1054         int     rc;
1055
1056         if (layout == NULL)
1057                 return -EINVAL;
1058
1059         rc = llapi_layout_file_comp_add(fname, layout);
1060         if (rc)
1061                 fprintf(stderr, "Add layout component(s) to %s failed. %s\n",
1062                         fname, strerror(errno));
1063         return rc;
1064 }
1065
1066 static int lfs_component_create(char *fname, int open_flags, mode_t open_mode,
1067                                 struct llapi_layout *layout)
1068 {
1069         struct stat     st;
1070         int     fd;
1071
1072         if (layout == NULL)
1073                 return -EINVAL;
1074
1075         fd = lstat(fname, &st);
1076         if (fd == 0 && S_ISDIR(st.st_mode))
1077                 open_flags = O_DIRECTORY | O_RDONLY;
1078
1079         fd = llapi_layout_file_open(fname, open_flags, open_mode, layout);
1080         if (fd < 0)
1081                 fprintf(stderr, "%s: cannot %s '%s': %s\n", progname,
1082                         S_ISDIR(st.st_mode) ?
1083                                 "set default composite layout for" :
1084                                 "create composite file",
1085                         fname, strerror(errno));
1086         return fd;
1087 }
1088
1089 static int lfs_migrate(char *name, __u64 migration_flags,
1090                        struct llapi_stripe_param *param,
1091                        struct llapi_layout *layout)
1092 {
1093         int fd = -1;
1094         int fdv = -1;
1095         int rc;
1096
1097         rc = migrate_open_files(name, migration_flags, param, layout,
1098                                 &fd, &fdv);
1099         if (rc < 0)
1100                 goto out;
1101
1102         if (!(migration_flags & MIGRATION_NONBLOCK)) {
1103                 /* Blocking mode (forced if servers do not support file lease).
1104                  * It is also the default mode, since we cannot distinguish
1105                  * between a broken lease and a server that does not support
1106                  * atomic swap/close (LU-6785) */
1107                 rc = migrate_block(fd, fdv);
1108                 goto out;
1109         }
1110
1111         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
1112         if (rc < 0) {
1113                 error_loc = "cannot get lease";
1114                 goto out;
1115         }
1116
1117         rc = migrate_nonblock(fd, fdv);
1118         if (rc < 0) {
1119                 llapi_lease_release(fd);
1120                 goto out;
1121         }
1122
1123         /* Atomically put lease, swap layouts and close.
1124          * for a migration we need to check data version on file did
1125          * not change. */
1126         rc = llapi_fswap_layouts(fd, fdv, 0, 0, SWAP_LAYOUTS_CLOSE);
1127         if (rc < 0) {
1128                 error_loc = "cannot swap layout";
1129                 goto out;
1130         }
1131
1132 out:
1133         if (fd >= 0)
1134                 close(fd);
1135
1136         if (fdv >= 0)
1137                 close(fdv);
1138
1139         if (rc < 0)
1140                 fprintf(stderr, "error: %s: %s: %s: %s\n",
1141                         progname, name, error_loc, strerror(-rc));
1142         return rc;
1143 }
1144
1145 static int comp_str2flags(char *string, __u32 *flags, __u32 *neg_flags)
1146 {
1147         char *name;
1148
1149         if (string == NULL)
1150                 return -EINVAL;
1151
1152         *flags = 0;
1153         *neg_flags = 0;
1154         for (name = strtok(string, ","); name; name = strtok(NULL, ",")) {
1155                 bool found = false;
1156                 int i;
1157
1158                 for (i = 0; i < ARRAY_SIZE(comp_flags_table); i++) {
1159                         __u32 comp_flag = comp_flags_table[i].cfn_flag;
1160                         const char *comp_name = comp_flags_table[i].cfn_name;
1161
1162                         if (strcmp(name, comp_name) == 0) {
1163                                 *flags |= comp_flag;
1164                                 found = true;
1165                         } else if (strncmp(name, "^", 1) == 0 &&
1166                                    strcmp(name + 1, comp_name) == 0) {
1167                                 *neg_flags |= comp_flag;
1168                                 found = true;
1169                         }
1170                 }
1171                 if (!found) {
1172                         llapi_printf(LLAPI_MSG_ERROR,
1173                                      "%s: component flag '%s' not supported\n",
1174                                      progname, name);
1175                         return -EINVAL;
1176                 }
1177         }
1178
1179         if (!*flags && !*neg_flags)
1180                 return -EINVAL;
1181
1182         /* don't allow to set and exclude the same flag */
1183         if (*flags & *neg_flags)
1184                 return -EINVAL;
1185
1186         return 0;
1187 }
1188
1189 static int mirror_str2state(char *string, __u16 *state, __u16 *neg_state)
1190 {
1191         if (string == NULL)
1192                 return -EINVAL;
1193
1194         *state = 0;
1195         *neg_state = 0;
1196
1197         if (strncmp(string, "^", 1) == 0) {
1198                 *neg_state = llapi_layout_string_flags(string + 1);
1199                 if (*neg_state != 0)
1200                         return 0;
1201         } else {
1202                 *state = llapi_layout_string_flags(string);
1203                 if (*state != 0)
1204                         return 0;
1205         }
1206
1207         llapi_printf(LLAPI_MSG_ERROR,
1208                      "%s: mirrored file state '%s' not supported\n",
1209                      progname, string);
1210         return -EINVAL;
1211 }
1212
1213 /**
1214  * struct mirror_args - Command-line arguments for mirror(s).
1215  * @m_count:  Number of mirrors to be created with this layout.
1216  * @m_flags:  Mirror level flags, only 'prefer' is supported.
1217  * @m_layout: Mirror layout.
1218  * @m_file:   A victim file. Its layout will be split and used as a mirror.
1219  * @m_next:   Point to the next node of the list.
1220  *
1221  * Command-line arguments for mirror(s) will be parsed and stored in
1222  * a linked list that consists of this structure.
1223  */
1224 struct mirror_args {
1225         __u32                   m_count;
1226         __u32                   m_flags;
1227         struct llapi_layout     *m_layout;
1228         const char              *m_file;
1229         struct mirror_args      *m_next;
1230 };
1231
1232 static int mirror_sanity_check_flags(struct llapi_layout *layout, void *unused)
1233 {
1234         uint32_t flags;
1235         int rc;
1236
1237         rc = llapi_layout_comp_flags_get(layout, &flags);
1238         if (rc)
1239                 return -errno;
1240
1241         if (flags & LCME_FL_NEG) {
1242                 fprintf(stderr, "error: %s: negative flags are not supported\n",
1243                         progname);
1244                 return -EINVAL;
1245         }
1246
1247         if (flags & LCME_FL_STALE) {
1248                 fprintf(stderr, "error: %s: setting '%s' is not supported\n",
1249                         progname, comp_flags_table[LCME_FL_STALE].cfn_name);
1250                 return -EINVAL;
1251         }
1252
1253         return LLAPI_LAYOUT_ITER_CONT;
1254 }
1255
1256 static inline int mirror_sanity_check_one(struct llapi_layout *layout)
1257 {
1258         uint64_t start, end;
1259         uint64_t pattern;
1260         int rc;
1261
1262         /* LU-10112: do not support dom+flr in phase 1 */
1263         rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_FIRST);
1264         if (rc)
1265                 return -errno;
1266
1267         rc = llapi_layout_pattern_get(layout, &pattern);
1268         if (rc)
1269                 return -errno;
1270
1271         if (pattern == LOV_PATTERN_MDT || pattern == LLAPI_LAYOUT_MDT) {
1272                 fprintf(stderr, "error: %s: doesn't support dom+flr for now\n",
1273                         progname);
1274                 return -ENOTSUP;
1275         }
1276
1277         rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_LAST);
1278         if (rc)
1279                 return -errno;
1280
1281         rc = llapi_layout_comp_extent_get(layout, &start, &end);
1282         if (rc)
1283                 return -errno;
1284
1285         if (end != LUSTRE_EOF) {
1286                 fprintf(stderr, "error: %s: mirror layout doesn't reach eof\n",
1287                         progname);
1288                 return -EINVAL;
1289         }
1290
1291         rc = llapi_layout_comp_iterate(layout, mirror_sanity_check_flags, NULL);
1292         return rc;
1293 }
1294
1295 /**
1296  * enum mirror_flags - Flags for extending a mirrored file.
1297  * @MF_NO_VERIFY: Indicates not to verify the mirror(s) from victim file(s)
1298  *             in case the victim file(s) contains the same data as the
1299  *             original mirrored file.
1300  * @MF_DESTROY: Indicates to delete the mirror from the mirrored file.
1301  * @MF_COMP_ID: specified component id instead of mirror id
1302  *
1303  * Flags for extending a mirrored file.
1304  */
1305 enum mirror_flags {
1306         MF_NO_VERIFY    = 0x1,
1307         MF_DESTROY      = 0x2,
1308         MF_COMP_ID      = 0x4,
1309         MF_COMP_POOL    = 0x8,
1310 };
1311
1312 /**
1313  * mirror_create_sanity_check() - Check mirror list.
1314  * @list:  A linked list that stores the mirror arguments.
1315  *
1316  * This function does a sanity check on @list for creating
1317  * a mirrored file.
1318  *
1319  * Return: 0 on success or a negative error code on failure.
1320  */
1321 static int mirror_create_sanity_check(const char *fname,
1322                                       struct mirror_args *list)
1323 {
1324         int rc = 0;
1325         bool has_m_file = false;
1326         bool has_m_layout = false;
1327
1328         if (list == NULL)
1329                 return -EINVAL;
1330
1331         if (fname) {
1332                 struct llapi_layout *layout;
1333
1334                 layout = llapi_layout_get_by_path(fname, 0);
1335                 if (!layout) {
1336                         fprintf(stderr,
1337                                 "error: %s: file '%s' couldn't get layout\n",
1338                                 progname, fname);
1339                         return -ENODATA;
1340                 }
1341
1342                 rc = mirror_sanity_check_one(layout);
1343                 llapi_layout_free(layout);
1344
1345                 if (rc)
1346                         return rc;
1347         }
1348
1349         while (list != NULL) {
1350                 if (list->m_file != NULL) {
1351                         has_m_file = true;
1352                         llapi_layout_free(list->m_layout);
1353
1354                         list->m_layout =
1355                                 llapi_layout_get_by_path(list->m_file, 0);
1356                         if (list->m_layout == NULL) {
1357                                 fprintf(stderr,
1358                                         "error: %s: file '%s' has no layout\n",
1359                                         progname, list->m_file);
1360                                 return -ENODATA;
1361                         }
1362                 } else {
1363                         has_m_layout = true;
1364                         if (list->m_layout == NULL) {
1365                                 fprintf(stderr, "error: %s: no mirror layout\n",
1366                                         progname);
1367                                 return -EINVAL;
1368                         }
1369                 }
1370
1371                 rc = mirror_sanity_check_one(list->m_layout);
1372                 if (rc)
1373                         return rc;
1374
1375                 list = list->m_next;
1376         }
1377
1378         if (has_m_file && has_m_layout) {
1379                 fprintf(stderr,
1380                         "error: %s: -f <victim_file> option should not be specified with setstripe options\n",
1381                         progname);
1382                 return -EINVAL;
1383         }
1384
1385         return 0;
1386 }
1387
1388 static int mirror_set_flags(struct llapi_layout *layout, void *cbdata)
1389 {
1390         __u32 mirror_flags = *(__u32 *)cbdata;
1391         uint32_t flags;
1392         int rc;
1393
1394         rc = llapi_layout_comp_flags_get(layout, &flags);
1395         if (rc < 0)
1396                 return rc;
1397
1398         if (!flags) {
1399                 rc = llapi_layout_comp_flags_set(layout, mirror_flags);
1400                 if (rc)
1401                         return rc;
1402         }
1403
1404         return LLAPI_LAYOUT_ITER_CONT;
1405 }
1406
1407 /**
1408  * mirror_create() - Create a mirrored file.
1409  * @fname:        The file to be created.
1410  * @mirror_list:  A linked list that stores the mirror arguments.
1411  *
1412  * This function creates a mirrored file @fname with the mirror(s)
1413  * from @mirror_list.
1414  *
1415  * Return: 0 on success or a negative error code on failure.
1416  */
1417 static int mirror_create(char *fname, struct mirror_args *mirror_list)
1418 {
1419         struct llapi_layout *layout = NULL;
1420         struct mirror_args *cur_mirror = NULL;
1421         uint16_t mirror_count = 0;
1422         int i = 0;
1423         int rc = 0;
1424
1425         rc = mirror_create_sanity_check(NULL, mirror_list);
1426         if (rc)
1427                 return rc;
1428
1429         cur_mirror = mirror_list;
1430         while (cur_mirror != NULL) {
1431                 rc = llapi_layout_comp_iterate(cur_mirror->m_layout,
1432                                                mirror_set_flags,
1433                                                &cur_mirror->m_flags);
1434                 if (rc) {
1435                         rc = -errno;
1436                         fprintf(stderr, "%s: failed to set mirror flags\n",
1437                                 progname);
1438                         goto error;
1439                 }
1440
1441                 for (i = 0; i < cur_mirror->m_count; i++) {
1442                         rc = llapi_layout_merge(&layout, cur_mirror->m_layout);
1443                         if (rc) {
1444                                 rc = -errno;
1445                                 fprintf(stderr, "error: %s: "
1446                                         "merge layout failed: %s\n",
1447                                         progname, strerror(errno));
1448                                 goto error;
1449                         }
1450                 }
1451                 mirror_count += cur_mirror->m_count;
1452                 cur_mirror = cur_mirror->m_next;
1453         }
1454
1455         if (layout == NULL) {
1456                 fprintf(stderr, "error: %s: layout is NULL\n", progname);
1457                 return -EINVAL;
1458         }
1459
1460         rc = llapi_layout_mirror_count_set(layout, mirror_count);
1461         if (rc) {
1462                 rc = -errno;
1463                 fprintf(stderr, "error: %s: set mirror count failed: %s\n",
1464                         progname, strerror(errno));
1465                 goto error;
1466         }
1467
1468         rc = lfs_component_create(fname, O_CREAT | O_WRONLY, 0666,
1469                                   layout);
1470         if (rc >= 0) {
1471                 close(rc);
1472                 rc = 0;
1473         }
1474
1475 error:
1476         llapi_layout_free(layout);
1477         return rc;
1478 }
1479
1480 /**
1481  * Compare files and check lease on @fd.
1482  *
1483  * \retval bytes number of bytes are the same
1484  */
1485 static ssize_t mirror_file_compare(int fd, int fdv)
1486 {
1487         const size_t buflen = 4 * 1024 * 1024; /* 4M */
1488         void *buf;
1489         ssize_t bytes_done = 0;
1490         ssize_t bytes_read = 0;
1491
1492         buf = malloc(buflen * 2);
1493         if (!buf)
1494                 return -ENOMEM;
1495
1496         while (1) {
1497                 if (!llapi_lease_check(fd)) {
1498                         bytes_done = -EBUSY;
1499                         break;
1500                 }
1501
1502                 bytes_read = read(fd, buf, buflen);
1503                 if (bytes_read <= 0)
1504                         break;
1505
1506                 if (bytes_read != read(fdv, buf + buflen, buflen))
1507                         break;
1508
1509                 /* XXX: should compute the checksum on each buffer and then
1510                  * compare checksum to avoid cache collision */
1511                 if (memcmp(buf, buf + buflen, bytes_read))
1512                         break;
1513
1514                 bytes_done += bytes_read;
1515         }
1516
1517         free(buf);
1518
1519         return bytes_done;
1520 }
1521
1522 static int mirror_extend_file(const char *fname, const char *victim_file,
1523                               enum mirror_flags mirror_flags)
1524 {
1525         int fd = -1;
1526         int fdv = -1;
1527         struct stat stbuf;
1528         struct stat stbuf_v;
1529         struct ll_ioc_lease *data = NULL;
1530         int rc;
1531
1532         fd = open(fname, O_RDWR);
1533         if (fd < 0) {
1534                 error_loc = "open source file";
1535                 rc = -errno;
1536                 goto out;
1537         }
1538
1539         fdv = open(victim_file, O_RDWR);
1540         if (fdv < 0) {
1541                 error_loc = "open target file";
1542                 rc = -errno;
1543                 goto out;
1544         }
1545
1546         if (fstat(fd, &stbuf) || fstat(fdv, &stbuf_v)) {
1547                 error_loc = "stat source or target file";
1548                 rc = -errno;
1549                 goto out;
1550         }
1551
1552         if (stbuf.st_dev != stbuf_v.st_dev) {
1553                 error_loc = "stat source and target file";
1554                 rc = -EXDEV;
1555                 goto out;
1556         }
1557
1558         /* mirrors should be of the same size */
1559         if (stbuf.st_size != stbuf_v.st_size) {
1560                 error_loc = "file sizes don't match";
1561                 rc = -EINVAL;
1562                 goto out;
1563         }
1564
1565         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
1566         if (rc < 0) {
1567                 error_loc = "cannot get lease";
1568                 goto out;
1569         }
1570
1571         if (!(mirror_flags & MF_NO_VERIFY)) {
1572                 ssize_t ret;
1573                 /* mirrors should have the same contents */
1574                 ret = mirror_file_compare(fd, fdv);
1575                 if (ret != stbuf.st_size) {
1576                         error_loc = "file busy or contents don't match";
1577                         rc = ret < 0 ? ret : -EINVAL;
1578                         goto out;
1579                 }
1580         }
1581
1582         /* Get rid of caching pages from clients */
1583         rc = llapi_file_flush(fd);
1584         if (rc < 0) {
1585                 error_loc = "cannot get data version";
1586                 goto out;
1587         }
1588
1589         rc = llapi_file_flush(fdv);
1590         if (rc < 0) {
1591                 error_loc = "cannot get data version";
1592                 goto out;
1593
1594         }
1595
1596         /* Make sure we keep original atime/mtime values */
1597         rc = migrate_copy_timestamps(fd, fdv);
1598         if (rc < 0) {
1599                 error_loc = "cannot copy timestamp";
1600                 goto out;
1601         }
1602
1603         /* Atomically put lease, merge layouts and close. */
1604         data = calloc(1, offsetof(typeof(*data), lil_ids[1]));
1605         if (!data) {
1606                 error_loc = "memory allocation";
1607                 goto out;
1608         }
1609         data->lil_mode = LL_LEASE_UNLCK;
1610         data->lil_flags = LL_LEASE_LAYOUT_MERGE;
1611         data->lil_count = 1;
1612         data->lil_ids[0] = fdv;
1613         rc = llapi_lease_set(fd, data);
1614         if (rc < 0) {
1615                 error_loc = "cannot merge layout";
1616                 goto out;
1617         } else if (rc == 0) {
1618                 rc = -EBUSY;
1619                 error_loc = "lost lease lock";
1620                 goto out;
1621         }
1622         rc = 0;
1623
1624 out:
1625         if (data)
1626                 free(data);
1627         if (fd >= 0)
1628                 close(fd);
1629         if (fdv >= 0)
1630                 close(fdv);
1631         if (!rc)
1632                 (void) unlink(victim_file);
1633         if (rc < 0)
1634                 fprintf(stderr, "error: %s: %s: %s: %s\n",
1635                         progname, fname, error_loc, strerror(-rc));
1636         return rc;
1637 }
1638
1639 static int mirror_extend_layout(char *name, struct llapi_layout *layout)
1640 {
1641         struct ll_ioc_lease *data = NULL;
1642         int fd = -1;
1643         int fdv = -1;
1644         int rc;
1645
1646         rc = migrate_open_files(name, 0, NULL, layout, &fd, &fdv);
1647         if (rc < 0)
1648                 goto out;
1649
1650         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
1651         if (rc < 0) {
1652                 error_loc = "cannot get lease";
1653                 goto out;
1654         }
1655
1656         rc = migrate_nonblock(fd, fdv);
1657         if (rc < 0) {
1658                 llapi_lease_release(fd);
1659                 goto out;
1660         }
1661
1662         /* Atomically put lease, merge layouts and close. */
1663         data = calloc(1, offsetof(typeof(*data), lil_ids[1]));
1664         if (!data) {
1665                 error_loc = "memory allocation";
1666                 goto out;
1667         }
1668         data->lil_mode = LL_LEASE_UNLCK;
1669         data->lil_flags = LL_LEASE_LAYOUT_MERGE;
1670         data->lil_count = 1;
1671         data->lil_ids[0] = fdv;
1672         rc = llapi_lease_set(fd, data);
1673         if (rc < 0) {
1674                 error_loc = "cannot merge layout";
1675                 goto out;
1676         } else if (rc == 0) {
1677                 rc = -EBUSY;
1678                 error_loc = "lost lease lock";
1679                 goto out;
1680         }
1681         rc = 0;
1682
1683 out:
1684         if (data)
1685                 free(data);
1686         if (fd >= 0)
1687                 close(fd);
1688         if (fdv >= 0)
1689                 close(fdv);
1690         if (rc < 0)
1691                 fprintf(stderr, "error: %s: %s: %s: %s\n",
1692                         progname, name, error_loc, strerror(-rc));
1693         return rc;
1694 }
1695
1696 static int mirror_extend(char *fname, struct mirror_args *mirror_list,
1697                          enum mirror_flags mirror_flags)
1698 {
1699         int rc;
1700
1701         rc = mirror_create_sanity_check(fname, mirror_list);
1702         if (rc)
1703                 return rc;
1704
1705         while (mirror_list) {
1706                 if (mirror_list->m_file != NULL) {
1707                         rc = mirror_extend_file(fname, mirror_list->m_file,
1708                                                 mirror_flags);
1709                 } else {
1710                         __u32 mirror_count = mirror_list->m_count;
1711
1712                         while (mirror_count > 0) {
1713                                 rc = mirror_extend_layout(fname,
1714                                                         mirror_list->m_layout);
1715                                 if (rc)
1716                                         break;
1717
1718                                 --mirror_count;
1719                         }
1720                 }
1721                 if (rc)
1722                         break;
1723
1724                 mirror_list = mirror_list->m_next;
1725         }
1726
1727         return rc;
1728 }
1729
1730 static int find_mirror_id(struct llapi_layout *layout, void *cbdata)
1731 {
1732         uint32_t id;
1733         int rc;
1734
1735         rc = llapi_layout_mirror_id_get(layout, &id);
1736         if (rc < 0)
1737                 return rc;
1738
1739         if ((__u16)id == *(__u16 *)cbdata)
1740                 return LLAPI_LAYOUT_ITER_STOP;
1741
1742         return LLAPI_LAYOUT_ITER_CONT;
1743 }
1744
1745 static int find_comp_id(struct llapi_layout *layout, void *cbdata)
1746 {
1747         uint32_t id;
1748         int rc;
1749
1750         rc = llapi_layout_comp_id_get(layout, &id);
1751         if (rc < 0)
1752                 return rc;
1753
1754         if (id == *(__u32 *)cbdata)
1755                 return LLAPI_LAYOUT_ITER_STOP;
1756
1757         return LLAPI_LAYOUT_ITER_CONT;
1758 }
1759
1760 struct pool_to_id_cbdata {
1761         const char *pool;
1762         __u32 id;
1763 };
1764 static int find_comp_id_by_pool(struct llapi_layout *layout, void *cbdata)
1765 {
1766         char buf[LOV_MAXPOOLNAME + 1];
1767         struct pool_to_id_cbdata *d = (void *)cbdata;
1768         uint32_t id;
1769         int rc;
1770
1771         rc = llapi_layout_pool_name_get(layout, buf, sizeof(buf));
1772         if (rc < 0)
1773                 return rc;
1774         if (strcmp(d->pool, buf))
1775                 return LLAPI_LAYOUT_ITER_CONT;
1776
1777         rc = llapi_layout_mirror_id_get(layout, &id);
1778         if (rc < 0)
1779                 return rc;
1780         d->id = id;
1781
1782         return LLAPI_LAYOUT_ITER_STOP;
1783 }
1784
1785 struct collect_ids_data {
1786         __u16   *cid_ids;
1787         int     cid_count;
1788         __u16   cid_exclude;
1789 };
1790
1791 static int collect_mirror_id(struct llapi_layout *layout, void *cbdata)
1792 {
1793         struct collect_ids_data *cid = cbdata;
1794         uint32_t id;
1795         int rc;
1796
1797         rc = llapi_layout_mirror_id_get(layout, &id);
1798         if (rc < 0)
1799                 return rc;
1800
1801         if ((__u16)id != cid->cid_exclude) {
1802                 int i;
1803
1804                 for (i = 0; i < cid->cid_count; i++) {
1805                         /* already collected the mirror id */
1806                         if (id == cid->cid_ids[i])
1807                                 return LLAPI_LAYOUT_ITER_CONT;
1808                 }
1809                 cid->cid_ids[cid->cid_count] = id;
1810                 cid->cid_count++;
1811         }
1812
1813         return LLAPI_LAYOUT_ITER_CONT;
1814 }
1815
1816 /**
1817  * last_non_stale_mirror() - Check if a mirror is the last non-stale mirror.
1818  * @mirror_id: Mirror id to be checked.
1819  * @layout:    Mirror component list.
1820  *
1821  * This function checks if a mirror with specified @mirror_id is the last
1822  * non-stale mirror of a layout @layout.
1823  *
1824  * Return: true or false.
1825  */
1826 static inline
1827 bool last_non_stale_mirror(__u16 mirror_id, struct llapi_layout *layout)
1828 {
1829         __u16 mirror_ids[128] = { 0 };
1830         struct collect_ids_data cid = { .cid_ids = mirror_ids,
1831                                         .cid_count = 0,
1832                                         .cid_exclude = mirror_id, };
1833         int i;
1834
1835         llapi_layout_comp_iterate(layout, collect_mirror_id, &cid);
1836
1837         for (i = 0; i < cid.cid_count; i++) {
1838                 struct llapi_resync_comp comp_array[1024] = { { 0 } };
1839                 int comp_size = 0;
1840
1841                 comp_size = llapi_mirror_find_stale(layout, comp_array,
1842                                                     ARRAY_SIZE(comp_array),
1843                                                     &mirror_ids[i], 1);
1844                 if (comp_size == 0)
1845                         return false;
1846         }
1847
1848         return true;
1849 }
1850
1851 static int mirror_split(const char *fname, __u32 id, const char *pool,
1852                         enum mirror_flags mflags, const char *victim_file)
1853 {
1854         struct llapi_layout *layout;
1855         char parent[PATH_MAX];
1856         char victim[PATH_MAX];
1857         int flags = O_CREAT | O_EXCL | O_LOV_DELAY_CREATE | O_NOFOLLOW;
1858         char *ptr;
1859         struct ll_ioc_lease *data;
1860         uint16_t mirror_count;
1861         int mdt_index;
1862         int fd, fdv;
1863         int rc;
1864
1865         /* check fname contains mirror with mirror_id/comp_id */
1866         layout = llapi_layout_get_by_path(fname, 0);
1867         if (!layout) {
1868                 fprintf(stderr,
1869                         "error %s: file '%s' couldn't get layout\n",
1870                         progname, fname);
1871                 return -EINVAL;
1872         }
1873
1874         rc = mirror_sanity_check_one(layout);
1875         if (rc)
1876                 goto free_layout;
1877
1878         rc = llapi_layout_mirror_count_get(layout, &mirror_count);
1879         if (rc) {
1880                 fprintf(stderr,
1881                         "error %s: file '%s' couldn't get mirror count\n",
1882                         progname, fname);
1883                 goto free_layout;
1884         }
1885         if (mirror_count < 2) {
1886                 fprintf(stderr,
1887                         "error %s: file '%s' has %d component, cannot split\n",
1888                         progname, fname, mirror_count);
1889                 goto free_layout;
1890         }
1891
1892         if (mflags & MF_COMP_POOL) {
1893                 struct pool_to_id_cbdata data = { .pool = pool };
1894
1895                 rc = llapi_layout_comp_iterate(layout, find_comp_id_by_pool,
1896                                                &data);
1897                 id = data.id;
1898         } else if (mflags & MF_COMP_ID) {
1899                 rc = llapi_layout_comp_iterate(layout, find_comp_id, &id);
1900                 id = mirror_id_of(id);
1901         } else {
1902                 rc = llapi_layout_comp_iterate(layout, find_mirror_id, &id);
1903         }
1904         if (rc < 0) {
1905                 fprintf(stderr, "error %s: failed to iterate layout of '%s'\n",
1906                         progname, fname);
1907                 goto free_layout;
1908         } else if (rc == LLAPI_LAYOUT_ITER_CONT) {
1909                 fprintf(stderr,
1910                      "error %s: file '%s' does not contain mirror with id %u\n",
1911                         progname, fname, id);
1912                 goto free_layout;
1913         }
1914
1915         fd = open(fname, O_RDWR);
1916         if (fd < 0) {
1917                 fprintf(stderr,
1918                         "error %s: open file '%s' failed: %s\n",
1919                         progname, fname, strerror(errno));
1920                 goto free_layout;
1921         }
1922
1923         /* get victim file directory pathname */
1924         if (strlen(fname) > sizeof(parent) - 1) {
1925                 fprintf(stderr, "error %s: file name of '%s' too long\n",
1926                         progname, fname);
1927                 rc = -ERANGE;
1928                 goto close_fd;
1929         }
1930         strncpy(parent, fname, sizeof(parent));
1931         ptr = strrchr(parent, '/');
1932         if (ptr == NULL) {
1933                 if (getcwd(parent, sizeof(parent)) == NULL) {
1934                         fprintf(stderr, "error %s: getcwd failed: %s\n",
1935                                 progname, strerror(errno));
1936                         rc = -errno;
1937                         goto close_fd;
1938                 }
1939         } else {
1940                 if (ptr == parent)
1941                         ptr = parent + 1;
1942                 *ptr = '\0';
1943         }
1944
1945         rc = llapi_file_fget_mdtidx(fd, &mdt_index);
1946         if (rc < 0) {
1947                 fprintf(stderr, "%s: cannot get MDT index of '%s'\n",
1948                         progname, fname);
1949                 goto close_fd;
1950         }
1951
1952         if (victim_file == NULL) {
1953                 /* use a temp file to store the splitted layout */
1954                 if (mflags & MF_DESTROY) {
1955                         if (last_non_stale_mirror(id, layout)) {
1956                                 rc = -EUCLEAN;
1957                                 fprintf(stderr,
1958                                         "%s: cannot destroy the last non-stale mirror of file '%s'\n",
1959                                         progname, fname);
1960                                 goto close_fd;
1961                         }
1962
1963                         fdv = llapi_create_volatile_idx(parent, mdt_index,
1964                                                         O_LOV_DELAY_CREATE);
1965                 } else {
1966                         snprintf(victim, sizeof(victim), "%s.mirror~%u",
1967                                  fname, id);
1968                         fdv = open(victim, flags, S_IRUSR | S_IWUSR);
1969                 }
1970         } else {
1971                 /* user specified victim file */
1972                 fdv = open(victim_file, flags, S_IRUSR | S_IWUSR);
1973         }
1974
1975         if (fdv < 0) {
1976                 fprintf(stderr,
1977                         "error %s: create victim file failed: %s\n",
1978                         progname, strerror(errno));
1979                 goto close_fd;
1980         }
1981
1982         /* get lease lock of fname */
1983         rc = llapi_lease_acquire(fd, LL_LEASE_WRLCK);
1984         if (rc < 0) {
1985                 fprintf(stderr,
1986                         "error %s: cannot get lease of file '%s': %d\n",
1987                         progname, fname, rc);
1988                 goto close_victim;
1989         }
1990
1991         /* Atomatically put lease, split layouts and close. */
1992         data = malloc(offsetof(typeof(*data), lil_ids[2]));
1993         if (!data) {
1994                 rc = -ENOMEM;
1995                 goto close_victim;
1996         }
1997
1998         data->lil_mode = LL_LEASE_UNLCK;
1999         data->lil_flags = LL_LEASE_LAYOUT_SPLIT;
2000         data->lil_count = 2;
2001         data->lil_ids[0] = fdv;
2002         data->lil_ids[1] = id;
2003         rc = llapi_lease_set(fd, data);
2004         if (rc <= 0) {
2005                 if (rc == 0) /* lost lease lock */
2006                         rc = -EBUSY;
2007                 fprintf(stderr,
2008                         "error %s: cannot split '%s': %s\n",
2009                         progname, fname, strerror(-rc));
2010         } else {
2011                 rc = 0;
2012         }
2013         free(data);
2014
2015 close_victim:
2016         close(fdv);
2017 close_fd:
2018         close(fd);
2019 free_layout:
2020         llapi_layout_free(layout);
2021         return rc;
2022 }
2023
2024 /**
2025  * Parse a string containing an target index list into an array of integers.
2026  *
2027  * The input string contains a comma delimited list of individual
2028  * indices and ranges, for example "1,2-4,7". Add the indices into the
2029  * \a tgts array and remove duplicates.
2030  *
2031  * \param[out] tgts    array to store indices in
2032  * \param[in] size     size of \a tgts array
2033  * \param[in] offset   starting index in \a tgts
2034  * \param[in] arg      string containing OST index list
2035  *
2036  * \retval positive    number of indices in \a tgts
2037  * \retval -EINVAL     unable to parse \a arg
2038  */
2039 static int parse_targets(__u32 *tgts, int size, int offset, char *arg)
2040 {
2041         int rc;
2042         int nr = offset;
2043         int slots = size - offset;
2044         char *ptr = NULL;
2045         bool end_of_loop;
2046
2047         if (arg == NULL)
2048                 return -EINVAL;
2049
2050         end_of_loop = false;
2051         while (!end_of_loop) {
2052                 int start_index;
2053                 int end_index;
2054                 int i;
2055                 char *endptr = NULL;
2056
2057                 rc = -EINVAL;
2058
2059                 ptr = strchrnul(arg, ',');
2060
2061                 end_of_loop = *ptr == '\0';
2062                 *ptr = '\0';
2063
2064                 start_index = strtol(arg, &endptr, 0);
2065                 if (endptr == arg) /* no data at all */
2066                         break;
2067                 if (*endptr != '-' && *endptr != '\0') /* has invalid data */
2068                         break;
2069
2070                 end_index = start_index;
2071                 if (*endptr == '-') {
2072                         end_index = strtol(endptr + 1, &endptr, 0);
2073                         if (*endptr != '\0')
2074                                 break;
2075                         if (end_index < start_index)
2076                                 break;
2077                 }
2078
2079                 for (i = start_index; i <= end_index && slots > 0; i++) {
2080                         int j;
2081
2082                         /* remove duplicate */
2083                         for (j = 0; j < offset; j++) {
2084                                 if (tgts[j] == i)
2085                                         break;
2086                         }
2087                         if (j == offset) { /* no duplicate */
2088                                 tgts[nr++] = i;
2089                                 --slots;
2090                         }
2091                 }
2092                 if (slots == 0 && i < end_index)
2093                         break;
2094
2095                 *ptr = ',';
2096                 arg = ++ptr;
2097                 offset = nr;
2098                 rc = 0;
2099         }
2100         if (!end_of_loop && ptr != NULL)
2101                 *ptr = ',';
2102
2103         return rc < 0 ? rc : nr;
2104 }
2105
2106 struct lfs_setstripe_args {
2107         unsigned long long       lsa_comp_end;
2108         unsigned long long       lsa_stripe_size;
2109         long long                lsa_stripe_count;
2110         long long                lsa_stripe_off;
2111         __u32                    lsa_comp_flags;
2112         __u32                    lsa_comp_neg_flags;
2113         unsigned long long       lsa_pattern;
2114         unsigned int             lsa_mirror_count;
2115         int                      lsa_nr_tgts;
2116         bool                     lsa_first_comp;
2117         __u32                   *lsa_tgts;
2118         char                    *lsa_pool_name;
2119 };
2120
2121 static inline void setstripe_args_init(struct lfs_setstripe_args *lsa)
2122 {
2123         unsigned int mirror_count = lsa->lsa_mirror_count;
2124         bool first_comp = lsa->lsa_first_comp;
2125
2126         memset(lsa, 0, sizeof(*lsa));
2127
2128         lsa->lsa_stripe_size = LLAPI_LAYOUT_DEFAULT;
2129         lsa->lsa_stripe_count = LLAPI_LAYOUT_DEFAULT;
2130         lsa->lsa_stripe_off = LLAPI_LAYOUT_DEFAULT;
2131         lsa->lsa_pattern = LLAPI_LAYOUT_RAID0;
2132         lsa->lsa_pool_name = NULL;
2133
2134         lsa->lsa_mirror_count = mirror_count;
2135         lsa->lsa_first_comp = first_comp;
2136 }
2137
2138 /**
2139  * setstripe_args_init_inherit() - Initialize and inherit stripe options.
2140  * @lsa: Stripe options to be initialized and inherited.
2141  *
2142  * This function initializes stripe options in @lsa and inherit
2143  * stripe_size, stripe_count and OST pool_name options.
2144  *
2145  * Return: void.
2146  */
2147 static inline void setstripe_args_init_inherit(struct lfs_setstripe_args *lsa)
2148 {
2149         unsigned long long stripe_size;
2150         long long stripe_count;
2151         char *pool_name = NULL;
2152
2153         stripe_size = lsa->lsa_stripe_size;
2154         stripe_count = lsa->lsa_stripe_count;
2155         pool_name = lsa->lsa_pool_name;
2156
2157         setstripe_args_init(lsa);
2158
2159         lsa->lsa_stripe_size = stripe_size;
2160         lsa->lsa_stripe_count = stripe_count;
2161         lsa->lsa_pool_name = pool_name;
2162 }
2163
2164 static inline bool setstripe_args_specified(struct lfs_setstripe_args *lsa)
2165 {
2166         return (lsa->lsa_stripe_size != LLAPI_LAYOUT_DEFAULT ||
2167                 lsa->lsa_stripe_count != LLAPI_LAYOUT_DEFAULT ||
2168                 lsa->lsa_stripe_off != LLAPI_LAYOUT_DEFAULT ||
2169                 lsa->lsa_pattern != LLAPI_LAYOUT_RAID0 ||
2170                 lsa->lsa_comp_end != 0);
2171 }
2172
2173 /**
2174  * comp_args_to_layout() - Create or extend a composite layout.
2175  * @composite:       Pointer to the composite layout.
2176  * @lsa:             Stripe options for the new component.
2177  *
2178  * This function creates or extends a composite layout by adding a new
2179  * component with stripe options from @lsa.
2180  *
2181  * Return: 0 on success or an error code on failure.
2182  */
2183 static int comp_args_to_layout(struct llapi_layout **composite,
2184                                struct lfs_setstripe_args *lsa,
2185                                bool set_extent)
2186 {
2187         struct llapi_layout *layout = *composite;
2188         uint64_t prev_end = 0;
2189         int i = 0, rc;
2190
2191         if (layout == NULL) {
2192                 layout = llapi_layout_alloc();
2193                 if (layout == NULL) {
2194                         fprintf(stderr, "Alloc llapi_layout failed. %s\n",
2195                                 strerror(errno));
2196                         return -ENOMEM;
2197                 }
2198                 *composite = layout;
2199         } else {
2200                 uint64_t start;
2201
2202                 /* Get current component extent, current component
2203                  * must be the tail component. */
2204                 rc = llapi_layout_comp_extent_get(layout, &start, &prev_end);
2205                 if (rc) {
2206                         fprintf(stderr, "Get comp extent failed. %s\n",
2207                                 strerror(errno));
2208                         return rc;
2209                 }
2210
2211                 if (lsa->lsa_first_comp)
2212                         prev_end = 0;
2213
2214                 if (lsa->lsa_first_comp)
2215                         rc = llapi_layout_add_first_comp(layout);
2216                 else
2217                         rc = llapi_layout_comp_add(layout);
2218                 if (rc) {
2219                         fprintf(stderr, "Add component failed. %s\n",
2220                                 strerror(errno));
2221                         return rc;
2222                 }
2223         }
2224         /* reset lsa_first_comp */
2225         lsa->lsa_first_comp = false;
2226
2227         if (set_extent) {
2228                 rc = llapi_layout_comp_extent_set(layout, prev_end,
2229                                                   lsa->lsa_comp_end);
2230                 if (rc) {
2231                         fprintf(stderr, "Set extent [%lu, %llu) failed. %s\n",
2232                                 prev_end, lsa->lsa_comp_end, strerror(errno));
2233                         return rc;
2234                 }
2235         }
2236
2237         /* Data-on-MDT component setting */
2238         if (lsa->lsa_pattern == LLAPI_LAYOUT_MDT) {
2239                 /* In case of Data-on-MDT patterns the only extra option
2240                  * applicable is stripe size option. */
2241                 if (lsa->lsa_stripe_count != LLAPI_LAYOUT_DEFAULT) {
2242                         fprintf(stderr, "Option 'stripe-count' can't be "
2243                                 "specified with Data-on-MDT component: %lld\n",
2244                                 lsa->lsa_stripe_count);
2245                         return -EINVAL;
2246                 }
2247                 if (lsa->lsa_stripe_size != LLAPI_LAYOUT_DEFAULT) {
2248                         fprintf(stderr, "Option 'stripe-size' can't be "
2249                                 "specified with Data-on-MDT component: %llu\n",
2250                                 lsa->lsa_stripe_size);
2251                         return -EINVAL;
2252                 }
2253                 if (lsa->lsa_nr_tgts != 0) {
2254                         fprintf(stderr, "Option 'ost-list' can't be specified "
2255                                 "with Data-on-MDT component: '%i'\n",
2256                                 lsa->lsa_nr_tgts);
2257                         return -EINVAL;
2258                 }
2259                 if (lsa->lsa_stripe_off != LLAPI_LAYOUT_DEFAULT) {
2260                         fprintf(stderr, "Option 'stripe-offset' can't be "
2261                                 "specified with Data-on-MDT component: %lld\n",
2262                                 lsa->lsa_stripe_off);
2263                         return -EINVAL;
2264                 }
2265                 if (lsa->lsa_pool_name != 0) {
2266                         fprintf(stderr, "Option 'pool' can't be specified "
2267                                 "with Data-on-MDT component: '%s'\n",
2268                                 lsa->lsa_pool_name);
2269                         return -EINVAL;
2270                 }
2271
2272                 rc = llapi_layout_pattern_set(layout, lsa->lsa_pattern);
2273                 if (rc) {
2274                         fprintf(stderr, "Set stripe pattern %#llx failed. %s\n",
2275                                 lsa->lsa_pattern,
2276                                 strerror(errno));
2277                         return rc;
2278                 }
2279                 /* Data-on-MDT component has always single stripe up to end */
2280                 lsa->lsa_stripe_size = lsa->lsa_comp_end;
2281         }
2282
2283         rc = llapi_layout_stripe_size_set(layout, lsa->lsa_stripe_size);
2284         if (rc) {
2285                 fprintf(stderr, "Set stripe size %llu failed: %s\n",
2286                         lsa->lsa_stripe_size, strerror(errno));
2287                 return rc;
2288         }
2289
2290         rc = llapi_layout_stripe_count_set(layout, lsa->lsa_stripe_count);
2291         if (rc) {
2292                 fprintf(stderr, "Set stripe count %lld failed: %s\n",
2293                         lsa->lsa_stripe_count, strerror(errno));
2294                 return rc;
2295         }
2296
2297         rc = llapi_layout_comp_flags_set(layout, lsa->lsa_comp_flags);
2298         if (rc) {
2299                 fprintf(stderr, "Set flags 0x%x failed: %s\n",
2300                         lsa->lsa_comp_flags, strerror(errno));
2301                 return rc;
2302         }
2303
2304         if (lsa->lsa_pool_name != NULL) {
2305                 rc = llapi_layout_pool_name_set(layout, lsa->lsa_pool_name);
2306                 if (rc) {
2307                         fprintf(stderr, "Set pool name: %s failed. %s\n",
2308                                 lsa->lsa_pool_name, strerror(errno));
2309                         return rc;
2310                 }
2311         } else {
2312                 rc = llapi_layout_pool_name_set(layout, "");
2313                 if (rc) {
2314                         fprintf(stderr, "Clear pool name failed: %s\n",
2315                                 strerror(errno));
2316                         return rc;
2317                 }
2318         }
2319
2320         if (lsa->lsa_nr_tgts > 0) {
2321                 if (lsa->lsa_stripe_count > 0 &&
2322                     lsa->lsa_stripe_count != LLAPI_LAYOUT_DEFAULT &&
2323                     lsa->lsa_stripe_count != LLAPI_LAYOUT_WIDE &&
2324                     lsa->lsa_nr_tgts != lsa->lsa_stripe_count) {
2325                         fprintf(stderr, "stripe_count(%lld) != nr_tgts(%d)\n",
2326                                 lsa->lsa_stripe_count,
2327                                 lsa->lsa_nr_tgts);
2328                         return -EINVAL;
2329                 }
2330                 for (i = 0; i < lsa->lsa_nr_tgts; i++) {
2331                         rc = llapi_layout_ost_index_set(layout, i,
2332                                                         lsa->lsa_tgts[i]);
2333                         if (rc)
2334                                 break;
2335                 }
2336         } else if (lsa->lsa_stripe_off != LLAPI_LAYOUT_DEFAULT &&
2337                    lsa->lsa_stripe_off != -1) {
2338                 rc = llapi_layout_ost_index_set(layout, 0, lsa->lsa_stripe_off);
2339         }
2340         if (rc) {
2341                 fprintf(stderr, "Set ost index %d failed. %s\n",
2342                         i, strerror(errno));
2343                 return rc;
2344         }
2345
2346         return 0;
2347 }
2348
2349 static int build_component(struct llapi_layout **layout,
2350                            struct lfs_setstripe_args *lsa, bool set_extent)
2351 {
2352         int rc;
2353
2354         rc = comp_args_to_layout(layout, lsa, set_extent);
2355         if (rc)
2356                 return rc;
2357
2358         if (lsa->lsa_mirror_count > 0) {
2359                 rc = llapi_layout_mirror_count_set(*layout,
2360                                                    lsa->lsa_mirror_count);
2361                 if (rc)
2362                         return rc;
2363
2364                 rc = llapi_layout_flags_set(*layout, LCM_FL_RDONLY);
2365                 if (rc)
2366                         return rc;
2367                 lsa->lsa_mirror_count = 0;
2368         }
2369
2370         return rc;
2371 }
2372
2373 static int build_layout_from_yaml_node(struct cYAML *node,
2374                                        struct llapi_layout **layout,
2375                                        struct lfs_setstripe_args *lsa,
2376                                        __u32 *osts)
2377 {
2378         char *string;
2379         int rc = 0;
2380
2381         while (node) {
2382                 if (node->cy_type == CYAML_TYPE_OBJECT) {
2383                         /* go deep to sub blocks */
2384                         rc = build_layout_from_yaml_node(node->cy_child, layout,
2385                                                          lsa, osts);
2386                         if (rc)
2387                                 return rc;
2388                 } else {
2389                         if (node->cy_string == NULL)
2390                                 return -EINVAL;
2391
2392                         string = node->cy_string;
2393                         /* skip leading lmm_ if present, to simplify parsing */
2394                         if (strncmp(string, "lmm_", 4) == 0)
2395                                 string += 4;
2396
2397                         if (node->cy_type == CYAML_TYPE_STRING) {
2398                                 if (!strcmp(string, "lcme_extent.e_end")) {
2399                                         if (!strcmp(node->cy_valuestring, "EOF") ||
2400                                             !strcmp(node->cy_valuestring, "eof"))
2401                                                 lsa->lsa_comp_end = LUSTRE_EOF;
2402                                 } else if (!strcmp(string, "pool")) {
2403                                         lsa->lsa_pool_name = node->cy_valuestring;
2404                                 } else if (!strcmp(string, "pattern")) {
2405                                         if (!strcmp(node->cy_valuestring, "mdt"))
2406                                                 lsa->lsa_pattern = LLAPI_LAYOUT_MDT;
2407                                 } else if (!strcmp(string, "lcme_flags")) {
2408                                         rc = comp_str2flags(node->cy_valuestring,
2409                                                             &lsa->lsa_comp_flags,
2410                                                             &lsa->lsa_comp_neg_flags);
2411                                         if (rc)
2412                                                 return rc;
2413                                         /* Only template flags have meaning in
2414                                          * the layout for a new file
2415                                          */
2416                                         lsa->lsa_comp_flags &= LCME_TEMPLATE_FLAGS;
2417                                 }
2418                         } else if (node->cy_type == CYAML_TYPE_NUMBER) {
2419                                 if (!strcmp(string, "lcm_mirror_count")) {
2420                                         lsa->lsa_mirror_count = node->cy_valueint;
2421                                 } else if (!strcmp(string, "lcme_extent.e_start")) {
2422                                         if (node->cy_valueint != 0 || *layout != NULL) {
2423                                                 rc = build_component(layout, lsa, true);
2424                                                 if (rc)
2425                                                         return rc;
2426                                         }
2427
2428                                         if (node->cy_valueint == 0)
2429                                                 lsa->lsa_first_comp = true;
2430
2431                                         /* initialize lsa */
2432                                         setstripe_args_init(lsa);
2433                                         lsa->lsa_tgts = osts;
2434                                 } else if (!strcmp(string, "lcme_extent.e_end")) {
2435                                         if (node->cy_valueint == -1)
2436                                                 lsa->lsa_comp_end = LUSTRE_EOF;
2437                                         else
2438                                                 lsa->lsa_comp_end = node->cy_valueint;
2439                                 } else if (!strcmp(string, "stripe_count")) {
2440                                         lsa->lsa_stripe_count = node->cy_valueint;
2441                                 } else if (!strcmp(string, "stripe_size")) {
2442                                         lsa->lsa_stripe_size = node->cy_valueint;
2443                                 } else if (!strcmp(string, "stripe_offset")) {
2444                                         lsa->lsa_stripe_off = node->cy_valueint;
2445                                 } else if (!strcmp(string, "l_ost_idx")) {
2446                                         osts[lsa->lsa_nr_tgts] = node->cy_valueint;
2447                                         lsa->lsa_nr_tgts++;
2448                                 }
2449                         }
2450                 }
2451                 node = node->cy_next;
2452         }
2453
2454         return rc;
2455 }
2456
2457 static int lfs_comp_create_from_yaml(char *template,
2458                                      struct llapi_layout **layout,
2459                                      struct lfs_setstripe_args *lsa,
2460                                      __u32 *osts)
2461 {
2462         struct cYAML *tree = NULL, *err_rc = NULL;
2463         int rc = 0;
2464
2465         tree = cYAML_build_tree(template, NULL, 0, &err_rc, false);
2466         if (!tree) {
2467                 fprintf(stderr, "%s: cannot parse YAML file %s\n",
2468                         progname, template);
2469                 cYAML_build_error(-EINVAL, -1, "yaml", "from comp yaml",
2470                                   "can't parse", &err_rc);
2471                 cYAML_print_tree2file(stderr, err_rc);
2472                 cYAML_free_tree(err_rc);
2473                 rc = -EINVAL;
2474                 goto err;
2475         }
2476
2477         /* initialize lsa for plain file */
2478         setstripe_args_init(lsa);
2479         lsa->lsa_tgts = osts;
2480
2481         rc = build_layout_from_yaml_node(tree, layout, lsa, osts);
2482         if (rc) {
2483                 fprintf(stderr, "%s: cannot build layout from YAML file %s.\n",
2484                         progname, template);
2485                 goto err;
2486         } else {
2487                 rc = build_component(layout, lsa, *layout != NULL);
2488         }
2489         /* clean clean lsa */
2490         setstripe_args_init(lsa);
2491
2492 err:
2493         if (tree)
2494                 cYAML_free_tree(tree);
2495         return rc;
2496 }
2497
2498 /* In 'lfs setstripe --component-add' mode, we need to fetch the extent
2499  * end of the last component in the existing file, and adjust the
2500  * first extent start of the components to be added accordingly. */
2501 static int adjust_first_extent(char *fname, struct llapi_layout *layout)
2502 {
2503         struct llapi_layout *head;
2504         uint64_t start, end, stripe_size, prev_end = 0;
2505         int rc;
2506
2507         if (layout == NULL) {
2508                 fprintf(stderr,
2509                         "%s setstripe: layout must be specified\n",
2510                         progname);
2511                 return -EINVAL;
2512         }
2513
2514         errno = 0;
2515         head = llapi_layout_get_by_path(fname, 0);
2516         if (head == NULL) {
2517                 fprintf(stderr,
2518                         "%s setstripe: cannot read layout from '%s': %s\n",
2519                         progname, fname, strerror(errno));
2520                 return -EINVAL;
2521         } else if (errno == ENODATA) {
2522                 /* file without LOVEA, this component-add will be turned
2523                  * into a component-create. */
2524                 llapi_layout_free(head);
2525                 return -ENODATA;
2526         } else if (!llapi_layout_is_composite(head)) {
2527                 fprintf(stderr, "%s setstripe: '%s' not a composite file\n",
2528                         progname, fname);
2529                 llapi_layout_free(head);
2530                 return -EINVAL;
2531         }
2532
2533         rc = llapi_layout_comp_extent_get(head, &start, &prev_end);
2534         if (rc) {
2535                 fprintf(stderr, "%s setstripe: cannot get prev extent: %s\n",
2536                         progname, strerror(errno));
2537                 llapi_layout_free(head);
2538                 return rc;
2539         }
2540
2541         llapi_layout_free(head);
2542
2543         /* Make sure we use the first component of the layout to be added. */
2544         rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_FIRST);
2545         if (rc < 0) {
2546                 fprintf(stderr,
2547                         "%s setstripe: cannot move component cursor: %s\n",
2548                         progname, strerror(errno));
2549                 return rc;
2550         }
2551
2552         rc = llapi_layout_comp_extent_get(layout, &start, &end);
2553         if (rc) {
2554                 fprintf(stderr, "%s setstripe: cannot get extent: %s\n",
2555                         progname, strerror(errno));
2556                 return rc;
2557         }
2558
2559         if (start > prev_end || end <= prev_end) {
2560                 fprintf(stderr,
2561                         "%s setstripe: first extent [%lu, %lu) not adjacent with extent end %lu\n",
2562                         progname, start, end, prev_end);
2563                 return -EINVAL;
2564         }
2565
2566         rc = llapi_layout_stripe_size_get(layout, &stripe_size);
2567         if (rc) {
2568                 fprintf(stderr, "%s setstripe: cannot get stripe size: %s\n",
2569                         progname, strerror(errno));
2570                 return rc;
2571         }
2572
2573         if (stripe_size != LLAPI_LAYOUT_DEFAULT &&
2574             (prev_end & (stripe_size - 1))) {
2575                 fprintf(stderr,
2576                         "%s setstripe: stripe size %lu not aligned with %lu\n",
2577                         progname, stripe_size, prev_end);
2578                 return -EINVAL;
2579         }
2580
2581         rc = llapi_layout_comp_extent_set(layout, prev_end, end);
2582         if (rc) {
2583                 fprintf(stderr,
2584                         "%s setstripe: cannot set component extent [%lu, %lu): %s\n",
2585                         progname, prev_end, end, strerror(errno));
2586                 return rc;
2587         }
2588
2589         return 0;
2590 }
2591
2592 static inline bool arg_is_eof(char *arg)
2593 {
2594         return !strncmp(arg, "-1", strlen("-1")) ||
2595                !strncmp(arg, "EOF", strlen("EOF")) ||
2596                !strncmp(arg, "eof", strlen("eof"));
2597 }
2598
2599 /**
2600  * lfs_mirror_alloc() - Allocate a mirror argument structure.
2601  *
2602  * Return: Valid mirror_args pointer on success and
2603  *         NULL if memory allocation fails.
2604  */
2605 static struct mirror_args *lfs_mirror_alloc(void)
2606 {
2607         struct mirror_args *mirror = NULL;
2608
2609         while (1) {
2610                 mirror = calloc(1, sizeof(*mirror));
2611                 if (mirror != NULL)
2612                         break;
2613
2614                 sleep(1);
2615         }
2616
2617         return mirror;
2618 }
2619
2620 /**
2621  * lfs_mirror_free() - Free memory allocated for a mirror argument
2622  *                     structure.
2623  * @mirror: Previously allocated mirror argument structure by
2624  *          lfs_mirror_alloc().
2625  *
2626  * Free memory allocated for @mirror.
2627  *
2628  * Return: void.
2629  */
2630 static void lfs_mirror_free(struct mirror_args *mirror)
2631 {
2632         if (mirror->m_layout != NULL)
2633                 llapi_layout_free(mirror->m_layout);
2634         free(mirror);
2635 }
2636
2637 /**
2638  * lfs_mirror_list_free() - Free memory allocated for a mirror list.
2639  * @mirror_list: Previously allocated mirror list.
2640  *
2641  * Free memory allocated for @mirror_list.
2642  *
2643  * Return: void.
2644  */
2645 static void lfs_mirror_list_free(struct mirror_args *mirror_list)
2646 {
2647         struct mirror_args *next_mirror = NULL;
2648
2649         while (mirror_list != NULL) {
2650                 next_mirror = mirror_list->m_next;
2651                 lfs_mirror_free(mirror_list);
2652                 mirror_list = next_mirror;
2653         }
2654 }
2655
2656 enum {
2657         LFS_POOL_OPT = 3,
2658         LFS_COMP_COUNT_OPT,
2659         LFS_COMP_START_OPT,
2660         LFS_COMP_FLAGS_OPT,
2661         LFS_COMP_DEL_OPT,
2662         LFS_COMP_SET_OPT,
2663         LFS_COMP_ADD_OPT,
2664         LFS_COMP_NO_VERIFY_OPT,
2665         LFS_PROJID_OPT,
2666         LFS_MIRROR_FLAGS_OPT,
2667         LFS_MIRROR_ID_OPT,
2668         LFS_MIRROR_STATE_OPT,
2669         LFS_LAYOUT_COPY,
2670         LFS_MIRROR_INDEX_OPT,
2671 };
2672
2673 /* functions */
2674 static int lfs_setstripe_internal(int argc, char **argv,
2675                                   enum setstripe_origin opc)
2676 {
2677         struct lfs_setstripe_args        lsa = { 0 };
2678         struct llapi_stripe_param       *param = NULL;
2679         struct find_param                migrate_mdt_param = {
2680                 .fp_max_depth = -1,
2681                 .fp_mdt_index = -1,
2682         };
2683         char                            *fname;
2684         int                              result = 0;
2685         int                              result2 = 0;
2686         char                            *end;
2687         int                              c;
2688         int                              delete = 0;
2689         unsigned long long               size_units = 1;
2690         bool                             migrate_mode = false;
2691         bool                             migrate_mdt_mode = false;
2692         bool                             migration_block = false;
2693         __u64                            migration_flags = 0;
2694         __u32                            tgts[LOV_MAX_STRIPE_COUNT] = { 0 };
2695         int                              comp_del = 0, comp_set = 0;
2696         int                              comp_add = 0;
2697         __u32                            comp_id = 0;
2698         struct llapi_layout             *layout = NULL;
2699         struct llapi_layout             **lpp = &layout;
2700         bool                             mirror_mode = false;
2701         bool                             has_m_file = false;
2702         __u32                            mirror_count = 0;
2703         enum mirror_flags                mirror_flags = 0;
2704         struct mirror_args              *mirror_list = NULL;
2705         struct mirror_args              *new_mirror = NULL;
2706         struct mirror_args              *last_mirror = NULL;
2707         __u16                            mirror_id = 0;
2708         char                             cmd[PATH_MAX];
2709         bool from_yaml = false;
2710         bool from_copy = false;
2711         char *template = NULL;
2712
2713         struct option long_opts[] = {
2714 /* find { .val = '0',   .name = "null",         .has_arg = no_argument }, */
2715 /* find { .val = 'A',   .name = "atime",        .has_arg = required_argument }*/
2716         /* --block is only valid in migrate mode */
2717         { .val = 'b',   .name = "block",        .has_arg = no_argument },
2718         { .val = LFS_COMP_ADD_OPT,
2719                         .name = "comp-add",     .has_arg = no_argument },
2720         { .val = LFS_COMP_ADD_OPT,
2721                         .name = "component-add", .has_arg = no_argument },
2722         { .val = LFS_COMP_DEL_OPT,
2723                         .name = "comp-del",     .has_arg = no_argument },
2724         { .val = LFS_COMP_DEL_OPT,
2725                         .name = "component-del", .has_arg = no_argument },
2726         { .val = LFS_COMP_FLAGS_OPT,
2727                         .name = "comp-flags",   .has_arg = required_argument },
2728         { .val = LFS_COMP_FLAGS_OPT,
2729                         .name = "component-flags",
2730                                                 .has_arg = required_argument },
2731         { .val = LFS_COMP_SET_OPT,
2732                         .name = "comp-set",     .has_arg = no_argument },
2733         { .val = LFS_COMP_SET_OPT,
2734                         .name = "component-set",
2735                                                 .has_arg = no_argument},
2736         { .val = LFS_COMP_NO_VERIFY_OPT,
2737                         .name = "no-verify",    .has_arg = no_argument},
2738         { .val = LFS_MIRROR_FLAGS_OPT,
2739                         .name = "flags",        .has_arg = required_argument},
2740         { .val = LFS_MIRROR_ID_OPT,
2741                         .name = "mirror-id",    .has_arg = required_argument},
2742         { .val = LFS_LAYOUT_COPY,
2743                         .name = "copy",         .has_arg = required_argument},
2744         { .val = 'c',   .name = "stripe-count", .has_arg = required_argument},
2745         { .val = 'c',   .name = "stripe_count", .has_arg = required_argument},
2746         { .val = 'c',   .name = "mdt-count",    .has_arg = required_argument},
2747 /* find { .val = 'C',   .name = "ctime",        .has_arg = required_argument }*/
2748         { .val = 'd',   .name = "delete",       .has_arg = no_argument},
2749         { .val = 'd',   .name = "destroy",      .has_arg = no_argument},
2750         /* --non-direct is only valid in migrate mode */
2751         { .val = 'D',   .name = "non-direct",   .has_arg = no_argument },
2752         { .val = 'E',   .name = "comp-end",     .has_arg = required_argument},
2753         { .val = 'E',   .name = "component-end",
2754                                                 .has_arg = required_argument},
2755         { .val = 'f',   .name = "file",         .has_arg = required_argument },
2756 /* find { .val = 'F',   .name = "fid",          .has_arg = no_argument }, */
2757 /* find { .val = 'g',   .name = "gid",          .has_arg = no_argument }, */
2758 /* find { .val = 'G',   .name = "group",        .has_arg = required_argument }*/
2759 /* find { .val = 'h',   .name = "help",         .has_arg = no_argument }, */
2760         { .val = 'H',   .name = "mdt-hash",     .has_arg = required_argument},
2761         { .val = 'i',   .name = "stripe-index", .has_arg = required_argument},
2762         { .val = 'i',   .name = "stripe_index", .has_arg = required_argument},
2763         { .val = 'I',   .name = "comp-id",      .has_arg = required_argument},
2764         { .val = 'I',   .name = "component-id", .has_arg = required_argument},
2765 /* find { .val = 'l',   .name = "lazy",         .has_arg = no_argument }, */
2766         { .val = 'L',   .name = "layout",       .has_arg = required_argument },
2767         { .val = 'm',   .name = "mdt",          .has_arg = required_argument},
2768         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument},
2769         { .val = 'm',   .name = "mdt_index",    .has_arg = required_argument},
2770         /* --non-block is only valid in migrate mode */
2771         { .val = 'n',   .name = "non-block",    .has_arg = no_argument },
2772         { .val = 'N',   .name = "mirror-count", .has_arg = optional_argument},
2773         { .val = 'o',   .name = "ost",          .has_arg = required_argument },
2774 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
2775         { .val = 'o',   .name = "ost-list",     .has_arg = required_argument },
2776         { .val = 'o',   .name = "ost_list",     .has_arg = required_argument },
2777 #endif
2778         { .val = 'p',   .name = "pool",         .has_arg = required_argument },
2779 /* find { .val = 'P',   .name = "print",        .has_arg = no_argument }, */
2780 /* getstripe { .val = 'q', .name = "quiet",     .has_arg = no_argument }, */
2781 /* getstripe { .val = 'r', .name = "recursive", .has_arg = no_argument }, */
2782 /* getstripe { .val = 'R', .name = "raw",       .has_arg = no_argument }, */
2783         { .val = 'S',   .name = "stripe-size",  .has_arg = required_argument },
2784         { .val = 'S',   .name = "stripe_size",  .has_arg = required_argument },
2785 /* find { .val = 't',   .name = "type",         .has_arg = required_argument }*/
2786 /* dirstripe { .val = 'T', .name = "mdt-count", .has_arg = required_argument }*/
2787 /* find { .val = 'u',   .name = "uid",          .has_arg = required_argument }*/
2788 /* find { .val = 'U',   .name = "user",         .has_arg = required_argument }*/
2789         /* --verbose is only valid in migrate mode */
2790         { .val = 'v',   .name = "verbose",      .has_arg = no_argument},
2791         { .val = 'y',   .name = "yaml",         .has_arg = required_argument },
2792         { .name = NULL } };
2793
2794         setstripe_args_init(&lsa);
2795
2796         migrate_mode = (opc == SO_MIGRATE);
2797         mirror_mode = (opc == SO_MIRROR_CREATE || opc == SO_MIRROR_EXTEND);
2798
2799         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
2800         progname = cmd;
2801         while ((c = getopt_long(argc, argv,
2802                                 "bc:dDE:f:H:i:I:m:N::no:p:L:s:S:vy:", long_opts,
2803                                 NULL)) >= 0) {
2804                 switch (c) {
2805                 case 0:
2806                         /* Long options. */
2807                         break;
2808                 case LFS_COMP_ADD_OPT:
2809                         comp_add = 1;
2810                         break;
2811                 case LFS_COMP_DEL_OPT:
2812                         comp_del = 1;
2813                         break;
2814                 case LFS_COMP_FLAGS_OPT:
2815                         result = comp_str2flags(optarg, &lsa.lsa_comp_flags,
2816                                                 &lsa.lsa_comp_neg_flags);
2817                         if (result != 0)
2818                                 goto usage_error;
2819                         if (mirror_mode && lsa.lsa_comp_neg_flags) {
2820                                 fprintf(stderr, "%s: inverted flags are not supported\n",
2821                                         progname);
2822                                 goto usage_error;
2823                         }
2824                         if (lsa.lsa_comp_neg_flags & LCME_FL_STALE) {
2825                                 fprintf(stderr,
2826                                         "%s: cannot clear 'stale' flags from component. Please use lfs-mirror-resync(1) instead\n",
2827                                         progname);
2828                                 result = -EINVAL;
2829                                 goto error;
2830                         }
2831
2832                         break;
2833                 case LFS_COMP_SET_OPT:
2834                         comp_set = 1;
2835                         break;
2836                 case LFS_COMP_NO_VERIFY_OPT:
2837                         mirror_flags |= MF_NO_VERIFY;
2838                         break;
2839                 case LFS_MIRROR_ID_OPT:
2840                         mirror_id = strtoul(optarg, &end, 0);
2841                         if (*end != '\0' || mirror_id == 0) {
2842                                 fprintf(stderr,
2843                                         "%s %s: invalid mirror ID '%s'\n",
2844                                         progname, argv[0], optarg);
2845                                 goto usage_error;
2846                         }
2847                         break;
2848                 case LFS_MIRROR_FLAGS_OPT: {
2849                         __u32 flags;
2850
2851                         if (!mirror_mode || !last_mirror) {
2852                                 fprintf(stderr, "error: %s: --flags must be specified with --mirror-count|-N option\n",
2853                                         progname);
2854                                 goto usage_error;
2855                         }
2856
2857                         result = comp_str2flags(optarg, &last_mirror->m_flags,
2858                                                 &flags);
2859                         if (result != 0)
2860                                 goto usage_error;
2861
2862                         if (flags) {
2863                                 fprintf(stderr, "%s: inverted flags are not supported\n",
2864                                         progname);
2865                                 result = -EINVAL;
2866                                 goto usage_error;
2867                         }
2868                         if (last_mirror->m_flags & ~LCME_USER_FLAGS) {
2869                                 fprintf(stderr,
2870                                         "%s: unsupported mirror flags: %s\n",
2871                                         progname, optarg);
2872                                 result = -EINVAL;
2873                                 goto error;
2874                         }
2875                         break;
2876                 }
2877                 case LFS_LAYOUT_COPY:
2878                         from_copy = true;
2879                         template = optarg;
2880                         break;
2881                 case 'b':
2882                         if (!migrate_mode) {
2883                                 fprintf(stderr,
2884                                         "%s %s: -b|--block valid only for migrate command\n",
2885                                         progname, argv[0]);
2886                                 goto usage_error;
2887                         }
2888                         migration_block = true;
2889                         break;
2890                 case 'c':
2891                         lsa.lsa_stripe_count = strtoul(optarg, &end, 0);
2892                         if (*end != '\0') {
2893                                 fprintf(stderr,
2894                                         "%s %s: invalid stripe count '%s'\n",
2895                                         progname, argv[0], optarg);
2896                                 goto usage_error;
2897                         }
2898
2899                         if (lsa.lsa_stripe_count == -1)
2900                                 lsa.lsa_stripe_count = LLAPI_LAYOUT_WIDE;
2901                         break;
2902                 case 'd':
2903                         /* delete the default striping pattern */
2904                         delete = 1;
2905                         if (opc == SO_MIRROR_SPLIT) {
2906                                 if (has_m_file) {
2907                                         fprintf(stderr,
2908                                               "%s %s: -d cannot used with -f\n",
2909                                                 progname, argv[0]);
2910                                         goto usage_error;
2911                                 }
2912                                 mirror_flags |= MF_DESTROY;
2913                         }
2914                         break;
2915                 case 'D':
2916                         if (!migrate_mode) {
2917                                 fprintf(stderr,
2918                                         "%s %s: -D|--non-direct is valid "
2919                                         "only for migrate command\n",
2920                                         progname, argv[0]);
2921                                 goto usage_error;
2922                         }
2923                         migration_flags |= MIGRATION_NONDIRECT;
2924                         break;
2925                 case 'E':
2926                         if (lsa.lsa_comp_end != 0) {
2927                                 result = comp_args_to_layout(lpp, &lsa, true);
2928                                 if (result) {
2929                                         fprintf(stderr,
2930                                                 "%s %s: invalid layout\n",
2931                                                 progname, argv[0]);
2932                                         goto usage_error;
2933                                 }
2934
2935                                 setstripe_args_init_inherit(&lsa);
2936                         }
2937
2938                         if (arg_is_eof(optarg)) {
2939                                 lsa.lsa_comp_end = LUSTRE_EOF;
2940                         } else {
2941                                 result = llapi_parse_size(optarg,
2942                                                         &lsa.lsa_comp_end,
2943                                                         &size_units, 0);
2944                                 if (result) {
2945                                         fprintf(stderr,
2946                                                 "%s %s: invalid component end '%s'\n",
2947                                                 progname, argv[0], optarg);
2948                                         goto usage_error;
2949                                 }
2950                         }
2951                         break;
2952                 case 'H':
2953                         if (!migrate_mode) {
2954                                 fprintf(stderr, "--mdt-hash is valid only for migrate command\n");
2955                                 return CMD_HELP;
2956                         }
2957
2958                         lsa.lsa_pattern = check_hashtype(optarg);
2959                         if (lsa.lsa_pattern == 0) {
2960                                 fprintf(stderr,
2961                                         "%s %s: bad stripe hash type '%s'\n",
2962                                         progname, argv[0], optarg);
2963                                 return CMD_HELP;
2964                         }
2965                         break;
2966                 case 'i':
2967                         lsa.lsa_stripe_off = strtol(optarg, &end, 0);
2968                         if (*end != '\0') {
2969                                 fprintf(stderr,
2970                                         "%s %s: invalid stripe offset '%s'\n",
2971                                         progname, argv[0], optarg);
2972                                 goto usage_error;
2973                         }
2974                         if (lsa.lsa_stripe_off == -1)
2975                                 lsa.lsa_stripe_off = LLAPI_LAYOUT_DEFAULT;
2976                         break;
2977                 case 'I':
2978                         comp_id = strtoul(optarg, &end, 0);
2979                         if (*end != '\0' || comp_id == 0 ||
2980                             comp_id > LCME_ID_MAX) {
2981                                 fprintf(stderr,
2982                                         "%s %s: invalid component ID '%s'\n",
2983                                         progname, argv[0], optarg);
2984                                 goto usage_error;
2985                         }
2986                         break;
2987                 case 'f':
2988                         if (opc != SO_MIRROR_EXTEND && opc != SO_MIRROR_SPLIT) {
2989                                 fprintf(stderr,
2990                                         "error: %s: invalid option: %s\n",
2991                                         progname, argv[optopt + 1]);
2992                                 goto usage_error;
2993                         }
2994                         if (opc == SO_MIRROR_EXTEND) {
2995                                 if (last_mirror == NULL) {
2996                                         fprintf(stderr,
2997                                 "error: %s: '-N' must exist in front of '%s'\n",
2998                                                 progname, argv[optopt + 1]);
2999                                         goto usage_error;
3000                                 }
3001                                 last_mirror->m_file = optarg;
3002                                 last_mirror->m_count = 1;
3003                         } else {
3004                                 /* mirror split */
3005                                 if (mirror_list == NULL)
3006                                         mirror_list = lfs_mirror_alloc();
3007                                 mirror_list->m_file = optarg;
3008                         }
3009                         has_m_file = true;
3010                         break;
3011                 case 'L':
3012                         if (strcmp(argv[optind - 1], "mdt") == 0) {
3013                                 /* Can be only the first component */
3014                                 if (layout != NULL) {
3015                                         result = -EINVAL;
3016                                         fprintf(stderr, "error: 'mdt' layout "
3017                                                 "can be only the first one\n");
3018                                         goto error;
3019                                 }
3020                                 if (lsa.lsa_comp_end > (1ULL << 30)) { /* 1Gb */
3021                                         result = -EFBIG;
3022                                         fprintf(stderr, "error: 'mdt' layout "
3023                                                 "size is too big\n");
3024                                         goto error;
3025                                 }
3026                                 lsa.lsa_pattern = LLAPI_LAYOUT_MDT;
3027                         } else if (strcmp(argv[optind - 1], "raid0") != 0) {
3028                                 result = -EINVAL;
3029                                 fprintf(stderr, "error: layout '%s' is "
3030                                         "unknown, supported layouts are: "
3031                                         "'mdt', 'raid0'\n", argv[optind]);
3032                                 goto error;
3033                         }
3034                         break;
3035                 case 'm':
3036                         if (!migrate_mode) {
3037                                 fprintf(stderr,
3038                                         "%s %s: -m|--mdt is valid only for migrate command\n",
3039                                         progname, argv[0]);
3040                                 goto usage_error;
3041                         }
3042                         migrate_mdt_mode = true;
3043                         lsa.lsa_nr_tgts = parse_targets(tgts,
3044                                                 sizeof(tgts) / sizeof(__u32),
3045                                                 lsa.lsa_nr_tgts, optarg);
3046                         if (lsa.lsa_nr_tgts < 0) {
3047                                 fprintf(stderr,
3048                                         "%s %s: invalid MDT target(s) '%s'\n",
3049                                         progname, argv[0], optarg);
3050                                 return CMD_HELP;
3051                         }
3052
3053                         lsa.lsa_tgts = tgts;
3054                         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
3055                                 lsa.lsa_stripe_off = tgts[0];
3056                         break;
3057                 case 'n':
3058                         if (!migrate_mode) {
3059                                 fprintf(stderr,
3060                                         "%s %s: -n|--non-block valid only for migrate command\n",
3061                                         progname, argv[0]);
3062                                 goto usage_error;
3063                         }
3064                         migration_flags |= MIGRATION_NONBLOCK;
3065                         break;
3066                 case 'N':
3067                         if (opc == SO_SETSTRIPE) {
3068                                 opc = SO_MIRROR_CREATE;
3069                                 mirror_mode = true;
3070                         }
3071                         mirror_count = 1;
3072                         if (optarg != NULL) {
3073                                 mirror_count = strtoul(optarg, &end, 0);
3074                                 if (*end != '\0' || mirror_count == 0) {
3075                                         fprintf(stderr,
3076                                                 "error: %s: bad mirror count: %s\n",
3077                                                 progname, optarg);
3078                                         result = -EINVAL;
3079                                         goto error;
3080                                 }
3081                         }
3082
3083                         new_mirror = lfs_mirror_alloc();
3084                         new_mirror->m_count = mirror_count;
3085
3086                         if (mirror_list == NULL)
3087                                 mirror_list = new_mirror;
3088
3089                         if (last_mirror != NULL) {
3090                                 /* wrap up last mirror */
3091                                 if (lsa.lsa_comp_end == 0)
3092                                         lsa.lsa_comp_end = LUSTRE_EOF;
3093
3094                                 result = comp_args_to_layout(lpp, &lsa, true);
3095                                 if (result) {
3096                                         lfs_mirror_free(new_mirror);
3097                                         goto error;
3098                                 }
3099
3100                                 setstripe_args_init_inherit(&lsa);
3101
3102                                 last_mirror->m_next = new_mirror;
3103                         }
3104
3105                         last_mirror = new_mirror;
3106                         lpp = &last_mirror->m_layout;
3107                         break;
3108                 case 'o':
3109 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
3110                         if (strcmp(argv[optind - 1], "--ost-list") == 0)
3111                                 fprintf(stderr, "warning: '--ost-list' is "
3112                                         "deprecated, use '--ost' instead\n");
3113 #endif
3114                         if (lsa.lsa_pattern == LLAPI_LAYOUT_MDT) {
3115                                 fprintf(stderr,
3116                                         "%s %s: -o|--ost incompatible with DoM layout\n",
3117                                         progname, argv[0]);
3118                                 goto usage_error;
3119                         }
3120                         lsa.lsa_nr_tgts = parse_targets(tgts,
3121                                                 sizeof(tgts) / sizeof(__u32),
3122                                                 lsa.lsa_nr_tgts, optarg);
3123                         if (lsa.lsa_nr_tgts < 0) {
3124                                 fprintf(stderr,
3125                                         "%s %s: invalid OST target(s) '%s'\n",
3126                                         progname, argv[0], optarg);
3127                                 goto usage_error;
3128                         }
3129
3130                         lsa.lsa_tgts = tgts;
3131                         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
3132                                 lsa.lsa_stripe_off = tgts[0];
3133                         break;
3134                 case 'p':
3135                         if (optarg == NULL)
3136                                 goto usage_error;
3137                         lsa.lsa_pool_name = optarg;
3138
3139                         if (strlen(lsa.lsa_pool_name) == 0 ||
3140                             strncmp(lsa.lsa_pool_name, "none",
3141                                     LOV_MAXPOOLNAME) == 0)
3142                                 lsa.lsa_pool_name = NULL;
3143                         break;
3144                 case 'S':
3145                         result = llapi_parse_size(optarg, &lsa.lsa_stripe_size,
3146                                                   &size_units, 0);
3147                         if (result) {
3148                                 fprintf(stderr,
3149                                         "%s %s: invalid stripe size '%s'\n",
3150                                         progname, argv[0], optarg);
3151                                 goto usage_error;
3152                         }
3153                         break;
3154                 case 'v':
3155                         if (!migrate_mode) {
3156                                 fprintf(stderr,
3157                                         "%s %s: -v|--verbose valid only for migrate command\n",
3158                                         progname, argv[0]);
3159                                 goto usage_error;
3160                         }
3161                         migrate_mdt_param.fp_verbose = VERBOSE_DETAIL;
3162                         break;
3163                 case 'y':
3164                         from_yaml = true;
3165                         template = optarg;
3166                         break;
3167                 default:
3168                         fprintf(stderr, "%s %s: unrecognized option '%s'\n",
3169                                 progname, argv[0], argv[optind - 1]);
3170                         goto usage_error;
3171                 }
3172         }
3173
3174         fname = argv[optind];
3175
3176         if (optind == argc) {
3177                 fprintf(stderr, "%s %s: FILE must be specified\n",
3178                         progname, argv[0]);
3179                 goto usage_error;
3180         }
3181
3182         if (mirror_mode && mirror_count == 0) {
3183                 fprintf(stderr,
3184                         "error: %s: --mirror-count|-N option is required\n",
3185                         progname);
3186                 result = -EINVAL;
3187                 goto error;
3188         }
3189
3190         if (mirror_mode) {
3191                 if (lsa.lsa_comp_end == 0)
3192                         lsa.lsa_comp_end = LUSTRE_EOF;
3193         }
3194
3195         if (lsa.lsa_comp_end != 0) {
3196                 result = comp_args_to_layout(lpp, &lsa, true);
3197                 if (result)
3198                         goto error;
3199         }
3200
3201         if (mirror_flags & MF_NO_VERIFY) {
3202                 if (opc != SO_MIRROR_EXTEND) {
3203                         fprintf(stderr,
3204                                 "error: %s: --no-verify is valid only for lfs mirror extend command\n",
3205                                 progname);
3206                         result = -EINVAL;
3207                         goto error;
3208                 } else if (!has_m_file) {
3209                         fprintf(stderr,
3210                                 "error: %s: --no-verify must be specified with -f <victim_file> option\n",
3211                                 progname);
3212                         result = -EINVAL;
3213                         goto error;
3214                 }
3215         }
3216
3217         /* Only LCME_FL_INIT flags is used in PFL, and it shouldn't be
3218          * altered by user space tool, so we don't need to support the
3219          * --component-set for this moment. */
3220         if (comp_set && !comp_id) {
3221                 fprintf(stderr, "%s %s: --component-set doesn't have component-id set\n",
3222                         progname, argv[0]);
3223                 goto usage_error;
3224         }
3225
3226         if ((delete + comp_set + comp_del + comp_add) > 1) {
3227                 fprintf(stderr,
3228                         "%s %s: options --component-set, --component-del, --component-add and -d are mutually exclusive\n",
3229                         progname, argv[0]);
3230                 goto usage_error;
3231         }
3232
3233         if (delete && (setstripe_args_specified(&lsa) || comp_id != 0 ||
3234                        lsa.lsa_comp_flags != 0 || layout != NULL)) {
3235                 fprintf(stderr,
3236                         "%s %s: option -d is mutually exclusive with -s, -c, -o, -p, -I, -F and -E options\n",
3237                         progname, argv[0]);
3238                 goto usage_error;
3239         }
3240
3241         if ((comp_set || comp_del) &&
3242             (setstripe_args_specified(&lsa) || layout != NULL)) {
3243                 fprintf(stderr,
3244                         "%s %s: options --component-del and --component-set are mutually exclusive when used with -c, -E, -o, -p, or -s\n",
3245                         progname, argv[0]);
3246                 goto usage_error;
3247         }
3248
3249         if (comp_del && comp_id != 0 && lsa.lsa_comp_flags != 0) {
3250                 fprintf(stderr,
3251                         "%s %s: options -I and -F are mutually exclusive when used with --component-del\n",
3252                         progname, argv[0]);
3253                 goto usage_error;
3254         }
3255
3256         if (comp_add || comp_del) {
3257                 struct stat st;
3258
3259                 result = lstat(fname, &st);
3260                 if (result == 0 && S_ISDIR(st.st_mode)) {
3261                         fprintf(stderr,
3262                                 "%s setstripe: cannot use --component-add or --component-del for directory\n",
3263                                 progname);
3264                         goto usage_error;
3265                 }
3266
3267                 if (mirror_mode) {
3268                         fprintf(stderr, "error: %s: can't use --component-add "
3269                                 "or --component-del for mirror operation\n",
3270                                 progname);
3271                         goto usage_error;
3272                 }
3273         }
3274
3275         if (comp_add) {
3276                 if (layout == NULL) {
3277                         fprintf(stderr,
3278                                 "%s %s: option -E must be specified with --component-add\n",
3279                                 progname, argv[0]);
3280                         goto usage_error;
3281                 }
3282
3283                 result = adjust_first_extent(fname, layout);
3284                 if (result == -ENODATA)
3285                         comp_add = 0;
3286                 else if (result != 0)
3287                         goto error;
3288         }
3289
3290         if (from_yaml && from_copy) {
3291                 fprintf(stderr,
3292                         "%s: can't specify --yaml and --copy together\n",
3293                         progname);
3294                 goto error;
3295         }
3296
3297         if ((from_yaml || from_copy) &&
3298             (setstripe_args_specified(&lsa) || layout != NULL)) {
3299                 fprintf(stderr, "error: %s: can't specify --yaml with "
3300                         "-c, -S, -i, -o, -p or -E options.\n",
3301                         argv[0]);
3302                 goto error;
3303         }
3304
3305         if ((migration_flags & MIGRATION_NONBLOCK) && migration_block) {
3306                 fprintf(stderr,
3307                         "%s %s: options --non-block and --block are mutually exclusive\n",
3308                         progname, argv[0]);
3309                 goto usage_error;
3310         }
3311
3312         if (!comp_del && !comp_set && (opc != SO_MIRROR_SPLIT) &&
3313             comp_id != 0) {
3314                 fprintf(stderr,
3315                 "%s %s: option -I can only be used with --component-del or --component-set or lfs mirror split\n",
3316                         progname, argv[0]);
3317                 goto usage_error;
3318         }
3319
3320         if (migrate_mdt_mode) {
3321                 struct lmv_user_md *lmu;
3322
3323                 /* initialize migrate mdt parameters */
3324                 lmu = calloc(1, lmv_user_md_size(lsa.lsa_nr_tgts,
3325                                                  LMV_USER_MAGIC_SPECIFIC));
3326                 if (!lmu) {
3327                         fprintf(stderr,
3328                                 "%s %s: cannot allocate memory for lmv_user_md: %s\n",
3329                                 progname, argv[0], strerror(ENOMEM));
3330                         result = -ENOMEM;
3331                         goto error;
3332                 }
3333                 if (lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT)
3334                         lmu->lum_stripe_count = lsa.lsa_stripe_count;
3335                 if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT) {
3336                         fprintf(stderr,
3337                                 "%s %s: migrate should specify MDT index\n",
3338                                 progname, argv[0]);
3339                         free(lmu);
3340                         goto usage_error;
3341                 }
3342                 lmu->lum_stripe_offset = lsa.lsa_stripe_off;
3343                 if (lsa.lsa_pattern != LLAPI_LAYOUT_RAID0)
3344                         lmu->lum_hash_type = lsa.lsa_pattern;
3345                 else
3346                         lmu->lum_hash_type = LMV_HASH_TYPE_FNV_1A_64;
3347                 if (lsa.lsa_pool_name) {
3348                         strncpy(lmu->lum_pool_name, lsa.lsa_pool_name,
3349                                 sizeof(lmu->lum_pool_name) - 1);
3350                         lmu->lum_pool_name[sizeof(lmu->lum_pool_name) - 1] = 0;
3351                 }
3352                 if (lsa.lsa_nr_tgts > 1) {
3353                         int i;
3354
3355                         if (lsa.lsa_stripe_count > 0 &&
3356                             lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT &&
3357                             lsa.lsa_stripe_count != lsa.lsa_nr_tgts) {
3358                                 fprintf(stderr,
3359                                         "error: %s: stripe count %lld doesn't match the number of MDTs: %d\n",
3360                                         progname, lsa.lsa_stripe_count,
3361                                         lsa.lsa_nr_tgts);
3362                                 free(lmu);
3363                                 goto usage_error;
3364                         }
3365
3366                         lmu->lum_magic = LMV_USER_MAGIC_SPECIFIC;
3367                         lmu->lum_stripe_count = lsa.lsa_nr_tgts;
3368                         for (i = 0; i < lsa.lsa_nr_tgts; i++)
3369                                 lmu->lum_objects[i].lum_mds = lsa.lsa_tgts[i];
3370                 } else {
3371                         lmu->lum_magic = LMV_USER_MAGIC;
3372                 }
3373
3374                 migrate_mdt_param.fp_lmv_md = lmu;
3375                 migrate_mdt_param.fp_migrate = 1;
3376         } else if (layout == NULL) {
3377                 /* initialize stripe parameters */
3378                 param = calloc(1, offsetof(typeof(*param),
3379                                lsp_osts[lsa.lsa_nr_tgts]));
3380                 if (param == NULL) {
3381                         fprintf(stderr,
3382                                 "%s %s: cannot allocate memory for parameters: %s\n",
3383                                 progname, argv[0], strerror(ENOMEM));
3384                         result = -ENOMEM;
3385                         goto error;
3386                 }
3387
3388                 if (lsa.lsa_stripe_size != LLAPI_LAYOUT_DEFAULT)
3389                         param->lsp_stripe_size = lsa.lsa_stripe_size;
3390                 if (lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT) {
3391                         if (lsa.lsa_stripe_count == LLAPI_LAYOUT_WIDE)
3392                                 param->lsp_stripe_count = -1;
3393                         else
3394                                 param->lsp_stripe_count = lsa.lsa_stripe_count;
3395                 }
3396                 if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
3397                         param->lsp_stripe_offset = -1;
3398                 else
3399                         param->lsp_stripe_offset = lsa.lsa_stripe_off;
3400                 param->lsp_pool = lsa.lsa_pool_name;
3401                 param->lsp_is_specific = false;
3402                 if (lsa.lsa_nr_tgts > 0) {
3403                         if (lsa.lsa_stripe_count > 0 &&
3404                             lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT &&
3405                             lsa.lsa_stripe_count != LLAPI_LAYOUT_WIDE &&
3406                             lsa.lsa_nr_tgts != lsa.lsa_stripe_count) {
3407                                 fprintf(stderr,
3408                                         "error: %s: stripe count %lld doesn't match the number of OSTs: %d\n",
3409                                         argv[0], lsa.lsa_stripe_count,
3410                                         lsa.lsa_nr_tgts);
3411                                 free(param);
3412                                 goto usage_error;
3413                         }
3414
3415                         param->lsp_is_specific = true;
3416                         param->lsp_stripe_count = lsa.lsa_nr_tgts;
3417                         memcpy(param->lsp_osts, tgts,
3418                                sizeof(*tgts) * lsa.lsa_nr_tgts);
3419                 }
3420         }
3421
3422         if (from_yaml) {
3423                 /* generate a layout from a YAML template */
3424                 result = lfs_comp_create_from_yaml(template, &layout,
3425                                                    &lsa, tgts);
3426                 if (result) {
3427                         fprintf(stderr, "error: %s: can't create composite "
3428                                 "layout from template file %s\n",
3429                                 argv[0], template);
3430                         goto error;
3431                 }
3432         } else if (from_copy) {
3433                 layout = llapi_layout_get_by_path(template, 0);
3434                 if (layout == NULL) {
3435                         fprintf(stderr,
3436                             "%s: can't create composite layout from file %s.\n",
3437                                 progname, template);
3438                         goto error;
3439                 }
3440         }
3441
3442         for (fname = argv[optind]; fname != NULL; fname = argv[++optind]) {
3443                 if (migrate_mdt_mode) {
3444                         result = llapi_migrate_mdt(fname, &migrate_mdt_param);
3445                 } else if (migrate_mode) {
3446                         result = lfs_migrate(fname, migration_flags, param,
3447                                              layout);
3448                 } else if (comp_set != 0) {
3449                         result = lfs_component_set(fname, comp_id,
3450                                                    lsa.lsa_comp_flags,
3451                                                    lsa.lsa_comp_neg_flags);
3452                 } else if (comp_del != 0) {
3453                         result = lfs_component_del(fname, comp_id,
3454                                                    lsa.lsa_comp_flags,
3455                                                    lsa.lsa_comp_neg_flags);
3456                 } else if (comp_add != 0) {
3457                         result = lfs_component_add(fname, layout);
3458                 } else if (opc == SO_MIRROR_CREATE) {
3459                         result = mirror_create(fname, mirror_list);
3460                 } else if (opc == SO_MIRROR_EXTEND) {
3461                         result = mirror_extend(fname, mirror_list,
3462                                                mirror_flags);
3463                 } else if (opc == SO_MIRROR_SPLIT) {
3464                         if (!mirror_id && !comp_id && !lsa.lsa_pool_name) {
3465                                 fprintf(stderr,
3466                         "%s %s: no mirror id or component id or pool name"
3467                         " is specified\n", progname, argv[0]);
3468                                 goto usage_error;
3469                         }
3470                         if (lsa.lsa_pool_name)
3471                                 mirror_flags |= MF_COMP_POOL;
3472                         else if (mirror_id != 0)
3473                                 comp_id = mirror_id;
3474                         else
3475                                 mirror_flags |= MF_COMP_ID;
3476                         result = mirror_split(fname, comp_id, lsa.lsa_pool_name,
3477                                               mirror_flags,
3478                                               has_m_file ? mirror_list->m_file :
3479                                               NULL);
3480                 } else if (layout != NULL) {
3481                         result = lfs_component_create(fname, O_CREAT | O_WRONLY,
3482                                                       0666, layout);
3483                         if (result >= 0) {
3484                                 close(result);
3485                                 result = 0;
3486                         }
3487                 } else {
3488                         result = llapi_file_open_param(fname,
3489                                                        O_CREAT | O_WRONLY,
3490                                                        0666, param);
3491                         if (result >= 0) {
3492                                 close(result);
3493                                 result = 0;
3494                         }
3495                 }
3496                 if (result) {
3497                         /* Save the first error encountered. */
3498                         if (result2 == 0)
3499                                 result2 = result;
3500                         continue;
3501                 }
3502         }
3503
3504         free(param);
3505         free(migrate_mdt_param.fp_lmv_md);
3506         llapi_layout_free(layout);
3507         lfs_mirror_list_free(mirror_list);
3508         return result2;
3509 usage_error:
3510         result = CMD_HELP;
3511 error:
3512         llapi_layout_free(layout);
3513         lfs_mirror_list_free(mirror_list);
3514         return result;
3515 }
3516
3517 static int lfs_poollist(int argc, char **argv)
3518 {
3519         if (argc != 2)
3520                 return CMD_HELP;
3521
3522         return llapi_poollist(argv[1]);
3523 }
3524
3525 static int set_time(time_t *time, time_t *set, char *str)
3526 {
3527         time_t t;
3528         int res = 0;
3529         char *endptr;
3530
3531         if (str[0] == '+')
3532                 res = 1;
3533         else if (str[0] == '-')
3534                 res = -1;
3535
3536         if (res)
3537                 str++;
3538
3539         t = strtol(str, &endptr, 0);
3540         if (*endptr != '\0') {
3541                 fprintf(stderr,
3542                         "%s find: bad time '%s': %s\n",
3543                         progname, str, strerror(EINVAL));
3544                 return INT_MAX;
3545         }
3546         if (*time < t * 24 * 60 * 60) {
3547                 if (res != 0)
3548                         str--;
3549                 fprintf(stderr,
3550                         "%s find: bad time '%s': too large\n",
3551                         progname, str);
3552                 return INT_MAX;
3553         }
3554
3555         *set = *time - t * 24 * 60 * 60;
3556         return res;
3557 }
3558
3559 static int name2uid(unsigned int *id, const char *name)
3560 {
3561         struct passwd *passwd;
3562
3563         passwd = getpwnam(name);
3564         if (passwd == NULL)
3565                 return -ENOENT;
3566         *id = passwd->pw_uid;
3567
3568         return 0;
3569 }
3570
3571 static int name2gid(unsigned int *id, const char *name)
3572 {
3573         struct group *group;
3574
3575         group = getgrnam(name);
3576         if (group == NULL)
3577                 return -ENOENT;
3578         *id = group->gr_gid;
3579
3580         return 0;
3581 }
3582
3583 static inline int name2projid(unsigned int *id, const char *name)
3584 {
3585         return -ENOTSUP;
3586 }
3587
3588 static int uid2name(char **name, unsigned int id)
3589 {
3590         struct passwd *passwd;
3591
3592         passwd = getpwuid(id);
3593         if (passwd == NULL)
3594                 return -ENOENT;
3595         *name = passwd->pw_name;
3596
3597         return 0;
3598 }
3599
3600 static inline int gid2name(char **name, unsigned int id)
3601 {
3602         struct group *group;
3603
3604         group = getgrgid(id);
3605         if (group == NULL)
3606                 return -ENOENT;
3607         *name = group->gr_name;
3608
3609         return 0;
3610 }
3611
3612 static int name2layout(__u32 *layout, char *name)
3613 {
3614         char *ptr, *layout_name;
3615
3616         *layout = 0;
3617         for (ptr = name; ; ptr = NULL) {
3618                 layout_name = strtok(ptr, ",");
3619                 if (layout_name == NULL)
3620                         break;
3621                 if (strcmp(layout_name, "released") == 0)
3622                         *layout |= LOV_PATTERN_F_RELEASED;
3623                 else if (strcmp(layout_name, "raid0") == 0)
3624                         *layout |= LOV_PATTERN_RAID0;
3625                 else if (strcmp(layout_name, "mdt") == 0)
3626                         *layout |= LOV_PATTERN_MDT;
3627                 else
3628                         return -1;
3629         }
3630         return 0;
3631 }
3632
3633 static int lfs_find(int argc, char **argv)
3634 {
3635         int c, rc;
3636         int ret = 0;
3637         time_t t;
3638         struct find_param param = {
3639                 .fp_max_depth = -1,
3640                 .fp_quiet = 1,
3641         };
3642         struct option long_opts[] = {
3643         { .val = 'A',   .name = "atime",        .has_arg = required_argument },
3644         { .val = 'b',   .name = "blocks",       .has_arg = required_argument },
3645         { .val = LFS_COMP_COUNT_OPT,
3646                         .name = "comp-count",   .has_arg = required_argument },
3647         { .val = LFS_COMP_COUNT_OPT,
3648                         .name = "component-count",
3649                                                 .has_arg = required_argument },
3650         { .val = LFS_COMP_FLAGS_OPT,
3651                         .name = "comp-flags",   .has_arg = required_argument },
3652         { .val = LFS_COMP_FLAGS_OPT,
3653                         .name = "component-flags",
3654                                                 .has_arg = required_argument },
3655         { .val = LFS_COMP_START_OPT,
3656                         .name = "comp-start",   .has_arg = required_argument },
3657         { .val = LFS_COMP_START_OPT,
3658                         .name = "component-start",
3659                                                 .has_arg = required_argument },
3660         { .val = LFS_MIRROR_STATE_OPT,
3661                         .name = "mirror-state", .has_arg = required_argument },
3662         { .val = 'c',   .name = "stripe-count", .has_arg = required_argument },
3663         { .val = 'c',   .name = "stripe_count", .has_arg = required_argument },
3664         { .val = 'C',   .name = "ctime",        .has_arg = required_argument },
3665 /* getstripe { .val = 'd', .name = "directory", .has_arg = no_argument }, */
3666         { .val = 'D',   .name = "maxdepth",     .has_arg = required_argument },
3667         { .val = 'E',   .name = "comp-end",     .has_arg = required_argument },
3668         { .val = 'E',   .name = "component-end",
3669                                                 .has_arg = required_argument },
3670 /* find { .val = 'F',   .name = "fid",          .has_arg = no_argument }, */
3671         { .val = 'g',   .name = "gid",          .has_arg = required_argument },
3672         { .val = 'G',   .name = "group",        .has_arg = required_argument },
3673         { .val = 'H',   .name = "mdt-hash",     .has_arg = required_argument },
3674         { .val = 'i',   .name = "stripe-index", .has_arg = required_argument },
3675         { .val = 'i',   .name = "stripe_index", .has_arg = required_argument },
3676 /* getstripe { .val = 'I', .name = "comp-id",   .has_arg = required_argument }*/
3677         { .val = 'l',   .name = "lazy",         .has_arg = no_argument },
3678         { .val = 'L',   .name = "layout",       .has_arg = required_argument },
3679         { .val = 'm',   .name = "mdt",          .has_arg = required_argument },
3680         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument },
3681         { .val = 'm',   .name = "mdt_index",    .has_arg = required_argument },
3682         { .val = 'M',   .name = "mtime",        .has_arg = required_argument },
3683         { .val = 'n',   .name = "name",         .has_arg = required_argument },
3684         { .val = 'N',   .name = "mirror-count", .has_arg = required_argument },
3685 /* find { .val = 'o'    .name = "or", .has_arg = no_argument }, like find(1) */
3686         { .val = 'O',   .name = "obd",          .has_arg = required_argument },
3687         { .val = 'O',   .name = "ost",          .has_arg = required_argument },
3688         /* no short option for pool yet, can be 'p' after 2.18 */
3689         { .val = LFS_POOL_OPT,
3690                         .name = "pool",         .has_arg = required_argument },
3691         { .val = '0',   .name = "print0",       .has_arg = no_argument },
3692         { .val = 'P',   .name = "print",        .has_arg = no_argument },
3693         { .val = LFS_PROJID_OPT,
3694                         .name = "projid",       .has_arg = required_argument },
3695 /* getstripe { .val = 'q', .name = "quiet",     .has_arg = no_argument }, */
3696 /* getstripe { .val = 'r', .name = "recursive", .has_arg = no_argument }, */
3697 /* getstripe { .val = 'R', .name = "raw",       .has_arg = no_argument }, */
3698         { .val = 's',   .name = "size",         .has_arg = required_argument },
3699         { .val = 'S',   .name = "stripe-size",  .has_arg = required_argument },
3700         { .val = 'S',   .name = "stripe_size",  .has_arg = required_argument },
3701         { .val = 't',   .name = "type",         .has_arg = required_argument },
3702         { .val = 'T',   .name = "mdt-count",    .has_arg = required_argument },
3703         { .val = 'u',   .name = "uid",          .has_arg = required_argument },
3704         { .val = 'U',   .name = "user",         .has_arg = required_argument },
3705 /* getstripe { .val = 'v', .name = "verbose",   .has_arg = no_argument }, */
3706 /* getstripe { .val = 'y', .name = "yaml",      .has_arg = no_argument }, */
3707         { .name = NULL } };
3708         int pathstart = -1;
3709         int pathend = -1;
3710         int neg_opt = 0;
3711         time_t *xtime;
3712         int *xsign;
3713         int isoption;
3714         char *endptr;
3715
3716         time(&t);
3717
3718         /* when getopt_long_only() hits '!' it returns 1, puts "!" in optarg */
3719         while ((c = getopt_long_only(argc, argv,
3720                         "-0A:b:c:C:D:E:g:G:H:i:L:m:M:n:N:O:Ppqrs:S:t:T:u:U:v",
3721                         long_opts, NULL)) >= 0) {
3722                 xtime = NULL;
3723                 xsign = NULL;
3724                 if (neg_opt)
3725                         --neg_opt;
3726                 /* '!' is part of option */
3727                 /* when getopt_long_only() finds a string which is not
3728                  * an option nor a known option argument it returns 1
3729                  * in that case if we already have found pathstart and pathend
3730                  * (i.e. we have the list of pathnames),
3731                  * the only supported value is "!"
3732                  */
3733                 isoption = (c != 1) || (strcmp(optarg, "!") == 0);
3734                 if (!isoption && pathend != -1) {
3735                         fprintf(stderr, "err: %s: filename|dirname must either "
3736                                         "precede options or follow options\n",
3737                                         argv[0]);
3738                         ret = CMD_HELP;
3739                         goto err;
3740                 }
3741                 if (!isoption && pathstart == -1)
3742                         pathstart = optind - 1;
3743                 if (isoption && pathstart != -1 && pathend == -1)
3744                         pathend = optind - 2;
3745                 switch (c) {
3746                 case 0:
3747                         /* Long options. */
3748                         break;
3749                 case 1:
3750                         /* unknown; opt is "!" or path component,
3751                          * checking done above.
3752                          */
3753                         if (strcmp(optarg, "!") == 0)
3754                                 neg_opt = 2;
3755                         break;
3756                 case 'A':
3757                         xtime = &param.fp_atime;
3758                         xsign = &param.fp_asign;
3759                         param.fp_exclude_atime = !!neg_opt;
3760                         /* no break, this falls through to 'C' for ctime */
3761                 case 'C':
3762                         if (c == 'C') {
3763                                 xtime = &param.fp_ctime;
3764                                 xsign = &param.fp_csign;
3765                                 param.fp_exclude_ctime = !!neg_opt;
3766                         }
3767                         /* no break, this falls through to 'M' for mtime */
3768                 case 'M':
3769                         if (c == 'M') {
3770                                 xtime = &param.fp_mtime;
3771                                 xsign = &param.fp_msign;
3772                                 param.fp_exclude_mtime = !!neg_opt;
3773                         }
3774                         rc = set_time(&t, xtime, optarg);
3775                         if (rc == INT_MAX) {
3776                                 ret = -1;
3777                                 goto err;
3778                         }
3779                         if (rc)
3780                                 *xsign = rc;
3781                         break;
3782                 case 'b':
3783                         if (optarg[0] == '+') {
3784                                 param.fp_blocks_sign = -1;
3785                                 optarg++;
3786                         } else if (optarg[0] == '-') {
3787                                 param.fp_blocks_sign =  1;
3788                                 optarg++;
3789                         }
3790
3791                         param.fp_blocks_units = 1024;
3792                         ret = llapi_parse_size(optarg, &param.fp_blocks,
3793                                                &param.fp_blocks_units, 0);
3794                         if (ret) {
3795                                 fprintf(stderr, "error: bad blocks '%s'\n",
3796                                         optarg);
3797                                 goto err;
3798                         }
3799                         param.fp_check_blocks = 1;
3800                         param.fp_exclude_blocks = !!neg_opt;
3801                         break;
3802                 case LFS_COMP_COUNT_OPT:
3803                         if (optarg[0] == '+') {
3804                                 param.fp_comp_count_sign = -1;
3805                                 optarg++;
3806                         } else if (optarg[0] == '-') {
3807                                 param.fp_comp_count_sign =  1;
3808                                 optarg++;
3809                         }
3810
3811                         param.fp_comp_count = strtoul(optarg, &endptr, 0);
3812                         if (*endptr != '\0') {
3813                                 fprintf(stderr, "error: bad component count "
3814                                         "'%s'\n", optarg);
3815                                 goto err;
3816                         }
3817                         param.fp_check_comp_count = 1;
3818                         param.fp_exclude_comp_count = !!neg_opt;
3819                         break;
3820                 case LFS_COMP_FLAGS_OPT:
3821                         rc = comp_str2flags(optarg, &param.fp_comp_flags,
3822                                             &param.fp_comp_neg_flags);
3823                         if (rc) {
3824                                 fprintf(stderr, "error: bad component flags "
3825                                         "'%s'\n", optarg);
3826                                 goto err;
3827                         }
3828                         param.fp_check_comp_flags = 1;
3829                         if (neg_opt) {
3830                                 __u32 flags = param.fp_comp_neg_flags;
3831                                 param.fp_comp_neg_flags = param.fp_comp_flags;
3832                                 param.fp_comp_flags = flags;
3833                         }
3834                         break;
3835                 case LFS_COMP_START_OPT:
3836                         if (optarg[0] == '+') {
3837                                 param.fp_comp_start_sign = -1;
3838                                 optarg++;
3839                         } else if (optarg[0] == '-') {
3840                                 param.fp_comp_start_sign =  1;
3841                                 optarg++;
3842                         }
3843
3844                         rc = llapi_parse_size(optarg, &param.fp_comp_start,
3845                                               &param.fp_comp_start_units, 0);
3846                         if (rc) {
3847                                 fprintf(stderr, "error: bad component start "
3848                                         "'%s'\n", optarg);
3849                                 goto err;
3850                         }
3851                         param.fp_check_comp_start = 1;
3852                         param.fp_exclude_comp_start = !!neg_opt;
3853                         break;
3854                 case LFS_MIRROR_STATE_OPT:
3855                         rc = mirror_str2state(optarg, &param.fp_mirror_state,
3856                                               &param.fp_mirror_neg_state);
3857                         if (rc) {
3858                                 fprintf(stderr,
3859                                         "error: bad mirrored file state '%s'\n",
3860                                         optarg);
3861                                 goto err;
3862                         }
3863                         param.fp_check_mirror_state = 1;
3864                         if (neg_opt) {
3865                                 __u16 state = param.fp_mirror_neg_state;
3866                                 param.fp_mirror_neg_state =
3867                                         param.fp_mirror_state;
3868                                 param.fp_mirror_state = state;
3869                         }
3870                         break;
3871                 case 'c':
3872                         if (optarg[0] == '+') {
3873                                 param.fp_stripe_count_sign = -1;
3874                                 optarg++;
3875                         } else if (optarg[0] == '-') {
3876                                 param.fp_stripe_count_sign =  1;
3877                                 optarg++;
3878                         }
3879
3880                         param.fp_stripe_count = strtoul(optarg, &endptr, 0);
3881                         if (*endptr != '\0') {
3882                                 fprintf(stderr,"error: bad stripe_count '%s'\n",
3883                                         optarg);
3884                                 ret = -1;
3885                                 goto err;
3886                         }
3887                         param.fp_check_stripe_count = 1;
3888                         param.fp_exclude_stripe_count = !!neg_opt;
3889                         break;
3890                 case 'D':
3891                         param.fp_max_depth = strtol(optarg, 0, 0);
3892                         break;
3893                 case 'E':
3894                         if (optarg[0] == '+') {
3895                                 param.fp_comp_end_sign = -1;
3896                                 optarg++;
3897                         } else if (optarg[0] == '-') {
3898                                 param.fp_comp_end_sign =  1;
3899                                 optarg++;
3900                         }
3901
3902                         if (arg_is_eof(optarg)) {
3903                                 param.fp_comp_end = LUSTRE_EOF;
3904                                 param.fp_comp_end_units = 1;
3905                                 rc = 0;
3906                         } else {
3907                                 rc = llapi_parse_size(optarg,
3908                                                 &param.fp_comp_end,
3909                                                 &param.fp_comp_end_units, 0);
3910                         }
3911                         if (rc) {
3912                                 fprintf(stderr, "error: bad component end "
3913                                         "'%s'\n", optarg);
3914                                 goto err;
3915                         }
3916                         param.fp_check_comp_end = 1;
3917                         param.fp_exclude_comp_end = !!neg_opt;
3918                         break;
3919                 case 'g':
3920                 case 'G':
3921                         rc = name2gid(&param.fp_gid, optarg);
3922                         if (rc) {
3923                                 param.fp_gid = strtoul(optarg, &endptr, 10);
3924                                 if (*endptr != '\0') {
3925                                         fprintf(stderr, "Group/GID: %s cannot "
3926                                                 "be found.\n", optarg);
3927                                         ret = -1;
3928                                         goto err;
3929                                 }
3930                         }
3931                         param.fp_exclude_gid = !!neg_opt;
3932                         param.fp_check_gid = 1;
3933                         break;
3934                 case 'H':
3935                         param.fp_hash_type = check_hashtype(optarg);
3936                         if (param.fp_hash_type == 0) {
3937                                 fprintf(stderr, "error: bad hash_type '%s'\n",
3938                                         optarg);
3939                                 ret = -1;
3940                                 goto err;
3941                         }
3942                         param.fp_check_hash_type = 1;
3943                         param.fp_exclude_hash_type = !!neg_opt;
3944                         break;
3945                 case 'l':
3946                         param.fp_lazy = 1;
3947                         break;
3948                 case 'L':
3949                         ret = name2layout(&param.fp_layout, optarg);
3950                         if (ret)
3951                                 goto err;
3952                         param.fp_exclude_layout = !!neg_opt;
3953                         param.fp_check_layout = 1;
3954                         break;
3955                 case 'u':
3956                 case 'U':
3957                         rc = name2uid(&param.fp_uid, optarg);
3958                         if (rc) {
3959                                 param.fp_uid = strtoul(optarg, &endptr, 10);
3960                                 if (*endptr != '\0') {
3961                                         fprintf(stderr, "User/UID: %s cannot "
3962                                                 "be found.\n", optarg);
3963                                         ret = -1;
3964                                         goto err;
3965                                 }
3966                         }
3967                         param.fp_exclude_uid = !!neg_opt;
3968                         param.fp_check_uid = 1;
3969                         break;
3970                 case 'n':
3971                         param.fp_pattern = (char *)optarg;
3972                         param.fp_exclude_pattern = !!neg_opt;
3973                         break;
3974                 case 'N':
3975                         if (optarg[0] == '+') {
3976                                 param.fp_mirror_count_sign = -1;
3977                                 optarg++;
3978                         } else if (optarg[0] == '-') {
3979                                 param.fp_mirror_count_sign =  1;
3980                                 optarg++;
3981                         }
3982
3983                         param.fp_mirror_count = strtoul(optarg, &endptr, 0);
3984                         if (*endptr != '\0') {
3985                                 fprintf(stderr,
3986                                         "error: bad mirror count '%s'\n",
3987                                         optarg);
3988                                 goto err;
3989                         }
3990                         param.fp_check_mirror_count = 1;
3991                         param.fp_exclude_mirror_count = !!neg_opt;
3992                         break;
3993                 case 'm':
3994                 case 'i':
3995                 case 'O': {
3996                         char *buf, *token, *next, *p;
3997                         int len = 1;
3998                         void *tmp;
3999
4000                         buf = strdup(optarg);
4001                         if (buf == NULL) {
4002                                 ret = -ENOMEM;
4003                                 goto err;
4004                         }
4005
4006                         param.fp_exclude_obd = !!neg_opt;
4007
4008                         token = buf;
4009                         while (token && *token) {
4010                                 token = strchr(token, ',');
4011                                 if (token) {
4012                                         len++;
4013                                         token++;
4014                                 }
4015                         }
4016                         if (c == 'm') {
4017                                 param.fp_exclude_mdt = !!neg_opt;
4018                                 param.fp_num_alloc_mdts += len;
4019                                 tmp = realloc(param.fp_mdt_uuid,
4020                                               param.fp_num_alloc_mdts *
4021                                               sizeof(*param.fp_mdt_uuid));
4022                                 if (tmp == NULL) {
4023                                         ret = -ENOMEM;
4024                                         goto err_free;
4025                                 }
4026
4027                                 param.fp_mdt_uuid = tmp;
4028                         } else {
4029                                 param.fp_exclude_obd = !!neg_opt;
4030                                 param.fp_num_alloc_obds += len;
4031                                 tmp = realloc(param.fp_obd_uuid,
4032                                               param.fp_num_alloc_obds *
4033                                               sizeof(*param.fp_obd_uuid));
4034                                 if (tmp == NULL) {
4035                                         ret = -ENOMEM;
4036                                         goto err_free;
4037                                 }
4038
4039                                 param.fp_obd_uuid = tmp;
4040                         }
4041                         for (token = buf; token && *token; token = next) {
4042                                 struct obd_uuid *puuid;
4043                                 if (c == 'm') {
4044                                         puuid =
4045                                         &param.fp_mdt_uuid[param.fp_num_mdts++];
4046                                 } else {
4047                                         puuid =
4048                                         &param.fp_obd_uuid[param.fp_num_obds++];
4049                                 }
4050                                 p = strchr(token, ',');
4051                                 next = 0;
4052                                 if (p) {
4053                                         *p = 0;
4054                                         next = p+1;
4055                                 }
4056
4057                                 if (strlen(token) > sizeof(puuid->uuid) - 1) {
4058                                         ret = -E2BIG;
4059                                         goto err_free;
4060                                 }
4061
4062                                 strncpy(puuid->uuid, token,
4063                                         sizeof(puuid->uuid));
4064                         }
4065 err_free:
4066                         if (buf)
4067                                 free(buf);
4068                         break;
4069                 }
4070 #if LUSTRE_VERSION_CODE >= OBD_OCD_VERSION(2, 18, 53, 0)
4071                 case 'p':
4072 #endif
4073                 case LFS_POOL_OPT:
4074                         if (strlen(optarg) > LOV_MAXPOOLNAME) {
4075                                 fprintf(stderr,
4076                                         "Pool name %s is too long (max %d)\n",
4077                                         optarg, LOV_MAXPOOLNAME);
4078                                 ret = -1;
4079                                 goto err;
4080                         }
4081                         /*
4082                          * We do check for empty pool because empty pool
4083                          * is used to find V1 LOV attributes
4084                          */
4085                         strncpy(param.fp_poolname, optarg, LOV_MAXPOOLNAME);
4086                         param.fp_poolname[LOV_MAXPOOLNAME] = '\0';
4087                         param.fp_exclude_pool = !!neg_opt;
4088                         param.fp_check_pool = 1;
4089                         break;
4090 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 14, 53, 0)
4091                 case 'p': /* want this for --pool, to match getstripe/find */
4092                         fprintf(stderr,
4093                                 "warning: -p deprecated, use --print0 or -0\n");
4094 #endif
4095                 case '0':
4096                         param.fp_zero_end = 1;
4097                         break;
4098                 case 'P': /* we always print, this option is a no-op */
4099                         break;
4100                 case LFS_PROJID_OPT:
4101                         rc = name2projid(&param.fp_projid, optarg);
4102                         if (rc) {
4103                                 param.fp_projid = strtoul(optarg, &endptr, 10);
4104                                 if (*endptr != '\0') {
4105                                         fprintf(stderr,
4106                                                 "Invalid project ID: %s",
4107                                                 optarg);
4108                                         ret = -1;
4109                                         goto err;
4110                                 }
4111                         }
4112                         param.fp_exclude_projid = !!neg_opt;
4113                         param.fp_check_projid = 1;
4114                         break;
4115                 case 's':
4116                         if (optarg[0] == '+') {
4117                                 param.fp_size_sign = -1;
4118                                 optarg++;
4119                         } else if (optarg[0] == '-') {
4120                                 param.fp_size_sign =  1;
4121                                 optarg++;
4122                         }
4123
4124                         ret = llapi_parse_size(optarg, &param.fp_size,
4125                                                &param.fp_size_units, 0);
4126                         if (ret) {
4127                                 fprintf(stderr, "error: bad file size '%s'\n",
4128                                         optarg);
4129                                 goto err;
4130                         }
4131                         param.fp_check_size = 1;
4132                         param.fp_exclude_size = !!neg_opt;
4133                         break;
4134                 case 'S':
4135                         if (optarg[0] == '+') {
4136                                 param.fp_stripe_size_sign = -1;
4137                                 optarg++;
4138                         } else if (optarg[0] == '-') {
4139                                 param.fp_stripe_size_sign =  1;
4140                                 optarg++;
4141                         }
4142
4143                         ret = llapi_parse_size(optarg, &param.fp_stripe_size,
4144                                                &param.fp_stripe_size_units, 0);
4145                         if (ret) {
4146                                 fprintf(stderr, "error: bad stripe_size '%s'\n",
4147                                         optarg);
4148                                 goto err;
4149                         }
4150                         param.fp_check_stripe_size = 1;
4151                         param.fp_exclude_stripe_size = !!neg_opt;
4152                         break;
4153                 case 't':
4154                         param.fp_exclude_type = !!neg_opt;
4155                         switch (optarg[0]) {
4156                         case 'b':
4157                                 param.fp_type = S_IFBLK;
4158                                 break;
4159                         case 'c':
4160                                 param.fp_type = S_IFCHR;
4161                                 break;
4162                         case 'd':
4163                                 param.fp_type = S_IFDIR;
4164                                 break;
4165                         case 'f':
4166                                 param.fp_type = S_IFREG;
4167                                 break;
4168                         case 'l':
4169                                 param.fp_type = S_IFLNK;
4170                                 break;
4171                         case 'p':
4172                                 param.fp_type = S_IFIFO;
4173                                 break;
4174                         case 's':
4175                                 param.fp_type = S_IFSOCK;
4176                                 break;
4177                         default:
4178                                 fprintf(stderr, "error: %s: bad type '%s'\n",
4179                                         argv[0], optarg);
4180                                 ret = CMD_HELP;
4181                                 goto err;
4182                         };
4183                         break;
4184                 case 'T':
4185                         if (optarg[0] == '+') {
4186                                 param.fp_mdt_count_sign = -1;
4187                                 optarg++;
4188                         } else if (optarg[0] == '-') {
4189                                 param.fp_mdt_count_sign =  1;
4190                                 optarg++;
4191                         }
4192
4193                         param.fp_mdt_count = strtoul(optarg, &endptr, 0);
4194                         if (*endptr != '\0') {
4195                                 fprintf(stderr, "error: bad mdt_count '%s'\n",
4196                                         optarg);
4197                                 ret = -1;
4198                                 goto err;
4199                         }
4200                         param.fp_check_mdt_count = 1;
4201                         param.fp_exclude_mdt_count = !!neg_opt;
4202                         break;
4203                 default:
4204                         ret = CMD_HELP;
4205                         goto err;
4206                 };
4207         }
4208
4209         if (pathstart == -1) {
4210                 fprintf(stderr, "error: %s: no filename|pathname\n",
4211                         argv[0]);
4212                 ret = CMD_HELP;
4213                 goto err;
4214         } else if (pathend == -1) {
4215                 /* no options */
4216                 pathend = argc;
4217         }
4218
4219         do {
4220                 rc = llapi_find(argv[pathstart], &param);
4221                 if (rc != 0 && ret == 0)
4222                         ret = rc;
4223         } while (++pathstart < pathend);
4224
4225         if (ret)
4226                 fprintf(stderr, "error: %s failed for %s.\n",
4227                         argv[0], argv[optind - 1]);
4228 err:
4229         if (param.fp_obd_uuid && param.fp_num_alloc_obds)
4230                 free(param.fp_obd_uuid);
4231
4232         if (param.fp_mdt_uuid && param.fp_num_alloc_mdts)
4233                 free(param.fp_mdt_uuid);
4234
4235         return ret;
4236 }
4237
4238 static int lfs_getstripe_internal(int argc, char **argv,
4239                                   struct find_param *param)
4240 {
4241         struct option long_opts[] = {
4242 /* find { .val = 'A',   .name = "atime",        .has_arg = required_argument }*/
4243 /* find { .val = 'b',   .name = "blocks",       .has_arg = required_argument }*/
4244         { .val = LFS_COMP_COUNT_OPT,
4245                         .name = "comp-count",   .has_arg = no_argument },
4246         { .val = LFS_COMP_COUNT_OPT,
4247                 .name = "component-count",      .has_arg = no_argument },
4248         { .val = LFS_COMP_FLAGS_OPT,
4249                         .name = "comp-flags",   .has_arg = optional_argument },
4250         { .val = LFS_COMP_FLAGS_OPT,
4251                 .name = "component-flags",      .has_arg = optional_argument },
4252         { .val = LFS_COMP_START_OPT,
4253                         .name = "comp-start",   .has_arg = optional_argument },
4254         { .val = LFS_COMP_START_OPT,
4255                 .name = "component-start",      .has_arg = optional_argument },
4256         { .val = LFS_MIRROR_INDEX_OPT,
4257                 .name = "mirror-index",         .has_arg = required_argument },
4258         { .val = LFS_MIRROR_ID_OPT,
4259                 .name = "mirror-id",            .has_arg = required_argument },
4260         { .val = 'c',   .name = "stripe-count", .has_arg = no_argument },
4261         { .val = 'c',   .name = "stripe_count", .has_arg = no_argument },
4262 /* find { .val = 'C',   .name = "ctime",        .has_arg = required_argument }*/
4263         { .val = 'd',   .name = "directory",    .has_arg = no_argument },
4264         { .val = 'D',   .name = "default",      .has_arg = no_argument },
4265         { .val = 'E',   .name = "comp-end",     .has_arg = optional_argument },
4266         { .val = 'E',   .name = "component-end", .has_arg = optional_argument },
4267         { .val = 'F',   .name = "fid",          .has_arg = no_argument },
4268         { .val = 'g',   .name = "generation",   .has_arg = no_argument },
4269 /* find { .val = 'G',   .name = "group",        .has_arg = required_argument }*/
4270 /* dirstripe { .val = 'H', .name = "mdt-hash",  .has_arg = required_argument }*/
4271         { .val = 'i',   .name = "stripe-index", .has_arg = no_argument },
4272         { .val = 'i',   .name = "stripe_index", .has_arg = no_argument },
4273         { .val = 'I',   .name = "comp-id",      .has_arg = optional_argument },
4274         { .val = 'I',   .name = "component-id", .has_arg = optional_argument },
4275 /* find { .val = 'l',   .name = "lazy",         .has_arg = no_argument }, */
4276         { .val = 'L',   .name = "layout",       .has_arg = no_argument },
4277         { .val = 'm',   .name = "mdt",          .has_arg = no_argument },
4278         { .val = 'm',   .name = "mdt-index",    .has_arg = no_argument },
4279         { .val = 'm',   .name = "mdt_index",    .has_arg = no_argument },
4280 /* find { .val = 'M',   .name = "mtime",        .has_arg = required_argument }*/
4281 /* find { .val = 'n',   .name = "name",         .has_arg = required_argument }*/
4282         { .val = 'N',   .name = "mirror-count", .has_arg = no_argument },
4283         { .val = 'O',   .name = "obd",          .has_arg = required_argument },
4284         { .val = 'O',   .name = "ost",          .has_arg = required_argument },
4285         { .val = 'p',   .name = "pool",         .has_arg = no_argument },
4286 /* find { .val = 'P',   .name = "print",        .has_arg = no_argument }, */
4287         { .val = 'q',   .name = "quiet",        .has_arg = no_argument },
4288         { .val = 'r',   .name = "recursive",    .has_arg = no_argument },
4289         { .val = 'R',   .name = "raw",          .has_arg = no_argument },
4290         { .val = 'S',   .name = "stripe-size",  .has_arg = no_argument },
4291         { .val = 'S',   .name = "stripe_size",  .has_arg = no_argument },
4292 /* find { .val = 't',   .name = "type",         .has_arg = required_argument }*/
4293 /* dirstripe { .val = 'T', .name = "mdt-count", .has_arg = required_argument }*/
4294 /* find { .val = 'u',   .name = "uid",          .has_arg = required_argument }*/
4295 /* find { .val = 'U',   .name = "user",         .has_arg = required_argument }*/
4296         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
4297         { .val = 'y',   .name = "yaml",         .has_arg = no_argument },
4298         { .name = NULL } };
4299         int c, rc;
4300         int neg_opt = 0;
4301         int pathstart = -1, pathend = -1;
4302         int isoption;
4303         char *end, *tmp;
4304
4305         while ((c = getopt_long(argc, argv,
4306                         "-cdDE::FghiI::LmMNoO:pqrRsSvy",
4307                         long_opts, NULL)) != -1) {
4308                 if (neg_opt)
4309                         --neg_opt;
4310
4311                 /* '!' is part of option */
4312                 isoption = (c != 1) || (strcmp(optarg, "!") == 0);
4313                 if (!isoption && pathend != -1) {
4314                         fprintf(stderr,
4315                                 "error: %s: filename|dirname must either precede options or follow options\n",
4316                                 argv[0]);
4317                         return CMD_HELP;
4318                 }
4319                 if (!isoption && pathstart == -1)
4320                         pathstart = optind - 1;
4321                 if (isoption && pathstart != -1 && pathend == -1)
4322                         pathend = optind - 2;
4323
4324                 switch (c) {
4325                 case 1:
4326                         /* unknown: opt is "!" */
4327                         if (strcmp(optarg, "!") == 0)
4328                                 neg_opt = 2;
4329                         break;
4330                 case 'c':
4331                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
4332                                 param->fp_verbose |= VERBOSE_COUNT;
4333                                 param->fp_max_depth = 0;
4334                         }
4335                         break;
4336                 case LFS_COMP_COUNT_OPT:
4337                         param->fp_verbose |= VERBOSE_COMP_COUNT;
4338                         param->fp_max_depth = 0;
4339                         break;
4340                 case LFS_COMP_FLAGS_OPT:
4341                         if (optarg != NULL) {
4342                                 rc = comp_str2flags(optarg,
4343                                                     &param->fp_comp_flags,
4344                                                     &param->fp_comp_neg_flags);
4345                                 if (rc != 0) {
4346                                         fprintf(stderr, "error: %s bad "
4347                                                 "component flags '%s'.\n",
4348                                                 argv[0], optarg);
4349                                         return CMD_HELP;
4350                                 }
4351                                 param->fp_check_comp_flags = 1;
4352                         } else {
4353                                 param->fp_verbose |= VERBOSE_COMP_FLAGS;
4354                                 param->fp_max_depth = 0;
4355                         }
4356                         break;
4357                 case LFS_COMP_START_OPT:
4358                         if (optarg != NULL) {
4359                                 tmp = optarg;
4360                                 if (tmp[0] == '+') {
4361                                         param->fp_comp_start_sign = -1;
4362                                         tmp++;
4363                                 } else if (tmp[0] == '-') {
4364                                         param->fp_comp_start_sign = 1;
4365                                         tmp++;
4366                                 }
4367                                 rc = llapi_parse_size(tmp,
4368                                                 &param->fp_comp_start,
4369                                                 &param->fp_comp_start_units, 0);
4370                                 if (rc != 0) {
4371                                         fprintf(stderr, "error: %s bad "
4372                                                 "component start '%s'.\n",
4373                                                 argv[0], tmp);
4374                                         return CMD_HELP;
4375                                 } else {
4376                                         param->fp_check_comp_start = 1;
4377                                 }
4378                         } else {
4379                                 param->fp_verbose |= VERBOSE_COMP_START;
4380                                 param->fp_max_depth = 0;
4381                         }
4382                         break;
4383                 case LFS_MIRROR_INDEX_OPT:
4384                         if (optarg[0] == '+') {
4385                                 param->fp_mirror_index_sign = -1;
4386                                 optarg++;
4387                         } else if (optarg[0] == '-') {
4388                                 param->fp_mirror_index_sign = 1;
4389                                 optarg++;
4390                         }
4391
4392                         param->fp_mirror_index = strtoul(optarg, &end, 0);
4393                         if (*end != '\0' || (param->fp_mirror_index == 0 &&
4394                             param->fp_mirror_index_sign == 0 && neg_opt == 0)) {
4395                                 fprintf(stderr,
4396                                         "%s %s: invalid mirror index '%s'\n",
4397                                         progname, argv[0], optarg);
4398                                 return CMD_HELP;
4399                         }
4400                         if (param->fp_mirror_id != 0) {
4401                                 fprintf(stderr,
4402                                         "%s %s: can't specify both mirror index and mirror ID\n",
4403                                         progname, argv[0]);
4404                                 return CMD_HELP;
4405                         }
4406                         param->fp_check_mirror_index = 1;
4407                         param->fp_exclude_mirror_index = !!neg_opt;
4408                         break;
4409                 case LFS_MIRROR_ID_OPT:
4410                         if (optarg[0] == '+') {
4411                                 param->fp_mirror_id_sign = -1;
4412                                 optarg++;
4413                         } else if (optarg[0] == '-') {
4414                                 param->fp_mirror_id_sign = 1;
4415                                 optarg++;
4416                         }
4417
4418                         param->fp_mirror_id = strtoul(optarg, &end, 0);
4419                         if (*end != '\0' || (param->fp_mirror_id == 0 &&
4420                             param->fp_mirror_id_sign == 0 && neg_opt == 0)) {
4421                                 fprintf(stderr,
4422                                         "%s %s: invalid mirror ID '%s'\n",
4423                                         progname, argv[0], optarg);
4424                                 return CMD_HELP;
4425                         }
4426                         if (param->fp_mirror_index != 0) {
4427                                 fprintf(stderr,
4428                                         "%s %s: can't specify both mirror index and mirror ID\n",
4429                                         progname, argv[0]);
4430                                 return CMD_HELP;
4431                         }
4432                         param->fp_check_mirror_id = 1;
4433                         param->fp_exclude_mirror_id = !!neg_opt;
4434                         break;
4435                 case 'd':
4436                         param->fp_max_depth = 0;
4437                         break;
4438                 case 'D':
4439                         param->fp_get_default_lmv = 1;
4440                         break;
4441                 case 'E':
4442                         if (optarg != NULL) {
4443                                 tmp = optarg;
4444                                 if (tmp[0] == '+') {
4445                                         param->fp_comp_end_sign = -1;
4446                                         tmp++;
4447                                 } else if (tmp[0] == '-') {
4448                                         param->fp_comp_end_sign = 1;
4449                                         tmp++;
4450                                 }
4451
4452                                 if (arg_is_eof(tmp)) {
4453                                         param->fp_comp_end = LUSTRE_EOF;
4454                                         param->fp_comp_end_units = 1;
4455                                         rc = 0;
4456                                 } else {
4457                                         rc = llapi_parse_size(tmp,
4458                                                 &param->fp_comp_end,
4459                                                 &param->fp_comp_end_units, 0);
4460                                 }
4461                                 if (rc != 0) {
4462                                         fprintf(stderr, "error: %s bad "
4463                                                 "component end '%s'.\n",
4464                                                 argv[0], tmp);
4465                                         return CMD_HELP;
4466                                 }
4467                                 param->fp_check_comp_end = 1;
4468                         } else {
4469                                 param->fp_verbose |= VERBOSE_COMP_END;
4470                                 param->fp_max_depth = 0;
4471                         }
4472                         break;
4473                 case 'F':
4474                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
4475                                 param->fp_verbose |= VERBOSE_DFID;
4476                                 param->fp_max_depth = 0;
4477                         }
4478                         break;
4479                 case 'g':
4480                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
4481                                 param->fp_verbose |= VERBOSE_GENERATION;
4482                                 param->fp_max_depth = 0;
4483                         }
4484                         break;
4485                 case 'i':
4486                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
4487                                 param->fp_verbose |= VERBOSE_STRIPE_OFFSET;
4488                                 param->fp_max_depth = 0;
4489                         }
4490                         break;
4491                 case 'I':
4492                         if (optarg != NULL) {
4493                                 param->fp_comp_id = strtoul(optarg, &end, 0);
4494                                 if (*end != '\0' || param->fp_comp_id == 0 ||
4495                                     param->fp_comp_id > LCME_ID_MAX) {
4496                                         fprintf(stderr, "error: %s bad "
4497                                                 "component id '%s'\n",
4498                                                 argv[0], optarg);
4499                                         return CMD_HELP;
4500                                 } else {
4501                                         param->fp_check_comp_id = 1;
4502                                 }
4503                         } else {
4504                                 param->fp_max_depth = 0;
4505                                 param->fp_verbose |= VERBOSE_COMP_ID;
4506                         }
4507                         break;
4508                 case 'L':
4509                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
4510                                 param->fp_verbose |= VERBOSE_PATTERN;
4511                                 param->fp_max_depth = 0;
4512                         }
4513                         break;
4514 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
4515                 case 'M':
4516                         fprintf(stderr, "warning: '-M' deprecated"
4517                                 ", use '--mdt-index' or '-m' instead\n");
4518 #endif
4519                 case 'm':
4520                         if (!(param->fp_verbose & VERBOSE_DETAIL))
4521                                 param->fp_max_depth = 0;
4522                         param->fp_verbose |= VERBOSE_MDTINDEX;
4523                         break;
4524                 case 'N':
4525                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
4526                                 param->fp_verbose |= VERBOSE_MIRROR_COUNT;
4527                                 param->fp_max_depth = 0;
4528                         }
4529                         break;
4530                 case 'O':
4531                         if (param->fp_obd_uuid) {
4532                                 fprintf(stderr,
4533                                         "error: %s: only one obduuid allowed",
4534                                         argv[0]);
4535                                 return CMD_HELP;
4536                         }
4537                         param->fp_obd_uuid = (struct obd_uuid *)optarg;
4538                         break;
4539                 case 'p':
4540                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
4541                                 param->fp_verbose |= VERBOSE_POOL;
4542                                 param->fp_max_depth = 0;
4543                         }
4544                         break;
4545                 case 'q':
4546                         param->fp_quiet++;
4547                         break;
4548                 case 'r':
4549                         param->fp_recursive = 1;
4550                         break;
4551                 case 'R':
4552                         param->fp_raw = 1;
4553                         break;
4554                 case 'S':
4555                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
4556                                 param->fp_verbose |= VERBOSE_STRIPE_SIZE;
4557                                 param->fp_max_depth = 0;
4558                         }
4559                         break;
4560                 case 'v':
4561                         param->fp_verbose = VERBOSE_DEFAULT | VERBOSE_DETAIL;
4562                         break;
4563                 case 'y':
4564                         param->fp_yaml = 1;
4565                         break;
4566                 default:
4567                         return CMD_HELP;
4568                 }
4569         }
4570
4571         if (pathstart == -1) {
4572                 fprintf(stderr, "error: %s: no filename|pathname\n",
4573                                 argv[0]);
4574                 return CMD_HELP;
4575         } else if (pathend == -1) {
4576                 /* no options */
4577                 pathend = argc;
4578         }
4579
4580         if (pathend > argc)
4581                 return CMD_HELP;
4582
4583         if (param->fp_recursive)
4584                 param->fp_max_depth = -1;
4585         else if (param->fp_verbose & VERBOSE_DETAIL)
4586                 param->fp_max_depth = 1;
4587
4588         if (!param->fp_verbose)
4589                 param->fp_verbose = VERBOSE_DEFAULT;
4590         if (param->fp_quiet)
4591                 param->fp_verbose = VERBOSE_OBJID;
4592
4593         do {
4594                 rc = llapi_getstripe(argv[pathstart], param);
4595         } while (++pathstart < pathend && !rc);
4596
4597         if (rc)
4598                 fprintf(stderr, "error: %s failed for %s.\n",
4599                         argv[0], argv[optind - 1]);
4600         return rc;
4601 }
4602
4603 static int lfs_tgts(int argc, char **argv)
4604 {
4605         char mntdir[PATH_MAX] = {'\0'}, path[PATH_MAX] = {'\0'};
4606         struct find_param param;
4607         int index = 0, rc=0;
4608
4609         if (argc > 2)
4610                 return CMD_HELP;
4611
4612         if (argc == 2 && !realpath(argv[1], path)) {
4613                 rc = -errno;
4614                 fprintf(stderr, "error: invalid path '%s': %s\n",
4615                         argv[1], strerror(-rc));
4616                 return rc;
4617         }
4618
4619         while (!llapi_search_mounts(path, index++, mntdir, NULL)) {
4620                 /* Check if we have a mount point */
4621                 if (mntdir[0] == '\0')
4622                         continue;
4623
4624                 memset(&param, 0, sizeof(param));
4625                 if (!strcmp(argv[0], "mdts"))
4626                         param.fp_get_lmv = 1;
4627
4628                 rc = llapi_ostlist(mntdir, &param);
4629                 if (rc) {
4630                         fprintf(stderr, "error: %s: failed on %s\n",
4631                                 argv[0], mntdir);
4632                 }
4633                 if (path[0] != '\0')
4634                         break;
4635                 memset(mntdir, 0, PATH_MAX);
4636         }
4637
4638         return rc;
4639 }
4640
4641 static int lfs_getstripe(int argc, char **argv)
4642 {
4643         struct find_param param = { 0 };
4644
4645         param.fp_max_depth = 1;
4646         return lfs_getstripe_internal(argc, argv, &param);
4647 }
4648
4649 /* functions */
4650 static int lfs_getdirstripe(int argc, char **argv)
4651 {
4652         struct find_param param = { 0 };
4653         struct option long_opts[] = {
4654         { .val = 'c',   .name = "mdt-count",    .has_arg = no_argument },
4655         { .val = 'D',   .name = "default",      .has_arg = no_argument },
4656         { .val = 'H',   .name = "mdt-hash",     .has_arg = no_argument },
4657         { .val = 'i',   .name = "mdt-index",    .has_arg = no_argument },
4658         { .val = 'm',   .name = "mdt-index",    .has_arg = no_argument },
4659         { .val = 'O',   .name = "obd",          .has_arg = required_argument },
4660         { .val = 'r',   .name = "recursive",    .has_arg = no_argument },
4661         { .val = 'T',   .name = "mdt-count",    .has_arg = no_argument },
4662         { .val = 'y',   .name = "yaml",         .has_arg = no_argument },
4663         { .name = NULL } };
4664         int c, rc;
4665
4666         param.fp_get_lmv = 1;
4667
4668         while ((c = getopt_long(argc, argv,
4669                                 "cDHimO:rtTy", long_opts, NULL)) != -1)
4670         {
4671                 switch (c) {
4672                 case 'c':
4673                 case 'T':
4674                         param.fp_verbose |= VERBOSE_COUNT;
4675                         break;
4676                 case 'D':
4677                         param.fp_get_default_lmv = 1;
4678                         break;
4679                 case 'i':
4680                 case 'm':
4681                         param.fp_verbose |= VERBOSE_STRIPE_OFFSET;
4682                         break;
4683 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
4684                 case 't':
4685                         fprintf(stderr, "warning: '-t' deprecated, "
4686                                 "use '--mdt-hash' or '-H' instead\n");
4687 #endif
4688                 case 'H':
4689                         param.fp_verbose |= VERBOSE_HASH_TYPE;
4690                         break;
4691                 case 'O':
4692                         if (param.fp_obd_uuid) {
4693                                 fprintf(stderr,
4694                                         "error: %s: only one obduuid allowed",
4695                                         argv[0]);
4696                                 return CMD_HELP;
4697                         }
4698                         param.fp_obd_uuid = (struct obd_uuid *)optarg;
4699                         break;
4700                 case 'r':
4701                         param.fp_recursive = 1;
4702                         break;
4703                 case 'y':
4704                         param.fp_yaml = 1;
4705                         break;
4706                 default:
4707                         return CMD_HELP;
4708                 }
4709         }
4710
4711         if (optind >= argc)
4712                 return CMD_HELP;
4713
4714         if (param.fp_recursive)
4715                 param.fp_max_depth = -1;
4716
4717         if (!param.fp_verbose)
4718                 param.fp_verbose = VERBOSE_DEFAULT;
4719
4720         do {
4721                 rc = llapi_getstripe(argv[optind], &param);
4722         } while (++optind < argc && !rc);
4723
4724         if (rc)
4725                 fprintf(stderr, "error: %s failed for %s.\n",
4726                         argv[0], argv[optind - 1]);
4727         return rc;
4728 }
4729
4730 enum mntdf_flags {
4731         MNTDF_INODES    = 0x0001,
4732         MNTDF_COOKED    = 0x0002,
4733         MNTDF_LAZY      = 0x0004,
4734         MNTDF_VERBOSE   = 0x0008,
4735         MNTDF_SHOW      = 0x0010,
4736 };
4737
4738 #define COOK(value)                                             \
4739 ({                                                              \
4740         int radix = 0;                                          \
4741         while (value > 1024) {                                  \
4742                 value /= 1024;                                  \
4743                 radix++;                                        \
4744         }                                                       \
4745         radix;                                                  \
4746 })
4747 #define UUF     "%-20s"
4748 #define CSF     "%11s"
4749 #define CDF     "%11llu"
4750 #define HDF     "%8.1f%c"
4751 #define RSF     "%4s"
4752 #define RDF     "%3d%%"
4753
4754 static inline int obd_statfs_ratio(const struct obd_statfs *st, bool inodes)
4755 {
4756         double avail, used, ratio = 0;
4757
4758         if (inodes) {
4759                 avail = st->os_ffree;
4760                 used = st->os_files - st->os_ffree;
4761         } else {
4762                 avail = st->os_bavail;
4763                 used = st->os_blocks - st->os_bfree;
4764         }
4765         if (avail + used > 0)
4766                 ratio = used / (used + avail) * 100;
4767
4768         /* Round up to match df(1) usage percentage */
4769         return (ratio - (int)ratio) > 0 ? (int)(ratio + 1) : (int)ratio;
4770 }
4771
4772 /* This is to identify various problem states for "lfs df" if .osn_err = true,
4773  * so only show flags reflecting those states by default. Informational states
4774  * are only shown with "-v" and use lower-case names to distinguish them.
4775  * UNUSED[12] were for "EROFS = 30" until 1.6 but are now available for use.
4776  */
4777 static struct obd_statfs_state_names {
4778         enum obd_statfs_state   osn_state;
4779         const char              osn_name;
4780         bool                    osn_err;
4781 } oss_names[] = {
4782         { .osn_state = OS_STATE_DEGRADED,    .osn_name = 'D', .osn_err = true },
4783         { .osn_state = OS_STATE_READONLY,    .osn_name = 'R', .osn_err = true },
4784         { .osn_state = OS_STATE_NOPRECREATE, .osn_name = 'N', .osn_err = true },
4785         { .osn_state = OS_STATE_UNUSED1,     .osn_name = '?', .osn_err = true },
4786         { .osn_state = OS_STATE_UNUSED2,     .osn_name = '?', .osn_err = true },
4787         { .osn_state = OS_STATE_ENOSPC,      .osn_name = 'S', .osn_err = true },
4788         { .osn_state = OS_STATE_ENOINO,      .osn_name = 'I', .osn_err = true },
4789         { .osn_state = OS_STATE_SUM,         .osn_name = 'a', /* aggregate */ },
4790         { .osn_state = OS_STATE_NONROT,      .osn_name = 'f', /* flash */     },
4791 };
4792
4793 static int showdf(char *mntdir, struct obd_statfs *stat,
4794                   char *uuid, enum mntdf_flags flags,
4795                   char *type, int index, int rc)
4796 {
4797         long long avail, used, total;
4798         int ratio = 0;
4799         char *suffix = "KMGTPEZY";
4800         /* Note if we have >2^64 bytes/fs these buffers will need to be grown */
4801         char tbuf[3 * sizeof(__u64)];
4802         char ubuf[3 * sizeof(__u64)];
4803         char abuf[3 * sizeof(__u64)];
4804         char rbuf[3 * sizeof(__u64)];
4805
4806         if (!uuid || !stat)
4807                 return -EINVAL;
4808
4809         switch (rc) {
4810         case 0:
4811                 if (flags & MNTDF_INODES) {
4812                         avail = stat->os_ffree;
4813                         used = stat->os_files - stat->os_ffree;
4814                         total = stat->os_files;
4815                 } else {
4816                         int shift = flags & MNTDF_COOKED ? 0 : 10;
4817
4818                         avail = (stat->os_bavail * stat->os_bsize) >> shift;
4819                         used  = ((stat->os_blocks - stat->os_bfree) *
4820                                  stat->os_bsize) >> shift;
4821                         total = (stat->os_blocks * stat->os_bsize) >> shift;
4822                 }
4823
4824                 ratio = obd_statfs_ratio(stat, flags & MNTDF_INODES);
4825
4826                 if (flags & MNTDF_COOKED) {
4827                         int i;
4828                         double cook_val;
4829
4830                         cook_val = (double)total;
4831                         i = COOK(cook_val);
4832                         if (i > 0)
4833                                 snprintf(tbuf, sizeof(tbuf), HDF, cook_val,
4834                                          suffix[i - 1]);
4835                         else
4836                                 snprintf(tbuf, sizeof(tbuf), CDF, total);
4837
4838                         cook_val = (double)used;
4839                         i = COOK(cook_val);
4840                         if (i > 0)
4841                                 snprintf(ubuf, sizeof(ubuf), HDF, cook_val,
4842                                          suffix[i - 1]);
4843                         else
4844                                 snprintf(ubuf, sizeof(ubuf), CDF, used);
4845
4846                         cook_val = (double)avail;
4847                         i = COOK(cook_val);
4848                         if (i > 0)
4849                                 snprintf(abuf, sizeof(abuf), HDF, cook_val,
4850                                          suffix[i - 1]);
4851                         else
4852                                 snprintf(abuf, sizeof(abuf), CDF, avail);
4853                 } else {
4854                         snprintf(tbuf, sizeof(tbuf), CDF, total);
4855                         snprintf(ubuf, sizeof(tbuf), CDF, used);
4856                         snprintf(abuf, sizeof(tbuf), CDF, avail);
4857                 }
4858
4859                 sprintf(rbuf, RDF, ratio);
4860                 printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s",
4861                        uuid, tbuf, ubuf, abuf, rbuf, mntdir);
4862                 if (type)
4863                         printf("[%s:%d]", type, index);
4864
4865                 if (stat->os_state) {
4866                         uint32_t i;
4867
4868                         printf(" ");
4869                         for (i = 0; i < ARRAY_SIZE(oss_names); i++) {
4870                                 if (oss_names[i].osn_state & stat->os_state &&
4871                                     (oss_names[i].osn_err ||
4872                                      flags & MNTDF_VERBOSE))
4873                                         printf("%c", oss_names[i].osn_name);
4874                         }
4875                 }
4876
4877                 printf("\n");
4878                 break;
4879         case -ENODATA:
4880                 printf(UUF": inactive device\n", uuid);
4881                 break;
4882         default:
4883                 printf(UUF": %s\n", uuid, strerror(-rc));
4884                 break;
4885         }
4886
4887         return 0;
4888 }
4889
4890 struct ll_stat_type {
4891         int   st_op;
4892         char *st_name;
4893 };
4894
4895 #define LL_STATFS_MAX   LOV_MAX_STRIPE_COUNT
4896
4897 struct ll_statfs_data {
4898         int                     sd_index;
4899         struct obd_statfs       sd_st;
4900 };
4901
4902 struct ll_statfs_buf {
4903         int                     sb_count;
4904         struct ll_statfs_data   sb_buf[LL_STATFS_MAX];
4905 };
4906
4907 static int mntdf(char *mntdir, char *fsname, char *pool, enum mntdf_flags flags,
4908                  int ops, struct ll_statfs_buf *lsb)
4909 {
4910         struct obd_statfs stat_buf, sum = { .os_bsize = 1 };
4911         struct obd_uuid uuid_buf;
4912         char *poolname = NULL;
4913         struct ll_stat_type types[] = {
4914                 { .st_op = LL_STATFS_LMV,       .st_name = "MDT" },
4915                 { .st_op = LL_STATFS_LOV,       .st_name = "OST" },
4916                 { .st_name = NULL } };
4917         struct ll_stat_type *tp;
4918         __u64 ost_files = 0;
4919         __u64 ost_ffree = 0;
4920         __u32 index;
4921         __u32 type;
4922         int fd;
4923         int rc = 0;
4924         int rc2;
4925
4926         if (pool) {
4927                 poolname = strchr(pool, '.');
4928                 if (poolname != NULL) {
4929                         if (strncmp(fsname, pool, strlen(fsname))) {
4930                                 fprintf(stderr, "filesystem name incorrect\n");
4931                                 return -ENODEV;
4932                         }
4933                         poolname++;
4934                 } else
4935                         poolname = pool;
4936         }
4937
4938         fd = open(mntdir, O_RDONLY);
4939         if (fd < 0) {
4940                 rc = -errno;
4941                 fprintf(stderr, "%s: cannot open '%s': %s\n", progname, mntdir,
4942                         strerror(errno));
4943                 return rc;
4944         }
4945
4946         if (flags & MNTDF_SHOW) {
4947                 if (flags & MNTDF_INODES)
4948                         printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s\n",
4949                                "UUID", "Inodes", "IUsed", "IFree",
4950                                "IUse%", "Mounted on");
4951                 else
4952                         printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s\n",
4953                                "UUID",
4954                                flags & MNTDF_COOKED ? "bytes" : "1K-blocks",
4955                                "Used", "Available", "Use%", "Mounted on");
4956         }
4957
4958         for (tp = types; tp->st_name != NULL; tp++) {
4959                 bool have_ost = false;
4960
4961                 if (!(tp->st_op & ops))
4962                         continue;
4963
4964                 for (index = 0; ; index++) {
4965                         memset(&stat_buf, 0, sizeof(struct obd_statfs));
4966                         memset(&uuid_buf, 0, sizeof(struct obd_uuid));
4967                         type = flags & MNTDF_LAZY ?
4968                                 tp->st_op | LL_STATFS_NODELAY : tp->st_op;
4969                         rc2 = llapi_obd_fstatfs(fd, type, index,
4970                                                &stat_buf, &uuid_buf);
4971                         if (rc2 == -ENODEV)
4972                                 break;
4973                         if (rc2 == -EAGAIN)
4974                                 continue;
4975                         if (rc2 == -ENODATA) { /* Inactive device, OK. */
4976                                 if (!(flags & MNTDF_VERBOSE))
4977                                         continue;
4978                         } else if (rc2 < 0 && rc == 0) {
4979                                 rc = rc2;
4980                         }
4981
4982                         /* If we have OSTs then don't report MDT block counts.
4983                          * For MDT-only filesystems the expectation is that all
4984                          * layouts have a DoM component.  For filesystems with
4985                          * OSTs, files are not necessarily going to store data
4986                          * on MDTs, and MDT space is limited to a fraction of
4987                          * OST space, so don't include it in the summary.
4988                          */
4989                         if (tp->st_op == LL_STATFS_LOV && !have_ost) {
4990                                 have_ost = true;
4991                                 sum.os_blocks = 0;
4992                                 sum.os_bfree = 0;
4993                                 sum.os_bavail = 0;
4994                         }
4995
4996                         if (poolname && tp->st_op == LL_STATFS_LOV &&
4997                             llapi_search_ost(fsname, poolname,
4998                                              obd_uuid2str(&uuid_buf)) != 1)
4999                                 continue;
5000
5001                         /* the llapi_obd_statfs() call may have returned with
5002                          * an error, but if it filled in uuid_buf we will at
5003                          * lease use that to print out a message for that OBD.
5004                          * If we didn't get anything in the uuid_buf, then fill
5005                          * it in so that we can print an error message. */
5006                         if (uuid_buf.uuid[0] == '\0')
5007                                 snprintf(uuid_buf.uuid, sizeof(uuid_buf.uuid),
5008                                          "%s%04x", tp->st_name, index);
5009                         if (!rc && lsb) {
5010                                 lsb->sb_buf[lsb->sb_count].sd_index = index;
5011                                 lsb->sb_buf[lsb->sb_count].sd_st = stat_buf;
5012                                 lsb->sb_count++;
5013                         }
5014                         if (flags & MNTDF_SHOW)
5015                                 showdf(mntdir, &stat_buf,
5016                                        obd_uuid2str(&uuid_buf), flags,
5017                                        tp->st_name, index, rc2);
5018
5019                         if (rc2)
5020                                 continue;
5021
5022                         if (tp->st_op == LL_STATFS_LMV) {
5023                                 sum.os_ffree += stat_buf.os_ffree;
5024                                 sum.os_files += stat_buf.os_files;
5025                         } else /* if (tp->st_op == LL_STATFS_LOV) */ {
5026                                 ost_files += stat_buf.os_files;
5027                                 ost_ffree += stat_buf.os_ffree;
5028                         }
5029                         sum.os_blocks += stat_buf.os_blocks *
5030                                          stat_buf.os_bsize;
5031                         sum.os_bfree  += stat_buf.os_bfree *
5032                                          stat_buf.os_bsize;
5033                         sum.os_bavail += stat_buf.os_bavail *
5034                                          stat_buf.os_bsize;
5035                 }
5036         }
5037
5038         close(fd);
5039
5040         /* If we have _some_ OSTs, but don't have as many free objects on the
5041          * OST as inodes on the MDTs, reduce the reported number of inodes
5042          * to compensate, so that the "inodes in use" number is correct.
5043          * This should be kept in sync with ll_statfs_internal().
5044          */
5045         if (ost_files && ost_ffree < sum.os_ffree) {
5046                 sum.os_files = (sum.os_files - sum.os_ffree) + ost_ffree;
5047                 sum.os_ffree = ost_ffree;
5048         }
5049         if (flags & MNTDF_SHOW) {
5050                 printf("\n");
5051                 showdf(mntdir, &sum, "filesystem_summary:", flags, NULL, 0, 0);
5052                 printf("\n");
5053         }
5054
5055         return rc;
5056 }
5057
5058 static int ll_statfs_data_comp(const void *sd1, const void *sd2)
5059 {
5060         const struct obd_statfs *st1 = &((const struct ll_statfs_data *)sd1)->
5061                                                 sd_st;
5062         const struct obd_statfs *st2 = &((const struct ll_statfs_data *)sd2)->
5063                                                 sd_st;
5064         int r1 = obd_statfs_ratio(st1, false);
5065         int r2 = obd_statfs_ratio(st2, false);
5066         int64_t result = r1 - r2;
5067
5068         /* if both space usage are above 90, compare free inodes */
5069         if (r1 > 90 && r2 > 90)
5070                 result = st2->os_ffree - st1->os_ffree;
5071
5072         if (result < 0)
5073                 return -1;
5074         else if (result == 0)
5075                 return 0;
5076         else
5077                 return 1;
5078 }
5079
5080 /* functions */
5081 static int lfs_setdirstripe(int argc, char **argv)
5082 {
5083         char                    *dname;
5084         int                     result;
5085         struct lfs_setstripe_args        lsa = { 0 };
5086         struct llapi_stripe_param       *param = NULL;
5087         __u32                   mdts[LMV_MAX_STRIPE_COUNT] = { 0 };
5088         char                    *end;
5089         int                     c;
5090         char                    *mode_opt = NULL;
5091         bool                    default_stripe = false;
5092         mode_t                  mode = S_IRWXU | S_IRWXG | S_IRWXO;
5093         mode_t                  previous_mode = 0;
5094         bool                    delete = false;
5095         struct ll_statfs_buf    *lsb = NULL;
5096         char                    mntdir[PATH_MAX] = "";
5097         bool                    auto_distributed = false;
5098
5099         struct option long_opts[] = {
5100         { .val = 'c',   .name = "count",        .has_arg = required_argument },
5101         { .val = 'c',   .name = "mdt-count",    .has_arg = required_argument },
5102         { .val = 'd',   .name = "delete",       .has_arg = no_argument },
5103         { .val = 'D',   .name = "default",      .has_arg = no_argument },
5104         { .val = 'D',   .name = "default_stripe", .has_arg = no_argument },
5105         { .val = 'H',   .name = "mdt-hash",     .has_arg = required_argument },
5106         { .val = 'i',   .name = "mdt-index",    .has_arg = required_argument },
5107 /* find { .val = 'l',   .name = "lazy",         .has_arg = no_argument }, */
5108 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
5109         { .val = 'i',   .name = "index",        .has_arg = required_argument },
5110 #endif
5111         { .val = 'o',   .name = "mode",         .has_arg = required_argument },
5112 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
5113         { .val = 't',   .name = "hash-type",    .has_arg = required_argument },
5114 #endif
5115         { .val = 'T',   .name = "mdt-count",    .has_arg = required_argument },
5116 /* setstripe { .val = 'y', .name = "yaml",      .has_arg = no_argument }, */
5117         { .name = NULL } };
5118
5119         setstripe_args_init(&lsa);
5120
5121         while ((c = getopt_long(argc, argv, "c:dDi:H:m:o:t:T:", long_opts,
5122                                 NULL)) >= 0) {
5123                 switch (c) {
5124                 case 0:
5125                         /* Long options. */
5126                         break;
5127                 case 'c':
5128                 case 'T':
5129                         lsa.lsa_stripe_count = strtoul(optarg, &end, 0);
5130                         if (*end != '\0') {
5131                                 fprintf(stderr,
5132                                         "%s %s: invalid stripe count '%s'\n",
5133                                         progname, argv[0], optarg);
5134                                 return CMD_HELP;
5135                         }
5136                         break;
5137                 case 'd':
5138                         delete = true;
5139                         default_stripe = true;
5140                         break;
5141                 case 'D':
5142                         default_stripe = true;
5143                         break;
5144 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
5145                 case 't':
5146                         fprintf(stderr, "warning: '--hash-type' and '-t' "
5147                               "deprecated, use '--mdt-hash' or '-H' instead\n");
5148 #endif
5149                 case 'H':
5150                         lsa.lsa_pattern = check_hashtype(optarg);
5151                         if (lsa.lsa_pattern == 0) {
5152                                 fprintf(stderr,
5153                                         "%s %s: bad stripe hash type '%s'\n",
5154                                         progname, argv[0], optarg);
5155                                 return CMD_HELP;
5156                         }
5157                         break;
5158                 case 'i':
5159 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
5160                         if (strcmp(argv[optind - 1], "--index") == 0)
5161                                 fprintf(stderr,
5162                                         "%s %s: warning: '--index' deprecated, use '--mdt-index' instead\n",
5163                                         progname, argv[0]);
5164 #endif
5165                         lsa.lsa_nr_tgts = parse_targets(mdts,
5166                                                 sizeof(mdts) / sizeof(__u32),
5167                                                 lsa.lsa_nr_tgts, optarg);
5168                         if (lsa.lsa_nr_tgts < 0) {
5169                                 fprintf(stderr,
5170                                         "%s %s: invalid MDT target(s) '%s'\n",
5171                                         progname, argv[0], optarg);
5172                                 return CMD_HELP;
5173                         }
5174
5175                         lsa.lsa_tgts = mdts;
5176                         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
5177                                 lsa.lsa_stripe_off = mdts[0];
5178                         break;
5179 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 16, 53, 0)
5180                 case 'm':
5181                         fprintf(stderr, "warning: '-m' is deprecated, "
5182                                 "use '--mode' or '-o' instead\n");
5183 #endif
5184                 case 'o':
5185                         mode_opt = optarg;
5186                         break;
5187                 default:
5188                         fprintf(stderr, "%s %s: unrecognized option '%s'\n",
5189                                 progname, argv[0], argv[optind - 1]);
5190                         return CMD_HELP;
5191                 }
5192         }
5193
5194         if (optind == argc) {
5195                 fprintf(stderr, "%s %s: DIR must be specified\n",
5196                         progname, argv[0]);
5197                 return CMD_HELP;
5198         }
5199
5200         if (!delete && lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT &&
5201             lsa.lsa_stripe_count == LLAPI_LAYOUT_DEFAULT) {
5202                 fprintf(stderr,
5203                         "%s %s: stripe offset and count must be specified\n",
5204                         progname, argv[0]);
5205                 return CMD_HELP;
5206         }
5207
5208         if (delete &&
5209             (lsa.lsa_stripe_off != LLAPI_LAYOUT_DEFAULT ||
5210              lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT)) {
5211                 fprintf(stderr,
5212                         "%s %s: cannot specify -d with -c or -i options\n",
5213                         progname, argv[0]);
5214                 return CMD_HELP;
5215         }
5216
5217         if (mode_opt != NULL) {
5218                 mode = strtoul(mode_opt, &end, 8);
5219                 if (*end != '\0') {
5220                         fprintf(stderr,
5221                                 "%s %s: bad MODE '%s'\n",
5222                                 progname, argv[0], mode_opt);
5223                         return CMD_HELP;
5224                 }
5225                 previous_mode = umask(0);
5226         }
5227
5228         /*
5229          * initialize stripe parameters, in case param is converted to specific,
5230          * i.e, 'lfs mkdir -i -1 -c N', always allocate space for lsp_tgts.
5231          */
5232         param = calloc(1, offsetof(typeof(*param),
5233                        lsp_tgts[lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT ?
5234                                 lsa.lsa_stripe_count : lsa.lsa_nr_tgts]));
5235         if (param == NULL) {
5236                 fprintf(stderr,
5237                         "%s %s: cannot allocate memory for parameters: %s\n",
5238                         progname, argv[0], strerror(ENOMEM));
5239                 return CMD_HELP;
5240         }
5241
5242         if (lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT)
5243                 param->lsp_stripe_count = lsa.lsa_stripe_count;
5244         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
5245                 param->lsp_stripe_offset = -1;
5246         else
5247                 param->lsp_stripe_offset = lsa.lsa_stripe_off;
5248         if (lsa.lsa_pattern != LLAPI_LAYOUT_RAID0)
5249                 param->lsp_stripe_pattern = lsa.lsa_pattern;
5250         else
5251                 param->lsp_stripe_pattern = LMV_HASH_TYPE_FNV_1A_64;
5252         param->lsp_pool = lsa.lsa_pool_name;
5253         param->lsp_is_specific = false;
5254         if (lsa.lsa_nr_tgts > 1) {
5255                 if (lsa.lsa_stripe_count > 0 &&
5256                     lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT &&
5257                     lsa.lsa_stripe_count != lsa.lsa_nr_tgts) {
5258                         fprintf(stderr,
5259                                 "error: %s: stripe count %lld doesn't match the number of MDTs: %d\n",
5260                                 argv[0], lsa.lsa_stripe_count,
5261                                 lsa.lsa_nr_tgts);
5262                         free(param);
5263                         return CMD_HELP;
5264                 }
5265
5266                 param->lsp_is_specific = true;
5267                 param->lsp_stripe_count = lsa.lsa_nr_tgts;
5268                 memcpy(param->lsp_tgts, mdts, sizeof(*mdts) * lsa.lsa_nr_tgts);
5269         }
5270
5271         dname = argv[optind];
5272         do {
5273                 if (default_stripe) {
5274                         result = llapi_dir_set_default_lmv(dname, param);
5275                 } else {
5276                         /* if current \a dname isn't under the same \a mntdir
5277                          * as the last one, and the last one was
5278                          * auto-distributed, restore \a param.
5279                          */
5280                         if (mntdir[0] != '\0' &&
5281                             strncmp(dname, mntdir, strlen(mntdir)) &&
5282                             auto_distributed) {
5283                                 param->lsp_is_specific = false;
5284                                 param->lsp_stripe_offset = -1;
5285                                 auto_distributed = false;
5286                         }
5287
5288                         if (!param->lsp_is_specific &&
5289                             param->lsp_stripe_offset == -1) {
5290                                 char path[PATH_MAX] = "";
5291
5292                                 if (!lsb) {
5293                                         lsb = malloc(sizeof(*lsb));
5294                                         if (!lsb) {
5295                                                 result = -ENOMEM;
5296                                                 break;
5297                                         }
5298                                 }
5299                                 lsb->sb_count = 0;
5300
5301                                 /* use mntdir for dirname() temporarily */
5302                                 strncpy(mntdir, dname, sizeof(mntdir) - 1);
5303                                 if (!realpath(dirname(mntdir), path)) {
5304                                         result = -errno;
5305                                         fprintf(stderr,
5306                                                 "error: invalid path '%s': %s\n",
5307                                                 argv[optind], strerror(errno));
5308                                         break;
5309                                 }
5310                                 mntdir[0] = '\0';
5311
5312                                 result = llapi_search_mounts(path, 0, mntdir,
5313                                                              NULL);
5314                                 if (result < 0 || mntdir[0] == '\0') {
5315                                         fprintf(stderr,
5316                                                 "No suitable Lustre mount found\n");
5317                                         break;
5318                                 }
5319
5320                                 result = mntdf(mntdir, NULL, NULL, 0,
5321                                                LL_STATFS_LMV, lsb);
5322                                 if (result < 0)
5323                                         break;
5324
5325                                 if (param->lsp_stripe_count > lsb->sb_count) {
5326                                         fprintf(stderr,
5327                                                 "error: stripe count %d is too big\n",
5328                                                 param->lsp_stripe_count);
5329                                         result = -ERANGE;
5330                                         break;
5331                                 }
5332
5333                                 qsort(lsb->sb_buf, lsb->sb_count,
5334                                       sizeof(struct ll_statfs_data),
5335                                       ll_statfs_data_comp);
5336
5337                                 auto_distributed = true;
5338                         }
5339
5340                         if (auto_distributed) {
5341                                 int r;
5342                                 int nr = MAX(param->lsp_stripe_count,
5343                                              lsb->sb_count / 2);
5344
5345                                 /* don't use server whose usage is above 90% */
5346                                 while (nr != param->lsp_stripe_count &&
5347                                        obd_statfs_ratio(&lsb->sb_buf[nr].sd_st,
5348                                                         false) > 90)
5349                                         nr = MAX(param->lsp_stripe_count,
5350                                                  nr / 2);
5351
5352                                 /* get \a r between [0, nr) */
5353                                 r = rand() % nr;
5354
5355                                 param->lsp_stripe_offset =
5356                                         lsb->sb_buf[r].sd_index;
5357                                 if (param->lsp_stripe_count > 1) {
5358                                         int i = 0;
5359
5360                                         param->lsp_is_specific = true;
5361                                         for (; i < param->lsp_stripe_count; i++)
5362                                                 param->lsp_tgts[(i + r) % nr] =
5363                                                         lsb->sb_buf[i].sd_index;
5364                                 }
5365                         }
5366
5367                         result = llapi_dir_create(dname, mode, param);
5368                 }
5369
5370                 if (result) {
5371                         fprintf(stderr,
5372                                 "%s setdirstripe: cannot create stripe dir '%s': %s\n",
5373                                 progname, dname, strerror(-result));
5374                         break;
5375                 }
5376                 dname = argv[++optind];
5377         } while (dname != NULL);
5378
5379         if (mode_opt != NULL)
5380                 umask(previous_mode);
5381
5382         free(lsb);
5383         free(param);
5384         return result;
5385 }
5386
5387 /* functions */
5388 static int lfs_rmentry(int argc, char **argv)
5389 {
5390         char *dname;
5391         int   index;
5392         int   result = 0;
5393
5394         if (argc <= 1) {
5395                 fprintf(stderr, "error: %s: missing dirname\n",
5396                         argv[0]);
5397                 return CMD_HELP;
5398         }
5399
5400         index = 1;
5401         dname = argv[index];
5402         while (dname != NULL) {
5403                 result = llapi_direntry_remove(dname);
5404                 if (result) {
5405                         fprintf(stderr, "error: %s: remove dir entry '%s' "
5406                                 "failed\n", argv[0], dname);
5407                         break;
5408                 }
5409                 dname = argv[++index];
5410         }
5411         return result;
5412 }
5413
5414 static int lfs_mv(int argc, char **argv)
5415 {
5416         struct lmv_user_md lmu = { LMV_USER_MAGIC };
5417         struct find_param param = {
5418                 .fp_max_depth = -1,
5419                 .fp_mdt_index = -1,
5420         };
5421         char *end;
5422         int c;
5423         int rc = 0;
5424         struct option long_opts[] = {
5425         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument },
5426         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
5427         { .name = NULL } };
5428
5429         while ((c = getopt_long(argc, argv, "m:M:v", long_opts, NULL)) != -1) {
5430                 switch (c) {
5431 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
5432                 case 'M':
5433                         fprintf(stderr, "warning: '-M' deprecated"
5434                                 ", use '--mdt-index' or '-m' instead\n");
5435 #endif
5436                 case 'm':
5437                         lmu.lum_stripe_offset = strtoul(optarg, &end, 0);
5438                         if (*end != '\0') {
5439                                 fprintf(stderr, "%s mv: bad MDT index '%s'\n",
5440                                         progname, optarg);
5441                                 return CMD_HELP;
5442                         }
5443                         break;
5444                 case 'v':
5445                         param.fp_verbose = VERBOSE_DETAIL;
5446                         break;
5447                 default:
5448                         fprintf(stderr, "%s mv: unrecognized option '%s'\n",
5449                                 progname, argv[optind - 1]);
5450                         return CMD_HELP;
5451                 }
5452         }
5453
5454         if (lmu.lum_stripe_offset == -1) {
5455                 fprintf(stderr, "%s mv: MDT index must be specified\n",
5456                         progname);
5457                 return CMD_HELP;
5458         }
5459
5460         if (optind >= argc) {
5461                 fprintf(stderr, "%s mv: DIR must be specified\n", progname);
5462                 return CMD_HELP;
5463         }
5464
5465
5466         /* initialize migrate mdt parameters */
5467         param.fp_lmv_md = &lmu;
5468         param.fp_migrate = 1;
5469         rc = llapi_migrate_mdt(argv[optind], &param);
5470         if (rc != 0)
5471                 fprintf(stderr, "%s mv: cannot migrate '%s' to MDT%04x: %s\n",
5472                         progname, argv[optind], param.fp_mdt_index,
5473                         strerror(-rc));
5474         return rc;
5475 }
5476
5477 static int lfs_osts(int argc, char **argv)
5478 {
5479         return lfs_tgts(argc, argv);
5480 }
5481
5482 static int lfs_mdts(int argc, char **argv)
5483 {
5484         return lfs_tgts(argc, argv);
5485 }
5486
5487 static int lfs_df(int argc, char **argv)
5488 {
5489         char mntdir[PATH_MAX] = {'\0'}, path[PATH_MAX] = {'\0'};
5490         enum mntdf_flags flags = MNTDF_SHOW;
5491         int ops = LL_STATFS_LMV | LL_STATFS_LOV;
5492         int c, rc = 0, index = 0;
5493         char fsname[PATH_MAX] = "", *pool_name = NULL;
5494         struct option long_opts[] = {
5495         { .val = 'h',   .name = "human-readable",
5496                                                 .has_arg = no_argument },
5497         { .val = 'i',   .name = "inodes",       .has_arg = no_argument },
5498         { .val = 'l',   .name = "lazy",         .has_arg = no_argument },
5499         { .val = 'p',   .name = "pool",         .has_arg = required_argument },
5500         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
5501         { .name = NULL} };
5502
5503         while ((c = getopt_long(argc, argv, "hilp:v", long_opts, NULL)) != -1) {
5504                 switch (c) {
5505                 case 'h':
5506                         flags |= MNTDF_COOKED;
5507                         break;
5508                 case 'i':
5509                         flags |= MNTDF_INODES;
5510                         break;
5511                 case 'l':
5512                         flags |= MNTDF_LAZY;
5513                         break;
5514                 case 'p':
5515                         pool_name = optarg;
5516                         break;
5517                 case 'v':
5518                         flags |= MNTDF_VERBOSE;
5519                         break;
5520                 default:
5521                         return CMD_HELP;
5522                 }
5523         }
5524         if (optind < argc && !realpath(argv[optind], path)) {
5525                 rc = -errno;
5526                 fprintf(stderr, "error: invalid path '%s': %s\n",
5527                         argv[optind], strerror(-rc));
5528                 return rc;
5529         }
5530
5531         while (!llapi_search_mounts(path, index++, mntdir, fsname)) {
5532                 /* Check if we have a mount point */
5533                 if (mntdir[0] == '\0')
5534                         continue;
5535
5536                 rc = mntdf(mntdir, fsname, pool_name, flags, ops, NULL);
5537                 if (rc || path[0] != '\0')
5538                         break;
5539                 fsname[0] = '\0'; /* avoid matching in next loop */
5540                 mntdir[0] = '\0'; /* avoid matching in next loop */
5541         }
5542
5543         return rc;
5544 }
5545
5546 static int lfs_getname(int argc, char **argv)
5547 {
5548         char mntdir[PATH_MAX] = "", path[PATH_MAX] = "", fsname[PATH_MAX] = "";
5549         int rc = 0, index = 0, c;
5550         char buf[sizeof(struct obd_uuid)];
5551
5552         while ((c = getopt(argc, argv, "h")) != -1)
5553                 return CMD_HELP;
5554
5555         if (optind == argc) { /* no paths specified, get all paths. */
5556                 while (!llapi_search_mounts(path, index++, mntdir, fsname)) {
5557                         rc = llapi_getname(mntdir, buf, sizeof(buf));
5558                         if (rc < 0) {
5559                                 fprintf(stderr,
5560                                         "cannot get name for `%s': %s\n",
5561                                         mntdir, strerror(-rc));
5562                                 break;
5563                         }
5564
5565                         printf("%s %s\n", buf, mntdir);
5566
5567                         path[0] = fsname[0] = mntdir[0] = 0;
5568                 }
5569         } else { /* paths specified, only attempt to search these. */
5570                 for (; optind < argc; optind++) {
5571                         rc = llapi_getname(argv[optind], buf, sizeof(buf));
5572                         if (rc < 0) {
5573                                 fprintf(stderr,
5574                                         "cannot get name for `%s': %s\n",
5575                                         argv[optind], strerror(-rc));
5576                                 break;
5577                         }
5578
5579                         printf("%s %s\n", buf, argv[optind]);
5580                 }
5581         }
5582         return rc;
5583 }
5584
5585 static int lfs_check(int argc, char **argv)
5586 {
5587         int rc;
5588         char mntdir[PATH_MAX] = {'\0'};
5589         int num_types = 1;
5590         char *obd_types[2];
5591         char obd_type1[4];
5592         char obd_type2[4];
5593
5594         if (argc != 2) {
5595                 fprintf(stderr, "%s check: server type must be specified\n",
5596                         progname);
5597                 return CMD_HELP;
5598         }
5599
5600         obd_types[0] = obd_type1;
5601         obd_types[1] = obd_type2;
5602
5603         if (strcmp(argv[1], "osts") == 0) {
5604                 strcpy(obd_types[0], "osc");
5605         } else if (strcmp(argv[1], "mds") == 0) {
5606                 strcpy(obd_types[0], "mdc");
5607         } else if (strcmp(argv[1], "servers") == 0) {
5608                 num_types = 2;
5609                 strcpy(obd_types[0], "osc");
5610                 strcpy(obd_types[1], "mdc");
5611         } else {
5612                 fprintf(stderr, "%s check: unrecognized option '%s'\n",
5613                         progname, argv[1]);
5614                 return CMD_HELP;
5615         }
5616
5617         rc = llapi_search_mounts(NULL, 0, mntdir, NULL);
5618         if (rc < 0 || mntdir[0] == '\0') {
5619                 fprintf(stderr,
5620                         "%s check: cannot find mounted Lustre filesystem: %s\n",
5621                         progname, (rc < 0) ? strerror(-rc) : strerror(ENODEV));
5622                 return rc;
5623         }
5624
5625         rc = llapi_target_check(num_types, obd_types, mntdir);
5626         if (rc)
5627                 fprintf(stderr, "%s check: cannot check target '%s': %s\n",
5628                         progname, argv[1], strerror(-rc));
5629
5630         return rc;
5631
5632 }
5633
5634 #ifdef HAVE_SYS_QUOTA_H
5635 #define ARG2INT(nr, str, msg)                                           \
5636 do {                                                                    \
5637         char *endp;                                                     \
5638         nr = strtol(str, &endp, 0);                                     \
5639         if (*endp != '\0') {                                            \
5640                 fprintf(stderr, "%s: bad %s '%s'\n",                    \
5641                         progname, msg, str);                            \
5642                 return CMD_HELP;                                        \
5643         }                                                               \
5644 } while (0)
5645
5646 #define ADD_OVERFLOW(a,b) ((a + b) < a) ? (a = ULONG_MAX) : (a = a + b)
5647
5648 /* Convert format time string "XXwXXdXXhXXmXXs" into seconds value
5649  * returns the value or ULONG_MAX on integer overflow or incorrect format
5650  * Notes:
5651  *        1. the order of specifiers is arbitrary (may be: 5w3s or 3s5w)
5652  *        2. specifiers may be encountered multiple times (2s3s is 5 seconds)
5653  *        3. empty integer value is interpreted as 0
5654  */
5655 static unsigned long str2sec(const char* timestr)
5656 {
5657         const char spec[] = "smhdw";
5658         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
5659         unsigned long val = 0;
5660         char *tail;
5661
5662         if (strpbrk(timestr, spec) == NULL) {
5663                 /* no specifiers inside the time string,
5664                    should treat it as an integer value */
5665                 val = strtoul(timestr, &tail, 10);
5666                 return *tail ? ULONG_MAX : val;
5667         }
5668
5669         /* format string is XXwXXdXXhXXmXXs */
5670         while (*timestr) {
5671                 unsigned long v;
5672                 int ind;
5673                 char* ptr;
5674
5675                 v = strtoul(timestr, &tail, 10);
5676                 if (v == ULONG_MAX || *tail == '\0')
5677                         /* value too large (ULONG_MAX or more)
5678                            or missing specifier */
5679                         goto error;
5680
5681                 ptr = strchr(spec, *tail);
5682                 if (ptr == NULL)
5683                         /* unknown specifier */
5684                         goto error;
5685
5686                 ind = ptr - spec;
5687
5688                 /* check if product will overflow the type */
5689                 if (!(v < ULONG_MAX / mult[ind]))
5690                         goto error;
5691
5692                 ADD_OVERFLOW(val, mult[ind] * v);
5693                 if (val == ULONG_MAX)
5694                         goto error;
5695
5696                 timestr = tail + 1;
5697         }
5698
5699         return val;
5700
5701 error:
5702         return ULONG_MAX;
5703 }
5704
5705 #define ARG2ULL(nr, str, def_units)                                     \
5706 do {                                                                    \
5707         unsigned long long limit, units = def_units;                    \
5708         int rc;                                                         \
5709                                                                         \
5710         rc = llapi_parse_size(str, &limit, &units, 1);                  \
5711         if (rc < 0) {                                                   \
5712                 fprintf(stderr, "%s: invalid limit '%s'\n",             \
5713                         progname, str);                                 \
5714                 return CMD_HELP;                                        \
5715         }                                                               \
5716         nr = limit;                                                     \
5717 } while (0)
5718
5719 static inline int has_times_option(int argc, char **argv)
5720 {
5721         int i;
5722
5723         for (i = 1; i < argc; i++)
5724                 if (!strcmp(argv[i], "-t"))
5725                         return 1;
5726
5727         return 0;
5728 }
5729
5730 int lfs_setquota_times(int argc, char **argv)
5731 {
5732         int c, rc;
5733         struct if_quotactl qctl;
5734         char *mnt, *obd_type = (char *)qctl.obd_type;
5735         struct obd_dqblk *dqb = &qctl.qc_dqblk;
5736         struct obd_dqinfo *dqi = &qctl.qc_dqinfo;
5737         struct option long_opts[] = {
5738         { .val = 'b',   .name = "block-grace",  .has_arg = required_argument },
5739         { .val = 'g',   .name = "group",        .has_arg = no_argument },
5740         { .val = 'i',   .name = "inode-grace",  .has_arg = required_argument },
5741         { .val = 'p',   .name = "projid",       .has_arg = no_argument },
5742         { .val = 't',   .name = "times",        .has_arg = no_argument },
5743         { .val = 'u',   .name = "user",         .has_arg = no_argument },
5744         { .name = NULL } };
5745         int qtype;
5746
5747         memset(&qctl, 0, sizeof(qctl));
5748         qctl.qc_cmd  = LUSTRE_Q_SETINFO;
5749         qctl.qc_type = ALLQUOTA;
5750
5751         while ((c = getopt_long(argc, argv, "b:gi:ptu",
5752                                 long_opts, NULL)) != -1) {
5753                 switch (c) {
5754                 case 'u':
5755                         qtype = USRQUOTA;
5756                         goto quota_type;
5757                 case 'g':
5758                         qtype = GRPQUOTA;
5759                         goto quota_type;
5760                 case 'p':
5761                         qtype = PRJQUOTA;
5762 quota_type:
5763                         if (qctl.qc_type != ALLQUOTA) {
5764                                 fprintf(stderr, "error: -u/g/p can't be used "
5765                                                 "more than once\n");
5766                                 return CMD_HELP;
5767                         }
5768                         qctl.qc_type = qtype;
5769                         break;
5770                 case 'b':
5771                         if ((dqi->dqi_bgrace = str2sec(optarg)) == ULONG_MAX) {
5772                                 fprintf(stderr, "error: bad block-grace: %s\n",
5773                                         optarg);
5774                                 return CMD_HELP;
5775                         }
5776                         dqb->dqb_valid |= QIF_BTIME;
5777                         break;
5778                 case 'i':
5779                         if ((dqi->dqi_igrace = str2sec(optarg)) == ULONG_MAX) {
5780                                 fprintf(stderr, "error: bad inode-grace: %s\n",
5781                                         optarg);
5782                                 return CMD_HELP;
5783                         }
5784                         dqb->dqb_valid |= QIF_ITIME;
5785                         break;
5786                 case 't': /* Yes, of course! */
5787                         break;
5788                 default: /* getopt prints error message for us when opterr != 0 */
5789                         return CMD_HELP;
5790                 }
5791         }
5792
5793         if (qctl.qc_type == ALLQUOTA) {
5794                 fprintf(stderr, "error: neither -u, -g nor -p specified\n");
5795                 return CMD_HELP;
5796         }
5797
5798         if (optind != argc - 1) {
5799                 fprintf(stderr, "error: unexpected parameters encountered\n");
5800                 return CMD_HELP;
5801         }
5802
5803         if ((dqb->dqb_valid | QIF_BTIME && dqi->dqi_bgrace >= UINT_MAX) ||
5804             (dqb->dqb_valid | QIF_ITIME && dqi->dqi_igrace >= UINT_MAX)) {
5805                 fprintf(stderr, "error: grace time is too large\n");
5806                 return CMD_HELP;
5807         }
5808
5809         mnt = argv[optind];
5810         rc = llapi_quotactl(mnt, &qctl);
5811         if (rc) {
5812                 if (*obd_type)
5813                         fprintf(stderr, "%s %s ", obd_type,
5814                                 obd_uuid2str(&qctl.obd_uuid));
5815                 fprintf(stderr, "setquota failed: %s\n", strerror(-rc));
5816                 return rc;
5817         }
5818
5819         return 0;
5820 }
5821
5822 #define BSLIMIT (1 << 0)
5823 #define BHLIMIT (1 << 1)
5824 #define ISLIMIT (1 << 2)
5825 #define IHLIMIT (1 << 3)
5826
5827 int lfs_setquota(int argc, char **argv)
5828 {
5829         int c, rc = 0;
5830         struct if_quotactl qctl;
5831         char *mnt, *obd_type = (char *)qctl.obd_type;
5832         struct obd_dqblk *dqb = &qctl.qc_dqblk;
5833         struct option long_opts[] = {
5834         { .val = 'b',   .name = "block-softlimit",
5835                                                 .has_arg = required_argument },
5836         { .val = 'B',   .name = "block-hardlimit",
5837                                                 .has_arg = required_argument },
5838         { .val = 'd',   .name = "default",      .has_arg = no_argument },
5839         { .val = 'g',   .name = "group",        .has_arg = required_argument },
5840         { .val = 'G',   .name = "default-grp",  .has_arg = no_argument },
5841         { .val = 'i',   .name = "inode-softlimit",
5842                                                 .has_arg = required_argument },
5843         { .val = 'I',   .name = "inode-hardlimit",
5844                                                 .has_arg = required_argument },
5845         { .val = 'p',   .name = "projid",       .has_arg = required_argument },
5846         { .val = 'P',   .name = "default-prj",  .has_arg = no_argument },
5847         { .val = 'u',   .name = "user",         .has_arg = required_argument },
5848         { .val = 'U',   .name = "default-usr",  .has_arg = no_argument },
5849         { .name = NULL } };
5850         unsigned limit_mask = 0;
5851         char *endptr;
5852         bool use_default = false;
5853         int qtype;
5854
5855         if (has_times_option(argc, argv))
5856                 return lfs_setquota_times(argc, argv);
5857
5858         memset(&qctl, 0, sizeof(qctl));
5859         qctl.qc_cmd  = LUSTRE_Q_SETQUOTA;
5860         qctl.qc_type = ALLQUOTA; /* ALLQUOTA makes no sense for setquota,
5861                                   * so it can be used as a marker that qc_type
5862                                   * isn't reinitialized from command line */
5863
5864         while ((c = getopt_long(argc, argv, "b:B:dg:Gi:I:p:Pu:U",
5865                 long_opts, NULL)) != -1) {
5866                 switch (c) {
5867                 case 'U':
5868                         qctl.qc_cmd = LUSTRE_Q_SETDEFAULT;
5869                         qtype = USRQUOTA;
5870                         qctl.qc_id = 0;
5871                         goto quota_type_def;
5872                 case 'u':
5873                         qtype = USRQUOTA;
5874                         rc = name2uid(&qctl.qc_id, optarg);
5875                         goto quota_type;
5876                 case 'G':
5877                         qctl.qc_cmd = LUSTRE_Q_SETDEFAULT;
5878                         qtype = GRPQUOTA;
5879                         qctl.qc_id = 0;
5880                         goto quota_type_def;
5881                 case 'g':
5882                         qtype = GRPQUOTA;
5883                         rc = name2gid(&qctl.qc_id, optarg);
5884                         goto quota_type;
5885                 case 'P':
5886                         qctl.qc_cmd = LUSTRE_Q_SETDEFAULT;
5887                         qtype = PRJQUOTA;
5888                         qctl.qc_id = 0;
5889                         goto quota_type_def;
5890                 case 'p':
5891                         qtype = PRJQUOTA;
5892                         rc = name2projid(&qctl.qc_id, optarg);
5893 quota_type:
5894                         if (rc) {
5895                                 qctl.qc_id = strtoul(optarg, &endptr, 10);
5896                                 if (*endptr != '\0') {
5897                                         fprintf(stderr, "%s setquota: invalid"
5898                                                 " id '%s'\n", progname, optarg);
5899                                         return -1;
5900                                 }
5901                         }
5902
5903                         if (qctl.qc_id == 0) {
5904                                 fprintf(stderr, "%s setquota: can't set quota"
5905                                         " for root usr/group/project.\n",
5906                                         progname);
5907                                 return -1;
5908                         }
5909
5910 quota_type_def:
5911                         if (qctl.qc_type != ALLQUOTA) {
5912                                 fprintf(stderr,
5913                                         "%s setquota: only one of -u, -U, -g,"
5914                                         " -G, -p or -P may be specified\n",
5915                                         progname);
5916                                 return CMD_HELP;
5917                         }
5918                         qctl.qc_type = qtype;
5919                         break;
5920                 case 'd':
5921                         qctl.qc_cmd = LUSTRE_Q_SETDEFAULT;
5922                         use_default = true;
5923                         break;
5924                 case 'b':
5925                         ARG2ULL(dqb->dqb_bsoftlimit, optarg, 1024);
5926                         dqb->dqb_bsoftlimit >>= 10;
5927                         limit_mask |= BSLIMIT;
5928                         if (dqb->dqb_bsoftlimit &&
5929                             dqb->dqb_bsoftlimit <= 1024) /* <= 1M? */
5930                                 fprintf(stderr,
5931                                         "%s setquota: warning: block softlimit '%llu' smaller than minimum qunit size\n"
5932                                         "See '%s help setquota' or Lustre manual for details\n",
5933                                         progname,
5934                                         (unsigned long long)dqb->dqb_bsoftlimit,
5935                                         progname);
5936                         break;
5937                 case 'B':
5938                         ARG2ULL(dqb->dqb_bhardlimit, optarg, 1024);
5939                         dqb->dqb_bhardlimit >>= 10;
5940                         limit_mask |= BHLIMIT;
5941                         if (dqb->dqb_bhardlimit &&
5942                             dqb->dqb_bhardlimit <= 1024) /* <= 1M? */
5943                                 fprintf(stderr,
5944                                         "%s setquota: warning: block hardlimit '%llu' smaller than minimum qunit size\n"
5945                                         "See '%s help setquota' or Lustre manual for details\n",
5946                                         progname,
5947                                         (unsigned long long)dqb->dqb_bhardlimit,
5948                                         progname);
5949                         break;
5950                 case 'i':
5951                         ARG2ULL(dqb->dqb_isoftlimit, optarg, 1);
5952                         limit_mask |= ISLIMIT;
5953                         if (dqb->dqb_isoftlimit &&
5954                             dqb->dqb_isoftlimit <= 1024) /* <= 1K inodes? */
5955                                 fprintf(stderr,
5956                                         "%s setquota: warning: inode softlimit '%llu' smaller than minimum qunit size\n"
5957                                         "See '%s help setquota' or Lustre manual for details\n",
5958                                         progname,
5959                                         (unsigned long long)dqb->dqb_isoftlimit,
5960                                         progname);
5961                         break;
5962                 case 'I':
5963                         ARG2ULL(dqb->dqb_ihardlimit, optarg, 1);
5964                         limit_mask |= IHLIMIT;
5965                         if (dqb->dqb_ihardlimit &&
5966                             dqb->dqb_ihardlimit <= 1024) /* <= 1K inodes? */
5967                                 fprintf(stderr,
5968                                         "%s setquota: warning: inode hardlimit '%llu' smaller than minimum qunit size\n"
5969                                         "See '%s help setquota' or Lustre manual for details\n",
5970                                         progname,
5971                                         (unsigned long long)dqb->dqb_ihardlimit,
5972                                         progname);
5973                         break;
5974                 default:
5975                         fprintf(stderr,
5976                                 "%s setquota: unrecognized option '%s'\n",
5977                                 progname, argv[optind - 1]);
5978                         return CMD_HELP;
5979                 }
5980         }
5981
5982         if (qctl.qc_type == ALLQUOTA) {
5983                 fprintf(stderr,
5984                         "%s setquota: either -u or -g must be specified\n",
5985                         progname);
5986                 return CMD_HELP;
5987         }
5988
5989         if (!use_default && limit_mask == 0) {
5990                 fprintf(stderr,
5991                         "%s setquota: at least one limit must be specified\n",
5992                         progname);
5993                 return CMD_HELP;
5994         }
5995
5996         if (use_default && limit_mask != 0) {
5997                 fprintf(stderr,
5998                         "%s setquota: limits should not be specified when"
5999                         " using default quota\n",
6000                         progname);
6001                 return CMD_HELP;
6002         }
6003
6004         if (use_default && qctl.qc_id == 0) {
6005                 fprintf(stderr,
6006                         "%s setquota: can not set default quota for root"
6007                         " user/group/project\n",
6008                         progname);
6009                 return CMD_HELP;
6010         }
6011
6012         if (optind != argc - 1) {
6013                 fprintf(stderr,
6014                         "%s setquota: filesystem not specified or unexpected argument '%s'\n",
6015                         progname, argv[optind]);
6016                 return CMD_HELP;
6017         }
6018
6019         mnt = argv[optind];
6020
6021         if (use_default) {
6022                 dqb->dqb_bhardlimit = 0;
6023                 dqb->dqb_bsoftlimit = 0;
6024                 dqb->dqb_ihardlimit = 0;
6025                 dqb->dqb_isoftlimit = 0;
6026                 dqb->dqb_itime = 0;
6027                 dqb->dqb_btime = 0;
6028                 dqb->dqb_valid |= QIF_LIMITS | QIF_TIMES;
6029         } else if ((!(limit_mask & BHLIMIT) ^ !(limit_mask & BSLIMIT)) ||
6030                    (!(limit_mask & IHLIMIT) ^ !(limit_mask & ISLIMIT))) {
6031                 /* sigh, we can't just set blimits/ilimits */
6032                 struct if_quotactl tmp_qctl = {.qc_cmd  = LUSTRE_Q_GETQUOTA,
6033                                                .qc_type = qctl.qc_type,
6034                                                .qc_id   = qctl.qc_id};
6035
6036                 rc = llapi_quotactl(mnt, &tmp_qctl);
6037                 if (rc < 0)
6038                         return rc;
6039
6040                 if (!(limit_mask & BHLIMIT))
6041                         dqb->dqb_bhardlimit = tmp_qctl.qc_dqblk.dqb_bhardlimit;
6042                 if (!(limit_mask & BSLIMIT))
6043                         dqb->dqb_bsoftlimit = tmp_qctl.qc_dqblk.dqb_bsoftlimit;
6044                 if (!(limit_mask & IHLIMIT))
6045                         dqb->dqb_ihardlimit = tmp_qctl.qc_dqblk.dqb_ihardlimit;
6046                 if (!(limit_mask & ISLIMIT))
6047                         dqb->dqb_isoftlimit = tmp_qctl.qc_dqblk.dqb_isoftlimit;
6048
6049                 /* Keep grace times if we have got no softlimit arguments */
6050                 if ((limit_mask & BHLIMIT) && !(limit_mask & BSLIMIT)) {
6051                         dqb->dqb_valid |= QIF_BTIME;
6052                         dqb->dqb_btime = tmp_qctl.qc_dqblk.dqb_btime;
6053                 }
6054
6055                 if ((limit_mask & IHLIMIT) && !(limit_mask & ISLIMIT)) {
6056                         dqb->dqb_valid |= QIF_ITIME;
6057                         dqb->dqb_itime = tmp_qctl.qc_dqblk.dqb_itime;
6058                 }
6059         }
6060
6061         dqb->dqb_valid |= (limit_mask & (BHLIMIT | BSLIMIT)) ? QIF_BLIMITS : 0;
6062         dqb->dqb_valid |= (limit_mask & (IHLIMIT | ISLIMIT)) ? QIF_ILIMITS : 0;
6063
6064         rc = llapi_quotactl(mnt, &qctl);
6065         if (rc) {
6066                 if (*obd_type)
6067                         fprintf(stderr,
6068                                 "%s setquota: cannot quotactl '%s' '%s': %s",
6069                                 progname, obd_type,
6070                                 obd_uuid2str(&qctl.obd_uuid), strerror(-rc));
6071                 return rc;
6072         }
6073
6074         return 0;
6075 }
6076
6077 /* Converts seconds value into format string
6078  * result is returned in buf
6079  * Notes:
6080  *        1. result is in descenting order: 1w2d3h4m5s
6081  *        2. zero fields are not filled (except for p. 3): 5d1s
6082  *        3. zero seconds value is presented as "0s"
6083  */
6084 static char * __sec2str(time_t seconds, char *buf)
6085 {
6086         const char spec[] = "smhdw";
6087         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
6088         unsigned long c;
6089         char *tail = buf;
6090         int i;
6091
6092         for (i = sizeof(mult) / sizeof(mult[0]) - 1 ; i >= 0; i--) {
6093                 c = seconds / mult[i];
6094
6095                 if (c > 0 || (i == 0 && buf == tail))
6096                         tail += snprintf(tail, 40-(tail-buf), "%lu%c", c, spec[i]);
6097
6098                 seconds %= mult[i];
6099         }
6100
6101         return tail;
6102 }
6103
6104 static void sec2str(time_t seconds, char *buf, int rc)
6105 {
6106         char *tail = buf;
6107
6108         if (rc)
6109                 *tail++ = '[';
6110
6111         tail = __sec2str(seconds, tail);
6112
6113         if (rc && tail - buf < 39) {
6114                 *tail++ = ']';
6115                 *tail++ = 0;
6116         }
6117 }
6118
6119 static void diff2str(time_t seconds, char *buf, time_t now)
6120 {
6121
6122         buf[0] = 0;
6123         if (!seconds)
6124                 return;
6125         if (seconds <= now) {
6126                 strcpy(buf, "none");
6127                 return;
6128         }
6129         __sec2str(seconds - now, buf);
6130 }
6131
6132 static void print_quota_title(char *name, struct if_quotactl *qctl,
6133                               bool human_readable, bool show_default)
6134 {
6135         if (show_default) {
6136                 printf("Disk default %s quota:\n", qtype_name(qctl->qc_type));
6137                 printf("%15s %8s%8s%8s %8s%8s%8s\n",
6138                        "Filesystem", "bquota", "blimit", "bgrace",
6139                        "iquota", "ilimit", "igrace");
6140         } else {
6141                 printf("Disk quotas for %s %s (%cid %u):\n",
6142                        qtype_name(qctl->qc_type), name,
6143                        *qtype_name(qctl->qc_type), qctl->qc_id);
6144                 printf("%15s%8s %7s%8s%8s%8s %7s%8s%8s\n",
6145                        "Filesystem", human_readable ? "used" : "kbytes",
6146                        "quota", "limit", "grace",
6147                        "files", "quota", "limit", "grace");
6148         }
6149 }
6150
6151 static void kbytes2str(__u64 num, char *buf, int buflen, bool h)
6152 {
6153         if (!h) {
6154                 snprintf(buf, buflen, "%ju", (uintmax_t)num);
6155         } else {
6156                 if (num >> 40)
6157                         snprintf(buf, buflen, "%5.4gP",
6158                                  (double)num / ((__u64)1 << 40));
6159                 else if (num >> 30)
6160                         snprintf(buf, buflen, "%5.4gT",
6161                                  (double)num / (1 << 30));
6162                 else if (num >> 20)
6163                         snprintf(buf, buflen, "%5.4gG",
6164                                  (double)num / (1 << 20));
6165                 else if (num >> 10)
6166                         snprintf(buf, buflen, "%5.4gM",
6167                                  (double)num / (1 << 10));
6168                 else
6169                         snprintf(buf, buflen, "%ju%s", (uintmax_t)num, "k");
6170         }
6171 }
6172
6173 #define STRBUF_LEN      32
6174 static void print_quota(char *mnt, struct if_quotactl *qctl, int type,
6175                         int rc, bool h, bool show_default)
6176 {
6177         time_t now;
6178
6179         time(&now);
6180
6181         if (qctl->qc_cmd == LUSTRE_Q_GETQUOTA || qctl->qc_cmd == Q_GETOQUOTA ||
6182             qctl->qc_cmd == LUSTRE_Q_GETDEFAULT) {
6183                 int bover = 0, iover = 0;
6184                 struct obd_dqblk *dqb = &qctl->qc_dqblk;
6185                 char numbuf[3][STRBUF_LEN];
6186                 char timebuf[40];
6187                 char strbuf[STRBUF_LEN];
6188
6189                 if (dqb->dqb_bhardlimit &&
6190                     lustre_stoqb(dqb->dqb_curspace) >= dqb->dqb_bhardlimit) {
6191                         bover = 1;
6192                 } else if (dqb->dqb_bsoftlimit && dqb->dqb_btime) {
6193                         if (dqb->dqb_btime > now) {
6194                                 bover = 2;
6195                         } else {
6196                                 bover = 3;
6197                         }
6198                 }
6199
6200                 if (dqb->dqb_ihardlimit &&
6201                     dqb->dqb_curinodes >= dqb->dqb_ihardlimit) {
6202                         iover = 1;
6203                 } else if (dqb->dqb_isoftlimit && dqb->dqb_itime) {
6204                         if (dqb->dqb_itime > now) {
6205                                 iover = 2;
6206                         } else {
6207                                 iover = 3;
6208                         }
6209                 }
6210
6211
6212                 if (strlen(mnt) > 15)
6213                         printf("%s\n%15s", mnt, "");
6214                 else
6215                         printf("%15s", mnt);
6216
6217                 if (bover)
6218                         diff2str(dqb->dqb_btime, timebuf, now);
6219                 else if (show_default)
6220                         snprintf(timebuf, sizeof(timebuf), "%llu",
6221                                  (unsigned long long)dqb->dqb_btime);
6222
6223                 kbytes2str(lustre_stoqb(dqb->dqb_curspace),
6224                            strbuf, sizeof(strbuf), h);
6225                 if (rc == -EREMOTEIO)
6226                         sprintf(numbuf[0], "%s*", strbuf);
6227                 else
6228                         sprintf(numbuf[0], (dqb->dqb_valid & QIF_SPACE) ?
6229                                 "%s" : "[%s]", strbuf);
6230
6231                 kbytes2str(dqb->dqb_bsoftlimit, strbuf, sizeof(strbuf), h);
6232                 if (type == QC_GENERAL)
6233                         sprintf(numbuf[1], (dqb->dqb_valid & QIF_BLIMITS) ?
6234                                 "%s" : "[%s]", strbuf);
6235                 else
6236                         sprintf(numbuf[1], "%s", "-");
6237
6238                 kbytes2str(dqb->dqb_bhardlimit, strbuf, sizeof(strbuf), h);
6239                 sprintf(numbuf[2], (dqb->dqb_valid & QIF_BLIMITS) ?
6240                         "%s" : "[%s]", strbuf);
6241
6242                 if (show_default)
6243                         printf(" %6s %7s %7s", numbuf[1], numbuf[2], timebuf);
6244                 else
6245                         printf(" %7s%c %6s %7s %7s",
6246                                numbuf[0], bover ? '*' : ' ', numbuf[1],
6247                                numbuf[2], bover > 1 ? timebuf : "-");
6248
6249
6250                 if (iover)
6251                         diff2str(dqb->dqb_itime, timebuf, now);
6252                 else if (show_default)
6253                         snprintf(timebuf, sizeof(timebuf), "%llu",
6254                                  (unsigned long long)dqb->dqb_itime);
6255
6256                 snprintf(numbuf[0], sizeof(numbuf),
6257                          (dqb->dqb_valid & QIF_INODES) ? "%ju" : "[%ju]",
6258                          (uintmax_t)dqb->dqb_curinodes);
6259
6260                 if (type == QC_GENERAL)
6261                         sprintf(numbuf[1], (dqb->dqb_valid & QIF_ILIMITS) ?
6262                                 "%ju" : "[%ju]",
6263                                 (uintmax_t)dqb->dqb_isoftlimit);
6264                 else
6265                         sprintf(numbuf[1], "%s", "-");
6266
6267                 sprintf(numbuf[2], (dqb->dqb_valid & QIF_ILIMITS) ?
6268                         "%ju" : "[%ju]", (uintmax_t)dqb->dqb_ihardlimit);
6269
6270                 if (show_default)
6271                         printf(" %6s %7s %7s", numbuf[1], numbuf[2], timebuf);
6272                 else if (type != QC_OSTIDX)
6273                         printf(" %7s%c %6s %7s %7s",
6274                                numbuf[0], iover ? '*' : ' ', numbuf[1],
6275                                numbuf[2], iover > 1 ? timebuf : "-");
6276                 else
6277                         printf(" %7s %7s %7s %7s", "-", "-", "-", "-");
6278                 printf("\n");
6279
6280         } else if (qctl->qc_cmd == LUSTRE_Q_GETINFO ||
6281                    qctl->qc_cmd == Q_GETOINFO) {
6282                 char bgtimebuf[40];
6283                 char igtimebuf[40];
6284
6285                 sec2str(qctl->qc_dqinfo.dqi_bgrace, bgtimebuf, rc);
6286                 sec2str(qctl->qc_dqinfo.dqi_igrace, igtimebuf, rc);
6287                 printf("Block grace time: %s; Inode grace time: %s\n",
6288                        bgtimebuf, igtimebuf);
6289         }
6290 }
6291
6292 static int print_obd_quota(char *mnt, struct if_quotactl *qctl, int is_mdt,
6293                            bool h, __u64 *total)
6294 {
6295         int rc = 0, rc1 = 0, count = 0;
6296         __u32 valid = qctl->qc_valid;
6297
6298         rc = llapi_get_obd_count(mnt, &count, is_mdt);
6299         if (rc) {
6300                 fprintf(stderr, "can not get %s count: %s\n",
6301                         is_mdt ? "mdt": "ost", strerror(-rc));
6302                 return rc;
6303         }
6304
6305         for (qctl->qc_idx = 0; qctl->qc_idx < count; qctl->qc_idx++) {
6306                 qctl->qc_valid = is_mdt ? QC_MDTIDX : QC_OSTIDX;
6307                 rc = llapi_quotactl(mnt, qctl);
6308                 if (rc) {
6309                         /* It is remote client case. */
6310                         if (rc == -EOPNOTSUPP) {
6311                                 rc = 0;
6312                                 goto out;
6313                         }
6314
6315                         if (!rc1)
6316                                 rc1 = rc;
6317                         fprintf(stderr, "quotactl %s%d failed.\n",
6318                                 is_mdt ? "mdt": "ost", qctl->qc_idx);
6319                         continue;
6320                 }
6321
6322                 print_quota(obd_uuid2str(&qctl->obd_uuid), qctl,
6323                             qctl->qc_valid, 0, h, false);
6324                 *total += is_mdt ? qctl->qc_dqblk.dqb_ihardlimit :
6325                                    qctl->qc_dqblk.dqb_bhardlimit;
6326         }
6327 out:
6328         qctl->qc_valid = valid;
6329         return rc ? : rc1;
6330 }
6331
6332 static int get_print_quota(char *mnt, char *name, struct if_quotactl *qctl,
6333                            int verbose, int quiet, bool human_readable,
6334                            bool show_default)
6335 {
6336         int rc1 = 0, rc2 = 0, rc3 = 0;
6337         char *obd_type = (char *)qctl->obd_type;
6338         char *obd_uuid = (char *)qctl->obd_uuid.uuid;
6339         __u64 total_ialloc = 0, total_balloc = 0;
6340         bool use_default_for_blk = false;
6341         bool use_default_for_file = false;
6342         int inacc;
6343
6344         rc1 = llapi_quotactl(mnt, qctl);
6345         if (rc1 < 0) {
6346                 switch (rc1) {
6347                 case -ESRCH:
6348                         fprintf(stderr, "%s quotas are not enabled.\n",
6349                                 qtype_name(qctl->qc_type));
6350                         goto out;
6351                 case -EPERM:
6352                         fprintf(stderr, "Permission denied.\n");
6353                 case -ENODEV:
6354                 case -ENOENT:
6355                         /* We already got error message. */
6356                         goto out;
6357                 default:
6358                         fprintf(stderr, "Unexpected quotactl error: %s\n",
6359                                 strerror(-rc1));
6360                 }
6361         }
6362
6363         if (!show_default && qctl->qc_id == 0) {
6364                 qctl->qc_dqblk.dqb_bhardlimit = 0;
6365                 qctl->qc_dqblk.dqb_bsoftlimit = 0;
6366                 qctl->qc_dqblk.dqb_ihardlimit = 0;
6367                 qctl->qc_dqblk.dqb_isoftlimit = 0;
6368                 qctl->qc_dqblk.dqb_btime = 0;
6369                 qctl->qc_dqblk.dqb_itime = 0;
6370                 qctl->qc_dqblk.dqb_valid |= QIF_LIMITS | QIF_TIMES;
6371         }
6372
6373         if (qctl->qc_dqblk.dqb_valid & QIF_BTIME &&
6374             LQUOTA_FLAG(qctl->qc_dqblk.dqb_btime) & LQUOTA_FLAG_DEFAULT) {
6375                 use_default_for_blk = true;
6376                 qctl->qc_dqblk.dqb_btime &= LQUOTA_GRACE_MASK;
6377         }
6378
6379         if (qctl->qc_dqblk.dqb_valid & QIF_ITIME &&
6380             LQUOTA_FLAG(qctl->qc_dqblk.dqb_itime) & LQUOTA_FLAG_DEFAULT) {
6381                 use_default_for_file = true;
6382                 qctl->qc_dqblk.dqb_itime &= LQUOTA_GRACE_MASK;
6383         }
6384
6385         if ((qctl->qc_cmd == LUSTRE_Q_GETQUOTA ||
6386              qctl->qc_cmd == LUSTRE_Q_GETDEFAULT) && !quiet)
6387                 print_quota_title(name, qctl, human_readable, show_default);
6388
6389         if (rc1 && *obd_type)
6390                 fprintf(stderr, "%s %s ", obd_type, obd_uuid);
6391
6392         if (qctl->qc_valid != QC_GENERAL)
6393                 mnt = "";
6394
6395         inacc = (qctl->qc_cmd == LUSTRE_Q_GETQUOTA) &&
6396                 ((qctl->qc_dqblk.dqb_valid & (QIF_LIMITS|QIF_USAGE)) !=
6397                  (QIF_LIMITS|QIF_USAGE));
6398
6399         print_quota(mnt, qctl, QC_GENERAL, rc1, human_readable, show_default);
6400
6401         if (!show_default && verbose &&
6402             qctl->qc_valid == QC_GENERAL && qctl->qc_cmd != LUSTRE_Q_GETINFO) {
6403                 char strbuf[STRBUF_LEN];
6404
6405                 rc2 = print_obd_quota(mnt, qctl, 1, human_readable,
6406                                       &total_ialloc);
6407                 rc3 = print_obd_quota(mnt, qctl, 0, human_readable,
6408                                       &total_balloc);
6409                 kbytes2str(total_balloc, strbuf, sizeof(strbuf),
6410                            human_readable);
6411                 printf("Total allocated inode limit: %ju, total "
6412                        "allocated block limit: %s\n", (uintmax_t)total_ialloc,
6413                        strbuf);
6414         }
6415
6416         if (use_default_for_blk)
6417                 printf("%cid %u is using default block quota setting\n",
6418                        *qtype_name(qctl->qc_type), qctl->qc_id);
6419
6420         if (use_default_for_file)
6421                 printf("%cid %u is using default file quota setting\n",
6422                        *qtype_name(qctl->qc_type), qctl->qc_id);
6423
6424         if (rc1 || rc2 || rc3 || inacc)
6425                 printf("Some errors happened when getting quota info. "
6426                        "Some devices may be not working or deactivated. "
6427                        "The data in \"[]\" is inaccurate.\n");
6428 out:
6429         return rc1;
6430
6431 }
6432
6433 static int lfs_project(int argc, char **argv)
6434 {
6435         int ret = 0, err = 0, c, i;
6436         struct project_handle_control phc = { 0 };
6437         enum lfs_project_ops_t op;
6438
6439         phc.newline = true;
6440         phc.assign_projid = false;
6441         /* default action */
6442         op = LFS_PROJECT_LIST;
6443
6444         while ((c = getopt(argc, argv, "p:cCsdkr0")) != -1) {
6445                 switch (c) {
6446                 case 'c':
6447                         if (op != LFS_PROJECT_LIST) {
6448                                 fprintf(stderr,
6449                                         "%s: cannot specify '-c' '-C' '-s' together\n",
6450                                         progname);
6451                                 return CMD_HELP;
6452                         }
6453
6454                         op = LFS_PROJECT_CHECK;
6455                         break;
6456                 case 'C':
6457                         if (op != LFS_PROJECT_LIST) {
6458                                 fprintf(stderr,
6459                                         "%s: cannot specify '-c' '-C' '-s' together\n",
6460                                         progname);
6461                                 return CMD_HELP;
6462                         }
6463
6464                         op = LFS_PROJECT_CLEAR;
6465                         break;
6466                 case 's':
6467                         if (op != LFS_PROJECT_LIST) {
6468                                 fprintf(stderr,
6469                                         "%s: cannot specify '-c' '-C' '-s' together\n",
6470                                         progname);
6471                                 return CMD_HELP;
6472                         }
6473
6474                         phc.set_inherit = true;
6475                         op = LFS_PROJECT_SET;
6476                         break;
6477                 case 'd':
6478                         phc.dironly = true;
6479                         break;
6480                 case 'k':
6481                         phc.keep_projid = true;
6482                         break;
6483                 case 'r':
6484                         phc.recursive = true;
6485                         break;
6486                 case 'p':
6487                         phc.projid = strtoul(optarg, NULL, 0);
6488                         phc.assign_projid = true;
6489
6490                         break;
6491                 case '0':
6492                         phc.newline = false;
6493                         break;
6494                 default:
6495                         fprintf(stderr, "%s: invalid option '%c'\n",
6496                                 progname, optopt);
6497                         return CMD_HELP;
6498                 }
6499         }
6500
6501         if (phc.assign_projid && op == LFS_PROJECT_LIST) {
6502                 op = LFS_PROJECT_SET;
6503                 phc.set_projid = true;
6504         } else if (phc.assign_projid && op == LFS_PROJECT_SET) {
6505                 phc.set_projid = true;
6506         }
6507
6508         switch (op) {
6509         case LFS_PROJECT_CHECK:
6510                 if (phc.keep_projid) {
6511                         fprintf(stderr,
6512                                 "%s: '-k' is useless together with '-c'\n",
6513                                 progname);
6514                         return CMD_HELP;
6515                 }
6516                 break;
6517         case LFS_PROJECT_CLEAR:
6518                 if (!phc.newline) {
6519                         fprintf(stderr,
6520                                 "%s: '-0' is useless together with '-C'\n",
6521                                 progname);
6522                         return CMD_HELP;
6523                 }
6524                 if (phc.assign_projid) {
6525                         fprintf(stderr,
6526                                 "%s: '-p' is useless together with '-C'\n",
6527                                 progname);
6528                         return CMD_HELP;
6529                 }
6530                 break;
6531         case LFS_PROJECT_SET:
6532                 if (!phc.newline) {
6533                         fprintf(stderr,
6534                                 "%s: '-0' is useless together with '-s'\n",
6535                                 progname);
6536                         return CMD_HELP;
6537                 }
6538                 if (phc.keep_projid) {
6539                         fprintf(stderr,
6540                                 "%s: '-k' is useless together with '-s'\n",
6541                                 progname);
6542                         return CMD_HELP;
6543                 }
6544                 break;
6545         default:
6546                 if (!phc.newline) {
6547                         fprintf(stderr,
6548                                 "%s: '-0' is useless for list operations\n",
6549                                 progname);
6550                         return CMD_HELP;
6551                 }
6552                 break;
6553         }
6554
6555         argv += optind;
6556         argc -= optind;
6557         if (argc == 0) {
6558                 fprintf(stderr, "%s: missing file or directory target(s)\n",
6559                         progname);
6560                 return CMD_HELP;
6561         }
6562
6563         for (i = 0; i < argc; i++) {
6564                 switch (op) {
6565                 case LFS_PROJECT_CHECK:
6566                         err = lfs_project_check(argv[i], &phc);
6567                         break;
6568                 case LFS_PROJECT_LIST:
6569                         err = lfs_project_list(argv[i], &phc);
6570                         break;
6571                 case LFS_PROJECT_CLEAR:
6572                         err = lfs_project_clear(argv[i], &phc);
6573                         break;
6574                 case LFS_PROJECT_SET:
6575                         err = lfs_project_set(argv[i], &phc);
6576                         break;
6577                 default:
6578                         break;
6579                 }
6580                 if (err && !ret)
6581                         ret = err;
6582         }
6583
6584         return ret;
6585 }
6586
6587 static int lfs_quota(int argc, char **argv)
6588 {
6589         int c;
6590         char *mnt, *name = NULL;
6591         struct if_quotactl qctl = { .qc_cmd = LUSTRE_Q_GETQUOTA,
6592                                     .qc_type = ALLQUOTA };
6593         char *obd_uuid = (char *)qctl.obd_uuid.uuid;
6594         int rc = 0, rc1 = 0, verbose = 0, quiet = 0;
6595         char *endptr;
6596         __u32 valid = QC_GENERAL, idx = 0;
6597         bool human_readable = false;
6598         bool show_default = false;
6599         int qtype;
6600
6601         while ((c = getopt(argc, argv, "gGi:I:o:pPqtuUvh")) != -1) {
6602                 switch (c) {
6603                 case 'U':
6604                         show_default = true;
6605                 case 'u':
6606                         qtype = USRQUOTA;
6607                         goto quota_type;
6608                 case 'G':
6609                         show_default = true;
6610                 case 'g':
6611                         qtype = GRPQUOTA;
6612                         goto quota_type;
6613                 case 'P':
6614                         show_default = true;
6615                 case 'p':
6616                         qtype = PRJQUOTA;
6617 quota_type:
6618                         if (qctl.qc_type != ALLQUOTA) {
6619                                 fprintf(stderr,
6620                                         "%s quota: only one of -u, -g, or -p may be specified\n",
6621                                         progname);
6622                                 return CMD_HELP;
6623                         }
6624                         qctl.qc_type = qtype;
6625                         break;
6626                 case 't':
6627                         qctl.qc_cmd = LUSTRE_Q_GETINFO;
6628                         break;
6629                 case 'o':
6630                         valid = qctl.qc_valid = QC_UUID;
6631                         snprintf(obd_uuid, sizeof(qctl.obd_uuid), "%s", optarg);
6632                         break;
6633                 case 'i':
6634                         valid = qctl.qc_valid = QC_MDTIDX;
6635                         idx = qctl.qc_idx = atoi(optarg);
6636                         if (idx == 0 && *optarg != '0') {
6637                                 fprintf(stderr,
6638                                         "%s quota: invalid MDT index '%s'\n",
6639                                         progname, optarg);
6640                                 return CMD_HELP;
6641                         }
6642                         break;
6643                 case 'I':
6644                         valid = qctl.qc_valid = QC_OSTIDX;
6645                         idx = qctl.qc_idx = atoi(optarg);
6646                         if (idx == 0 && *optarg != '0') {
6647                                 fprintf(stderr,
6648                                         "%s quota: invalid OST index '%s'\n",
6649                                         progname, optarg);
6650                                 return CMD_HELP;
6651                         }
6652                         break;
6653                 case 'v':
6654                         verbose = 1;
6655                         break;
6656                 case 'q':
6657                         quiet = 1;
6658                         break;
6659                 case 'h':
6660                         human_readable = true;
6661                         break;
6662                 default:
6663                         fprintf(stderr, "%s quota: unrecognized option '%s'\n",
6664                                 progname, argv[optind - 1]);
6665                         return CMD_HELP;
6666                 }
6667         }
6668
6669         /* current uid/gid info for "lfs quota /path/to/lustre/mount" */
6670         if (qctl.qc_cmd == LUSTRE_Q_GETQUOTA && qctl.qc_type == ALLQUOTA &&
6671             optind == argc - 1 && !show_default) {
6672
6673                 qctl.qc_cmd = LUSTRE_Q_GETQUOTA;
6674                 qctl.qc_valid = valid;
6675                 qctl.qc_idx = idx;
6676
6677                 for (qtype = USRQUOTA; qtype <= GRPQUOTA; qtype++) {
6678                         qctl.qc_type = qtype;
6679                         if (qtype == USRQUOTA) {
6680                                 qctl.qc_id = geteuid();
6681                                 rc = uid2name(&name, qctl.qc_id);
6682                         } else {
6683                                 qctl.qc_id = getegid();
6684                                 rc = gid2name(&name, qctl.qc_id);
6685                         }
6686                         if (rc)
6687                                 name = "<unknown>";
6688                         mnt = argv[optind];
6689                         rc1 = get_print_quota(mnt, name, &qctl, verbose, quiet,
6690                                               human_readable, show_default);
6691                         if (rc1 && !rc)
6692                                 rc = rc1;
6693                 }
6694                 return rc;
6695         /* lfs quota -u username /path/to/lustre/mount */
6696         } else if (qctl.qc_cmd == LUSTRE_Q_GETQUOTA) {
6697                 /* options should be followed by u/g-name and mntpoint */
6698                 if ((!show_default && optind + 2 != argc) ||
6699                     (show_default && optind + 1 != argc) ||
6700                     qctl.qc_type == ALLQUOTA) {
6701                         fprintf(stderr,
6702                                 "%s quota: name and mount point must be specified\n",
6703                                 progname);
6704                         return CMD_HELP;
6705                 }
6706
6707                 if (!show_default) {
6708                         name = argv[optind++];
6709                         switch (qctl.qc_type) {
6710                         case USRQUOTA:
6711                                 rc = name2uid(&qctl.qc_id, name);
6712                                 break;
6713                         case GRPQUOTA:
6714                                 rc = name2gid(&qctl.qc_id, name);
6715                                 break;
6716                         case PRJQUOTA:
6717                                 rc = name2projid(&qctl.qc_id, name);
6718                                 break;
6719                         default:
6720                                 rc = -ENOTSUP;
6721                                 break;
6722                         }
6723                 } else {
6724                         qctl.qc_valid = QC_GENERAL;
6725                         qctl.qc_cmd = LUSTRE_Q_GETDEFAULT;
6726                         qctl.qc_id = 0;
6727                 }
6728
6729                 if (rc) {
6730                         qctl.qc_id = strtoul(name, &endptr, 10);
6731                         if (*endptr != '\0') {
6732                                 fprintf(stderr, "%s quota: invalid id '%s'\n",
6733                                         progname, name);
6734                                 return CMD_HELP;
6735                         }
6736                 }
6737         } else if (optind + 1 != argc || qctl.qc_type == ALLQUOTA) {
6738                 fprintf(stderr, "%s quota: missing quota info argument(s)\n",
6739                         progname);
6740                 return CMD_HELP;
6741         }
6742
6743         mnt = argv[optind];
6744         rc = get_print_quota(mnt, name, &qctl, verbose, quiet,
6745                              human_readable, show_default);
6746         return rc;
6747 }
6748 #endif /* HAVE_SYS_QUOTA_H! */
6749
6750 static int flushctx_ioctl(char *mp)
6751 {
6752         int fd, rc;
6753
6754         fd = open(mp, O_RDONLY);
6755         if (fd == -1) {
6756                 fprintf(stderr, "flushctx: error open %s: %s\n",
6757                         mp, strerror(errno));
6758                 return -1;
6759         }
6760
6761         rc = ioctl(fd, LL_IOC_FLUSHCTX);
6762         if (rc == -1)
6763                 fprintf(stderr, "flushctx: error ioctl %s: %s\n",
6764                         mp, strerror(errno));
6765
6766         close(fd);
6767         return rc;
6768 }
6769
6770 static int lfs_flushctx(int argc, char **argv)
6771 {
6772         int     kdestroy = 0, c;
6773         char    mntdir[PATH_MAX] = {'\0'};
6774         int     index = 0;
6775         int     rc = 0;
6776
6777         while ((c = getopt(argc, argv, "k")) != -1) {
6778                 switch (c) {
6779                 case 'k':
6780                         kdestroy = 1;
6781                         break;
6782                 default:
6783                         fprintf(stderr, "error: %s: option '-%c' "
6784                                         "unrecognized\n", argv[0], c);
6785                         return CMD_HELP;
6786                 }
6787         }
6788
6789         if (kdestroy) {
6790             if ((rc = system("kdestroy > /dev/null")) != 0) {
6791                 rc = WEXITSTATUS(rc);
6792                 fprintf(stderr, "error destroying tickets: %d, continuing\n", rc);
6793             }
6794         }
6795
6796         if (optind >= argc) {
6797                 /* flush for all mounted lustre fs. */
6798                 while (!llapi_search_mounts(NULL, index++, mntdir, NULL)) {
6799                         /* Check if we have a mount point */
6800                         if (mntdir[0] == '\0')
6801                                 continue;
6802
6803                         if (flushctx_ioctl(mntdir))
6804                                 rc = -1;
6805
6806                         mntdir[0] = '\0'; /* avoid matching in next loop */
6807                 }
6808         } else {
6809                 /* flush fs as specified */
6810                 while (optind < argc) {
6811                         if (flushctx_ioctl(argv[optind++]))
6812                                 rc = -1;
6813                 }
6814         }
6815         return rc;
6816 }
6817
6818 static int lfs_changelog(int argc, char **argv)
6819 {
6820         void *changelog_priv;
6821         struct changelog_rec *rec;
6822         long long startrec = 0, endrec = 0;
6823         char *mdd;
6824         struct option long_opts[] = {
6825                 { .val = 'f', .name = "follow", .has_arg = no_argument },
6826                 { .name = NULL } };
6827         char short_opts[] = "f";
6828         int rc, follow = 0;
6829
6830         while ((rc = getopt_long(argc, argv, short_opts,
6831                 long_opts, NULL)) != -1) {
6832                 switch (rc) {
6833                 case 'f':
6834                         follow++;
6835                         break;
6836                 default:
6837                         fprintf(stderr,
6838                                 "%s changelog: unrecognized option '%s'\n",
6839                                 progname, argv[optind - 1]);
6840                         return CMD_HELP;
6841                 }
6842         }
6843         if (optind >= argc) {
6844                 fprintf(stderr, "%s changelog: mdtname must be specified\n",
6845                         progname);
6846                 return CMD_HELP;
6847         }
6848
6849         mdd = argv[optind++];
6850         if (argc > optind)
6851                 startrec = strtoll(argv[optind++], NULL, 10);
6852         if (argc > optind)
6853                 endrec = strtoll(argv[optind++], NULL, 10);
6854
6855         rc = llapi_changelog_start(&changelog_priv,
6856                                    CHANGELOG_FLAG_BLOCK |
6857                                    CHANGELOG_FLAG_JOBID |
6858                                    CHANGELOG_FLAG_EXTRA_FLAGS |
6859                                    (follow ? CHANGELOG_FLAG_FOLLOW : 0),
6860                                    mdd, startrec);
6861         if (rc < 0) {
6862                 fprintf(stderr, "%s changelog: cannot start changelog: %s\n",
6863                         progname, strerror(errno = -rc));
6864                 return rc;
6865         }
6866
6867         rc = llapi_changelog_set_xflags(changelog_priv,
6868                                         CHANGELOG_EXTRA_FLAG_UIDGID |
6869                                         CHANGELOG_EXTRA_FLAG_NID |
6870                                         CHANGELOG_EXTRA_FLAG_OMODE |
6871                                         CHANGELOG_EXTRA_FLAG_XATTR);
6872         if (rc < 0) {
6873                 fprintf(stderr,
6874                         "%s changelog: cannot set xflags for changelog: %s\n",
6875                         progname, strerror(errno = -rc));
6876                 return rc;
6877         }
6878
6879         while ((rc = llapi_changelog_recv(changelog_priv, &rec)) == 0) {
6880                 time_t secs;
6881                 struct tm ts;
6882
6883                 if (endrec && rec->cr_index > endrec) {
6884                         llapi_changelog_free(&rec);
6885                         break;
6886                 }
6887                 if (rec->cr_index < startrec) {
6888                         llapi_changelog_free(&rec);
6889                         continue;
6890                 }
6891
6892                 secs = rec->cr_time >> 30;
6893                 gmtime_r(&secs, &ts);
6894                 printf("%ju %02d%-5s %02d:%02d:%02d.%09d %04d.%02d.%02d "
6895                        "0x%x t="DFID, (uintmax_t)rec->cr_index, rec->cr_type,
6896                        changelog_type2str(rec->cr_type),
6897                        ts.tm_hour, ts.tm_min, ts.tm_sec,
6898                        (int)(rec->cr_time & ((1 << 30) - 1)),
6899                        ts.tm_year + 1900, ts.tm_mon + 1, ts.tm_mday,
6900                        rec->cr_flags & CLF_FLAGMASK, PFID(&rec->cr_tfid));
6901
6902                 if (rec->cr_flags & CLF_JOBID) {
6903                         struct changelog_ext_jobid *jid =
6904                                 changelog_rec_jobid(rec);
6905
6906                         if (jid->cr_jobid[0] != '\0')
6907                                 printf(" j=%s", jid->cr_jobid);
6908                 }
6909
6910                 if (rec->cr_flags & CLF_EXTRA_FLAGS) {
6911                         struct changelog_ext_extra_flags *ef =
6912                                 changelog_rec_extra_flags(rec);
6913
6914                         printf(" ef=0x%llx",
6915                                (unsigned long long)ef->cr_extra_flags);
6916
6917                         if (ef->cr_extra_flags & CLFE_UIDGID) {
6918                                 struct changelog_ext_uidgid *uidgid =
6919                                         changelog_rec_uidgid(rec);
6920
6921                                 printf(" u=%llu:%llu",
6922                                        (unsigned long long)uidgid->cr_uid,
6923                                        (unsigned long long)uidgid->cr_gid);
6924                         }
6925                         if (ef->cr_extra_flags & CLFE_NID) {
6926                                 struct changelog_ext_nid *nid =
6927                                         changelog_rec_nid(rec);
6928
6929                                 printf(" nid=%s",
6930                                        libcfs_nid2str(nid->cr_nid));
6931                         }
6932
6933                         if (ef->cr_extra_flags & CLFE_OPEN) {
6934                                 struct changelog_ext_openmode *omd =
6935                                         changelog_rec_openmode(rec);
6936                                 char mode[] = "---";
6937
6938                                 /* exec mode must be exclusive */
6939                                 if (omd->cr_openflags & MDS_FMODE_EXEC) {
6940                                         mode[2] = 'x';
6941                                 } else {
6942                                         if (omd->cr_openflags & MDS_FMODE_READ)
6943                                                 mode[0] = 'r';
6944                                         if (omd->cr_openflags &
6945                                             (MDS_FMODE_WRITE |
6946                                              MDS_OPEN_TRUNC |
6947                                              MDS_OPEN_APPEND))
6948                                                 mode[1] = 'w';
6949                                 }
6950
6951                                 if (strcmp(mode, "---") != 0)
6952                                         printf(" m=%s", mode);
6953
6954                         }
6955
6956                         if (ef->cr_extra_flags & CLFE_XATTR) {
6957                                 struct changelog_ext_xattr *xattr =
6958                                         changelog_rec_xattr(rec);
6959
6960                                 if (xattr->cr_xattr[0] != '\0')
6961                                         printf(" x=%s", xattr->cr_xattr);
6962                         }
6963                 }
6964
6965                 if (rec->cr_namelen)
6966                         printf(" p="DFID" %.*s", PFID(&rec->cr_pfid),
6967                                rec->cr_namelen, changelog_rec_name(rec));
6968
6969                 if (rec->cr_flags & CLF_RENAME) {
6970                         struct changelog_ext_rename *rnm =
6971                                 changelog_rec_rename(rec);
6972
6973                         if (!fid_is_zero(&rnm->cr_sfid))
6974                                 printf(" s="DFID" sp="DFID" %.*s",
6975                                        PFID(&rnm->cr_sfid),
6976                                        PFID(&rnm->cr_spfid),
6977                                        (int)changelog_rec_snamelen(rec),
6978                                        changelog_rec_sname(rec));
6979                 }
6980                 printf("\n");
6981
6982                 llapi_changelog_free(&rec);
6983         }
6984
6985         llapi_changelog_fini(&changelog_priv);
6986
6987         if (rc < 0)
6988                 fprintf(stderr, "%s changelog: cannot access changelog: %s\n",
6989                         progname, strerror(errno = -rc));
6990
6991         return (rc == 1 ? 0 : rc);
6992 }
6993
6994 static int lfs_changelog_clear(int argc, char **argv)
6995 {
6996         long long endrec;
6997         int rc;
6998
6999         if (argc != 4)
7000                 return CMD_HELP;
7001
7002         endrec = strtoll(argv[3], NULL, 10);
7003
7004         rc = llapi_changelog_clear(argv[1], argv[2], endrec);
7005
7006         if (rc == -EINVAL)
7007                 fprintf(stderr, "%s: record out of range: %llu\n",
7008                         argv[0], endrec);
7009         else if (rc == -ENOENT)
7010                 fprintf(stderr, "%s: no changelog user: %s\n",
7011                         argv[0], argv[2]);
7012         else if (rc)
7013                 fprintf(stderr, "%s error: %s\n", argv[0],
7014                         strerror(-rc));
7015
7016         if (rc)
7017                 errno = -rc;
7018
7019         return rc;
7020 }
7021
7022 static int lfs_fid2path(int argc, char **argv)
7023 {
7024         struct option long_opts[] = {
7025                 { .val = 'c',   .name = "cur",  .has_arg = no_argument },
7026                 { .val = 'l',   .name = "link", .has_arg = required_argument },
7027                 { .val = 'r',   .name = "rec",  .has_arg = required_argument },
7028                 { .name = NULL } };
7029         char  short_opts[] = "cl:r:";
7030         char *device, *fid, *path;
7031         long long recno = -1;
7032         int linkno = -1;
7033         int lnktmp;
7034         int printcur = 0;
7035         int rc = 0;
7036         char *endptr = NULL;
7037
7038         while ((rc = getopt_long(argc, argv, short_opts,
7039                 long_opts, NULL)) != -1) {
7040                 switch (rc) {
7041                 case 'c':
7042                         printcur++;
7043                         break;
7044                 case 'l':
7045                         linkno = strtol(optarg, &endptr, 10);
7046                         if (*endptr != '\0') {
7047                                 fprintf(stderr,
7048                                         "%s fid2path: invalid linkno '%s'\n",
7049                                         progname, optarg);
7050                                 return CMD_HELP;
7051                         }
7052                         break;
7053                 case 'r':
7054                         recno = strtoll(optarg, &endptr, 10);
7055                         if (*endptr != '\0') {
7056                                 fprintf(stderr,
7057                                         "%s fid2path: invalid recno '%s'\n",
7058                                         progname, optarg);
7059                                 return CMD_HELP;
7060                         }
7061                         break;
7062                 default:
7063                         fprintf(stderr,
7064                                 "%s fid2path: unrecognized option '%s'\n",
7065                                 progname, argv[optind - 1]);
7066                         return CMD_HELP;
7067                 }
7068         }
7069
7070         if (argc < 3) {
7071                 fprintf(stderr,
7072                         "%s fid2path: <fsname|rootpath> and <fid>... must be specified\n",
7073                         progname);
7074                 return CMD_HELP;
7075         }
7076
7077         device = argv[optind++];
7078         path = calloc(1, PATH_MAX);
7079         if (path == NULL) {
7080                 rc = -errno;
7081                 fprintf(stderr,
7082                         "%s fid2path: cannot allocate memory for path: %s\n",
7083                         progname, strerror(-rc));
7084                 return rc;
7085         }
7086
7087         rc = 0;
7088         while (optind < argc) {
7089                 fid = argv[optind++];
7090
7091                 lnktmp = (linkno >= 0) ? linkno : 0;
7092                 while (1) {
7093                         int oldtmp = lnktmp;
7094                         long long rectmp = recno;
7095                         int rc2;
7096                         rc2 = llapi_fid2path(device, fid, path, PATH_MAX,
7097                                              &rectmp, &lnktmp);
7098                         if (rc2 < 0) {
7099                                 fprintf(stderr,
7100                                         "%s fid2path: cannot find '%s': %s\n",
7101                                         progname, fid, strerror(errno = -rc2));
7102                                 if (rc == 0)
7103                                         rc = rc2;
7104                                 break;
7105                         }
7106
7107                         if (printcur)
7108                                 fprintf(stdout, "%lld ", rectmp);
7109                         if (device[0] == '/') {
7110                                 fprintf(stdout, "%s", device);
7111                                 if (device[strlen(device) - 1] != '/')
7112                                         fprintf(stdout, "/");
7113                         } else if (path[0] == '\0') {
7114                                 fprintf(stdout, "/");
7115                         }
7116                         fprintf(stdout, "%s\n", path);
7117
7118                         if (linkno >= 0)
7119                                 /* specified linkno */
7120                                 break;
7121                         if (oldtmp == lnktmp)
7122                                 /* no more links */
7123                                 break;
7124                 }
7125         }
7126
7127         free(path);
7128         return rc;
7129 }
7130
7131 static int lfs_path2fid(int argc, char **argv)
7132 {
7133         struct option long_opts[] = {
7134                 { .val = 'p', .name = "parents", .has_arg = no_argument },
7135                 { .name = NULL } };
7136         char            **path;
7137         const char        short_opts[] = "p";
7138         const char       *sep = "";
7139         struct lu_fid     fid;
7140         int               rc = 0;
7141         bool              show_parents = false;
7142
7143         while ((rc = getopt_long(argc, argv, short_opts,
7144                                  long_opts, NULL)) != -1) {
7145                 switch (rc) {
7146                 case 'p':
7147                         show_parents = true;
7148                         break;
7149                 default:
7150                         fprintf(stderr,
7151                                 "%s path2fid: unrecognized option '%s'\n",
7152                                 progname, argv[optind - 1]);
7153                         return CMD_HELP;
7154                 }
7155         }
7156
7157         if (optind > argc - 1) {
7158                 fprintf(stderr, "%s path2fid: FILE... must be specified\n",
7159                         progname);
7160                 return CMD_HELP;
7161         }
7162         else if (optind < argc - 1)
7163                 sep = ": ";
7164
7165         rc = 0;
7166         for (path = argv + optind; *path != NULL; path++) {
7167                 int err = 0;
7168                 if (!show_parents) {
7169                         err = llapi_path2fid(*path, &fid);
7170                         if (!err)
7171                                 printf("%s%s"DFID"\n",
7172                                        *sep != '\0' ? *path : "", sep,
7173                                        PFID(&fid));
7174                 } else {
7175                         char            name[NAME_MAX + 1];
7176                         unsigned int    linkno = 0;
7177
7178                         while ((err = llapi_path2parent(*path, linkno, &fid,
7179                                                 name, sizeof(name))) == 0) {
7180                                 if (*sep != '\0' && linkno == 0)
7181                                         printf("%s%s", *path, sep);
7182
7183                                 printf("%s"DFID"/%s", linkno != 0 ? "\t" : "",
7184                                        PFID(&fid), name);
7185                                 linkno++;
7186                         }
7187
7188                         /* err == -ENODATA is end-of-loop */
7189                         if (linkno > 0 && err == -ENODATA) {
7190                                 printf("\n");
7191                                 err = 0;
7192                         }
7193                 }
7194
7195                 if (err) {
7196                         fprintf(stderr,
7197                                 "%s path2fid: cannot get %sfid for '%s': %s\n",
7198                                 progname, show_parents ? "parent " : "", *path,
7199                                 strerror(-err));
7200                         if (rc == 0) {
7201                                 rc = err;
7202                                 errno = -err;
7203                         }
7204                 }
7205         }
7206
7207         return rc;
7208 }
7209
7210 #define MAX_ERRNO       4095
7211 #define IS_ERR_VALUE(x) ((unsigned long)(x) >= (unsigned long)-MAX_ERRNO)
7212
7213 static int lfs_rmfid_and_show_errors(const char *device, struct fid_array *fa)
7214 {
7215         int rc, rc2 = 0, k;
7216
7217         rc = llapi_rmfid(device, fa);
7218         if (rc) {
7219                 fprintf(stderr, "rmfid(): rc = %d\n", rc);
7220                 return rc;
7221         }
7222
7223         for (k = 0; k < fa->fa_nr; k++) {
7224                 rc = (__s32)fa->fa_fids[k].f_ver;
7225                 if (!IS_ERR_VALUE(rc))
7226                         continue;
7227                 if (!rc2 && rc)
7228                         rc2 = rc;
7229                 if (!rc)
7230                         continue;
7231                 fa->fa_fids[k].f_ver = 0;
7232                 fprintf(stderr, "rmfid("DFID"): rc = %d\n",
7233                         PFID(&fa->fa_fids[k]), rc);
7234         }
7235
7236         return rc2;
7237 }
7238
7239 static int lfs_rmfid(int argc, char **argv)
7240 {
7241         char *fidstr, *device;
7242         int rc = 0, rc2, nr;
7243         struct fid_array *fa;
7244
7245         if (optind > argc - 1) {
7246                 fprintf(stderr, "%s rmfid: missing dirname\n", progname);
7247                 return CMD_HELP;
7248         }
7249
7250         device = argv[optind++];
7251
7252         nr = argc - optind;
7253         fa = malloc(offsetof(struct fid_array, fa_fids[nr + 1]));
7254         if (fa == NULL)
7255                 return -ENOMEM;
7256
7257         fa->fa_nr = 0;
7258         rc = 0;
7259         while (optind < argc) {
7260                 int found;
7261
7262                 fidstr = argv[optind++];
7263                 while (*fidstr == '[')
7264                         fidstr++;
7265                 found = sscanf(fidstr, SFID, RFID(&fa->fa_fids[fa->fa_nr]));
7266                 if (found != 3) {
7267                         fprintf(stderr, "unrecognized FID: %s\n",
7268                                 argv[optind - 1]);
7269                         exit(1);
7270                 }
7271                 fa->fa_nr++;
7272                 if (fa->fa_nr == OBD_MAX_FIDS_IN_ARRAY) {
7273                         /* start another batch */
7274                         rc2 = lfs_rmfid_and_show_errors(device, fa);
7275                         if (rc2 && !rc)
7276                                 rc = rc2;
7277                         fa->fa_nr = 0;
7278                 }
7279         }
7280         if (fa->fa_nr) {
7281                 rc2 = lfs_rmfid_and_show_errors(device, fa);
7282                 if (rc2 && !rc)
7283                         rc = rc2;
7284         }
7285
7286         return rc;
7287 }
7288
7289 static int lfs_data_version(int argc, char **argv)
7290 {
7291         char *path;
7292         __u64 data_version;
7293         int fd;
7294         int rc;
7295         int c;
7296         int data_version_flags = LL_DV_RD_FLUSH; /* Read by default */
7297
7298         if (argc < 2) {
7299                 fprintf(stderr, "%s data_version: FILE must be specified\n",
7300                         progname);
7301                 return CMD_HELP;
7302         }
7303
7304         while ((c = getopt(argc, argv, "nrw")) != -1) {
7305                 switch (c) {
7306                 case 'n':
7307                         data_version_flags = 0;
7308                         break;
7309                 case 'r':
7310                         data_version_flags |= LL_DV_RD_FLUSH;
7311                         break;
7312                 case 'w':
7313                         data_version_flags |= LL_DV_WR_FLUSH;
7314                         break;
7315                 default:
7316                         fprintf(stderr,
7317                                 "%s data_version: unrecognized option '%s'\n",
7318                                 progname, argv[optind - 1]);
7319                         return CMD_HELP;
7320                 }
7321         }
7322         if (optind == argc) {
7323                 fprintf(stderr, "%s data_version: FILE must be specified\n",
7324                         progname);
7325                 return CMD_HELP;
7326         }
7327
7328         path = argv[optind];
7329         fd = open(path, O_RDONLY);
7330         if (fd < 0) {
7331                 rc = -errno;
7332                 fprintf(stderr, "%s data_version: cannot open file '%s': %s\n",
7333                         progname, path, strerror(-rc));
7334                 return rc;
7335         }
7336
7337         rc = llapi_get_data_version(fd, &data_version, data_version_flags);
7338         if (rc < 0)
7339                 fprintf(stderr,
7340                         "%s data_version: cannot get version for '%s': %s\n",
7341                         progname, path, strerror(-rc));
7342         else
7343                 printf("%ju" "\n", (uintmax_t)data_version);
7344
7345         close(fd);
7346         return rc;
7347 }
7348
7349 static int lfs_hsm_state(int argc, char **argv)
7350 {
7351         int rc;
7352         int i = 1;
7353         char *path;
7354         struct hsm_user_state hus;
7355
7356         if (argc < 2)
7357                 return CMD_HELP;
7358
7359         do {
7360                 path = argv[i];
7361
7362                 rc = llapi_hsm_state_get(path, &hus);
7363                 if (rc) {
7364                         fprintf(stderr, "can't get hsm state for %s: %s\n",
7365                                 path, strerror(errno = -rc));
7366                         return rc;
7367                 }
7368
7369                 /* Display path name and status flags */
7370                 printf("%s: (0x%08x)", path, hus.hus_states);
7371
7372                 if (hus.hus_states & HS_RELEASED)
7373                         printf(" released");
7374                 if (hus.hus_states & HS_EXISTS)
7375                         printf(" exists");
7376                 if (hus.hus_states & HS_DIRTY)
7377                         printf(" dirty");
7378                 if (hus.hus_states & HS_ARCHIVED)
7379                         printf(" archived");
7380                 /* Display user-settable flags */
7381                 if (hus.hus_states & HS_NORELEASE)
7382                         printf(" never_release");
7383                 if (hus.hus_states & HS_NOARCHIVE)
7384                         printf(" never_archive");
7385                 if (hus.hus_states & HS_LOST)
7386                         printf(" lost_from_hsm");
7387
7388                 if (hus.hus_archive_id != 0)
7389                         printf(", archive_id:%d", hus.hus_archive_id);
7390                 printf("\n");
7391
7392         } while (++i < argc);
7393
7394         return 0;
7395 }
7396
7397 #define LFS_HSM_SET   0
7398 #define LFS_HSM_CLEAR 1
7399
7400 /**
7401  * Generic function to set or clear HSM flags.
7402  * Used by hsm_set and hsm_clear.
7403  *
7404  * @mode  if LFS_HSM_SET, set the flags, if LFS_HSM_CLEAR, clear the flags.
7405  */
7406 static int lfs_hsm_change_flags(int argc, char **argv, int mode)
7407 {
7408         struct option long_opts[] = {
7409         { .val = 'A',   .name = "archived",     .has_arg = no_argument },
7410         { .val = 'a',   .name = "noarchive",    .has_arg = no_argument },
7411         { .val = 'd',   .name = "dirty",        .has_arg = no_argument },
7412         { .val = 'e',   .name = "exists",       .has_arg = no_argument },
7413         { .val = 'l',   .name = "lost",         .has_arg = no_argument },
7414         { .val = 'r',   .name = "norelease",    .has_arg = no_argument },
7415         { .val = 'i',   .name = "archive-id",   .has_arg = required_argument },
7416         { .name = NULL } };
7417         char short_opts[] = "lraAdei:";
7418         __u64 mask = 0;
7419         int c, rc;
7420         char *path;
7421         __u32 archive_id = 0;
7422         char *end = NULL;
7423
7424         if (argc < 3)
7425                 return CMD_HELP;
7426
7427         while ((c = getopt_long(argc, argv, short_opts,
7428                                 long_opts, NULL)) != -1) {
7429                 switch (c) {
7430                 case 'l':
7431                         mask |= HS_LOST;
7432                         break;
7433                 case 'a':
7434                         mask |= HS_NOARCHIVE;
7435                         break;
7436                 case 'A':
7437                         mask |= HS_ARCHIVED;
7438                         break;
7439                 case 'r':
7440                         mask |= HS_NORELEASE;
7441                         break;
7442                 case 'd':
7443                         mask |= HS_DIRTY;
7444                         break;
7445                 case 'e':
7446                         mask |= HS_EXISTS;
7447                         break;
7448                 case 'i':
7449                         archive_id = strtol(optarg, &end, 10);
7450                         if (*end != '\0') {
7451                                 fprintf(stderr, "invalid archive_id: '%s'\n",
7452                                         end);
7453                                 return CMD_HELP;
7454                         }
7455                         break;
7456                 case '?':
7457                         return CMD_HELP;
7458                 default:
7459                         fprintf(stderr, "error: %s: option '%s' unrecognized\n",
7460                                 argv[0], argv[optind - 1]);
7461                         return CMD_HELP;
7462                 }
7463         }
7464
7465         /* User should have specified a flag */
7466         if (mask == 0)
7467                 return CMD_HELP;
7468
7469         while (optind < argc) {
7470
7471                 path = argv[optind];
7472
7473                 /* If mode == 0, this means we apply the mask. */
7474                 if (mode == LFS_HSM_SET)
7475                         rc = llapi_hsm_state_set(path, mask, 0, archive_id);
7476                 else
7477                         rc = llapi_hsm_state_set(path, 0, mask, 0);
7478
7479                 if (rc != 0) {
7480                         fprintf(stderr, "Can't change hsm flags for %s: %s\n",
7481                                 path, strerror(errno = -rc));
7482                         return rc;
7483                 }
7484                 optind++;
7485         }
7486
7487         return 0;
7488 }
7489
7490 static int lfs_hsm_action(int argc, char **argv)
7491 {
7492         int                              rc;
7493         int                              i = 1;
7494         char                            *path;
7495         struct hsm_current_action        hca;
7496         struct hsm_extent                he;
7497         enum hsm_user_action             hua;
7498         enum hsm_progress_states         hps;
7499
7500         if (argc < 2)
7501                 return CMD_HELP;
7502
7503         do {
7504                 path = argv[i];
7505
7506                 rc = llapi_hsm_current_action(path, &hca);
7507                 if (rc) {
7508                         fprintf(stderr, "can't get hsm action for %s: %s\n",
7509                                 path, strerror(errno = -rc));
7510                         return rc;
7511                 }
7512                 he = hca.hca_location;
7513                 hua = hca.hca_action;
7514                 hps = hca.hca_state;
7515
7516                 printf("%s: %s", path, hsm_user_action2name(hua));
7517
7518                 /* Skip file without action */
7519                 if (hca.hca_action == HUA_NONE) {
7520                         printf("\n");
7521                         continue;
7522                 }
7523
7524                 printf(" %s ", hsm_progress_state2name(hps));
7525
7526                 if ((hps == HPS_RUNNING) &&
7527                     (hua == HUA_ARCHIVE || hua == HUA_RESTORE))
7528                         printf("(%llu bytes moved)\n",
7529                                (unsigned long long)he.length);
7530                 else if ((he.offset + he.length) == LUSTRE_EOF)
7531                         printf("(from %llu to EOF)\n",
7532                                (unsigned long long)he.offset);
7533                 else
7534                         printf("(from %llu to %llu)\n",
7535                                (unsigned long long)he.offset,
7536                                (unsigned long long)(he.offset + he.length));
7537
7538         } while (++i < argc);
7539
7540         return 0;
7541 }
7542
7543 static int lfs_hsm_set(int argc, char **argv)
7544 {
7545         return lfs_hsm_change_flags(argc, argv, LFS_HSM_SET);
7546 }
7547
7548 static int lfs_hsm_clear(int argc, char **argv)
7549 {
7550         return lfs_hsm_change_flags(argc, argv, LFS_HSM_CLEAR);
7551 }
7552
7553 /**
7554  * Check file state and return its fid, to be used by lfs_hsm_request().
7555  *
7556  * \param[in]     file      Path to file to check
7557  * \param[in,out] fid       Pointer to allocated lu_fid struct.
7558  * \param[in,out] last_dev  Pointer to last device id used.
7559  *
7560  * \return 0 on success.
7561  */
7562 static int lfs_hsm_prepare_file(const char *file, struct lu_fid *fid,
7563                                 dev_t *last_dev)
7564 {
7565         struct stat     st;
7566         int             rc;
7567
7568         rc = lstat(file, &st);
7569         if (rc) {
7570                 fprintf(stderr, "Cannot stat %s: %s\n", file, strerror(errno));
7571                 return -errno;
7572         }
7573         /* Checking for regular file as archiving as posix copytool
7574          * rejects archiving files other than regular files
7575          */
7576         if (!S_ISREG(st.st_mode)) {
7577                 fprintf(stderr, "error: \"%s\" is not a regular file\n", file);
7578                 return CMD_HELP;
7579         }
7580         /* A request should be ... */
7581         if (*last_dev != st.st_dev && *last_dev != 0) {
7582                 fprintf(stderr, "All files should be "
7583                         "on the same filesystem: %s\n", file);
7584                 return -EINVAL;
7585         }
7586         *last_dev = st.st_dev;
7587
7588         rc = llapi_path2fid(file, fid);
7589         if (rc) {
7590                 fprintf(stderr, "Cannot read FID of %s: %s\n",
7591                         file, strerror(-rc));
7592                 return rc;
7593         }
7594         return 0;
7595 }
7596
7597 /* Fill an HSM HUR item with a given file name.
7598  *
7599  * If mntpath is set, then the filename is actually a FID, and no
7600  * lookup on the filesystem will be performed.
7601  *
7602  * \param[in]  hur         the user request to fill
7603  * \param[in]  idx         index of the item inside the HUR to fill
7604  * \param[in]  mntpath     mountpoint of Lustre
7605  * \param[in]  fname       filename (if mtnpath is NULL)
7606  *                         or FID (if mntpath is set)
7607  * \param[in]  last_dev    pointer to last device id used
7608  *
7609  * \retval 0 on success
7610  * \retval CMD_HELP or a negative errno on error
7611  */
7612 static int fill_hur_item(struct hsm_user_request *hur, unsigned int idx,
7613                          const char *mntpath, const char *fname,
7614                          dev_t *last_dev)
7615 {
7616         struct hsm_user_item *hui = &hur->hur_user_item[idx];
7617         int rc;
7618
7619         hui->hui_extent.length = -1;
7620
7621         if (mntpath != NULL) {
7622                 if (*fname == '[')
7623                         fname++;
7624                 rc = sscanf(fname, SFID, RFID(&hui->hui_fid));
7625                 if (rc == 3) {
7626                         rc = 0;
7627                 } else {
7628                         fprintf(stderr, "hsm: '%s' is not a valid FID\n",
7629                                 fname);
7630                         rc = -EINVAL;
7631                 }
7632         } else {
7633                 rc = lfs_hsm_prepare_file(fname, &hui->hui_fid, last_dev);
7634         }
7635
7636         if (rc == 0)
7637                 hur->hur_request.hr_itemcount++;
7638
7639         return rc;
7640 }
7641
7642 static int lfs_hsm_request(int argc, char **argv, int action)
7643 {
7644         struct option long_opts[] = {
7645         { .val = 'a',   .name = "archive",      .has_arg = required_argument },
7646         { .val = 'D',   .name = "data",         .has_arg = required_argument },
7647         { .val = 'l',   .name = "filelist",     .has_arg = required_argument },
7648         { .val = 'm',   .name = "mntpath",      .has_arg = required_argument },
7649         { .name = NULL } };
7650         dev_t                    last_dev = 0;
7651         char                     short_opts[] = "l:D:a:m:";
7652         struct hsm_user_request *hur, *oldhur;
7653         int                      c, i;
7654         size_t                   len;
7655         int                      nbfile;
7656         char                    *line = NULL;
7657         char                    *filelist = NULL;
7658         char                     fullpath[PATH_MAX];
7659         char                    *opaque = NULL;
7660         int                      opaque_len = 0;
7661         int                      archive_id = 0;
7662         FILE                    *fp;
7663         int                      nbfile_alloc = 0;
7664         char                    *some_file = NULL;
7665         char                    *mntpath = NULL;
7666         int                      rc;
7667
7668         if (argc < 2)
7669                 return CMD_HELP;
7670
7671         while ((c = getopt_long(argc, argv, short_opts,
7672                                 long_opts, NULL)) != -1) {
7673                 switch (c) {
7674                 case 'l':
7675                         filelist = optarg;
7676                         break;
7677                 case 'D':
7678                         opaque = optarg;
7679                         break;
7680                 case 'a':
7681                         if (action != HUA_ARCHIVE &&
7682                             action != HUA_REMOVE) {
7683                                 fprintf(stderr,
7684                                         "error: -a is supported only "
7685                                         "when archiving or removing\n");
7686                                 return CMD_HELP;
7687                         }
7688                         archive_id = atoi(optarg);
7689                         break;
7690                 case 'm':
7691                         if (some_file == NULL) {
7692                                 mntpath = optarg;
7693                                 some_file = strdup(optarg);
7694                         }
7695                         break;
7696                 case '?':
7697                         return CMD_HELP;
7698                 default:
7699                         fprintf(stderr, "error: %s: option '%s' unrecognized\n",
7700                                 argv[0], argv[optind - 1]);
7701                         return CMD_HELP;
7702                 }
7703         }
7704
7705         /* All remaining args are files, so we have at least nbfile */
7706         nbfile = argc - optind;
7707
7708         if ((nbfile == 0) && (filelist == NULL))
7709                 return CMD_HELP;
7710
7711         if (opaque != NULL)
7712                 opaque_len = strlen(opaque);
7713
7714         /* Alloc the request structure with enough place to store all files
7715          * from command line. */
7716         hur = llapi_hsm_user_request_alloc(nbfile, opaque_len);
7717         if (hur == NULL) {
7718                 fprintf(stderr, "Cannot create the request: %s\n",
7719                         strerror(errno));
7720                 return errno;
7721         }
7722         nbfile_alloc = nbfile;
7723
7724         hur->hur_request.hr_action = action;
7725         hur->hur_request.hr_archive_id = archive_id;
7726         hur->hur_request.hr_flags = 0;
7727
7728         /* All remaining args are files, add them */
7729         if (nbfile != 0 && some_file == NULL)
7730                 some_file = strdup(argv[optind]);
7731
7732         for (i = 0; i < nbfile; i++) {
7733                 rc = fill_hur_item(hur, i, mntpath, argv[optind + i],
7734                                    &last_dev);
7735                 if (rc)
7736                         goto out_free;
7737         }
7738
7739         /* from here stop using nb_file, use hur->hur_request.hr_itemcount */
7740
7741         /* If a filelist was specified, read the filelist from it. */
7742         if (filelist != NULL) {
7743                 fp = fopen(filelist, "r");
7744                 if (fp == NULL) {
7745                         fprintf(stderr, "Cannot read the file list %s: %s\n",
7746                                 filelist, strerror(errno));
7747                         rc = -errno;
7748                         goto out_free;
7749                 }
7750
7751                 while ((rc = getline(&line, &len, fp)) != -1) {
7752                         /* If allocated buffer was too small, get something
7753                          * larger */
7754                         if (nbfile_alloc <= hur->hur_request.hr_itemcount) {
7755                                 ssize_t size;
7756
7757                                 nbfile_alloc = nbfile_alloc * 2 + 1;
7758                                 oldhur = hur;
7759                                 hur = llapi_hsm_user_request_alloc(nbfile_alloc,
7760                                                                    opaque_len);
7761                                 if (hur == NULL) {
7762                                         fprintf(stderr, "hsm: cannot allocate "
7763                                                 "the request: %s\n",
7764                                                 strerror(errno));
7765                                         hur = oldhur;
7766                                         rc = -errno;
7767                                         fclose(fp);
7768                                         goto out_free;
7769                                 }
7770                                 size = hur_len(oldhur);
7771                                 if (size < 0) {
7772                                         fprintf(stderr, "hsm: cannot allocate "
7773                                                 "%u files + %u bytes data\n",
7774                                             oldhur->hur_request.hr_itemcount,
7775                                             oldhur->hur_request.hr_data_len);
7776                                         free(hur);
7777                                         hur = oldhur;
7778                                         rc = -E2BIG;
7779                                         fclose(fp);
7780                                         goto out_free;
7781                                 }
7782                                 memcpy(hur, oldhur, size);
7783                                 free(oldhur);
7784                         }
7785
7786                         /* Chop CR */
7787                         if (line[strlen(line) - 1] == '\n')
7788                                 line[strlen(line) - 1] = '\0';
7789
7790                         rc = fill_hur_item(hur, hur->hur_request.hr_itemcount,
7791                                            mntpath, line, &last_dev);
7792                         if (rc) {
7793                                 fclose(fp);
7794                                 goto out_free;
7795                         }
7796
7797                         if (some_file == NULL) {
7798                                 some_file = line;
7799                                 line = NULL;
7800                         }
7801                 }
7802
7803                 rc = fclose(fp);
7804                 free(line);
7805         }
7806
7807         /* If a --data was used, add it to the request */
7808         hur->hur_request.hr_data_len = opaque_len;
7809         if (opaque != NULL)
7810                 memcpy(hur_data(hur), opaque, opaque_len);
7811
7812         /* Send the HSM request */
7813         if (realpath(some_file, fullpath) == NULL) {
7814                 fprintf(stderr, "Could not find path '%s': %s\n",
7815                         some_file, strerror(errno));
7816         }
7817         rc = llapi_hsm_request(fullpath, hur);
7818         if (rc) {
7819                 fprintf(stderr, "Cannot send HSM request (use of %s): %s\n",
7820                         some_file, strerror(-rc));
7821                 goto out_free;
7822         }
7823
7824 out_free:
7825         free(some_file);
7826         free(hur);
7827         return rc;
7828 }
7829
7830 static int lfs_hsm_archive(int argc, char **argv)
7831 {
7832         return lfs_hsm_request(argc, argv, HUA_ARCHIVE);
7833 }
7834
7835 static int lfs_hsm_restore(int argc, char **argv)
7836 {
7837         return lfs_hsm_request(argc, argv, HUA_RESTORE);
7838 }
7839
7840 static int lfs_hsm_release(int argc, char **argv)
7841 {
7842         return lfs_hsm_request(argc, argv, HUA_RELEASE);
7843 }
7844
7845 static int lfs_hsm_remove(int argc, char **argv)
7846 {
7847         return lfs_hsm_request(argc, argv, HUA_REMOVE);
7848 }
7849
7850 static int lfs_hsm_cancel(int argc, char **argv)
7851 {
7852         return lfs_hsm_request(argc, argv, HUA_CANCEL);
7853 }
7854
7855 static int lfs_swap_layouts(int argc, char **argv)
7856 {
7857         if (argc != 3)
7858                 return CMD_HELP;
7859
7860         return llapi_swap_layouts(argv[1], argv[2], 0, 0,
7861                                   SWAP_LAYOUTS_KEEP_MTIME |
7862                                   SWAP_LAYOUTS_KEEP_ATIME);
7863 }
7864
7865 static const char *const ladvise_names[] = LU_LADVISE_NAMES;
7866
7867 static const char *const lock_mode_names[] = LOCK_MODE_NAMES;
7868
7869 int lfs_get_mode(const char *string)
7870 {
7871         enum lock_mode_user mode;
7872
7873         for (mode = 0; mode < ARRAY_SIZE(lock_mode_names); mode++) {
7874                 if (lock_mode_names[mode] == NULL)
7875                         continue;
7876                 if (strcmp(string, lock_mode_names[mode]) == 0)
7877                         return mode;
7878         }
7879
7880         return -EINVAL;
7881 }
7882
7883 static enum lu_ladvise_type lfs_get_ladvice(const char *string)
7884 {
7885         enum lu_ladvise_type advice;
7886
7887         for (advice = 0;
7888              advice < ARRAY_SIZE(ladvise_names); advice++) {
7889                 if (ladvise_names[advice] == NULL)
7890                         continue;
7891                 if (strcmp(string, ladvise_names[advice]) == 0)
7892                         return advice;
7893         }
7894
7895         return LU_LADVISE_INVALID;
7896 }
7897
7898 static int lfs_ladvise(int argc, char **argv)
7899 {
7900         struct option long_opts[] = {
7901         { .val = 'a',   .name = "advice",       .has_arg = required_argument },
7902         { .val = 'b',   .name = "background",   .has_arg = no_argument },
7903         { .val = 'e',   .name = "end",          .has_arg = required_argument },
7904         { .val = 'l',   .name = "length",       .has_arg = required_argument },
7905         { .val = 'm',   .name = "mode",         .has_arg = required_argument },
7906         { .val = 's',   .name = "start",        .has_arg = required_argument },
7907         { .val = 'u',   .name = "unset",        .has_arg = no_argument },
7908         { .name = NULL } };
7909         char                     short_opts[] = "a:be:l:m:s:u";
7910         int                      c;
7911         int                      rc = 0;
7912         const char              *path;
7913         int                      fd;
7914         struct llapi_lu_ladvise  advice;
7915         enum lu_ladvise_type     advice_type = LU_LADVISE_INVALID;
7916         unsigned long long       start = 0;
7917         unsigned long long       end = LUSTRE_EOF;
7918         unsigned long long       length = 0;
7919         unsigned long long       size_units;
7920         unsigned long long       flags = 0;
7921         int                      mode = 0;
7922
7923         optind = 0;
7924         while ((c = getopt_long(argc, argv, short_opts,
7925                                 long_opts, NULL)) != -1) {
7926                 switch (c) {
7927                 case 'a':
7928                         advice_type = lfs_get_ladvice(optarg);
7929                         if (advice_type == LU_LADVISE_INVALID) {
7930                                 fprintf(stderr, "%s: invalid advice type "
7931                                         "'%s'\n", argv[0], optarg);
7932                                 fprintf(stderr, "Valid types:");
7933
7934                                 for (advice_type = 0;
7935                                      advice_type < ARRAY_SIZE(ladvise_names);
7936                                      advice_type++) {
7937                                         if (ladvise_names[advice_type] == NULL)
7938                                                 continue;
7939                                         fprintf(stderr, " %s",
7940                                                 ladvise_names[advice_type]);
7941                                 }
7942                                 fprintf(stderr, "\n");
7943
7944                                 return CMD_HELP;
7945                         }
7946                         break;
7947                 case 'b':
7948                         flags |= LF_ASYNC;
7949                         break;
7950                 case 'u':
7951                         flags |= LF_UNSET;
7952                         break;
7953                 case 'e':
7954                         size_units = 1;
7955                         rc = llapi_parse_size(optarg, &end,
7956                                               &size_units, 0);
7957                         if (rc) {
7958                                 fprintf(stderr, "%s: bad end offset '%s'\n",
7959                                         argv[0], optarg);
7960                                 return CMD_HELP;
7961                         }
7962                         break;
7963                 case 's':
7964                         size_units = 1;
7965                         rc = llapi_parse_size(optarg, &start,
7966                                               &size_units, 0);
7967                         if (rc) {
7968                                 fprintf(stderr, "%s: bad start offset "
7969                                         "'%s'\n", argv[0], optarg);
7970                                 return CMD_HELP;
7971                         }
7972                         break;
7973                 case 'l':
7974                         size_units = 1;
7975                         rc = llapi_parse_size(optarg, &length,
7976                                               &size_units, 0);
7977                         if (rc) {
7978                                 fprintf(stderr, "%s: bad length '%s'\n",
7979                                         argv[0], optarg);
7980                                 return CMD_HELP;
7981                         }
7982                         break;
7983                 case 'm':
7984                         mode = lfs_get_mode(optarg);
7985                         if (mode < 0) {
7986                                 fprintf(stderr, "%s: bad mode '%s', valid "
7987                                                  "modes are READ or WRITE\n",
7988                                         argv[0], optarg);
7989                                 return CMD_HELP;
7990                         }
7991                         break;
7992                 case '?':
7993                         return CMD_HELP;
7994                 default:
7995                         fprintf(stderr, "%s: option '%s' unrecognized\n",
7996                                 argv[0], argv[optind - 1]);
7997                         return CMD_HELP;
7998                 }
7999         }
8000
8001         if (advice_type == LU_LADVISE_INVALID) {
8002                 fprintf(stderr, "%s: please give an advice type\n", argv[0]);
8003                 fprintf(stderr, "Valid types:");
8004                 for (advice_type = 0; advice_type < ARRAY_SIZE(ladvise_names);
8005                      advice_type++) {
8006                         if (ladvise_names[advice_type] == NULL)
8007                                 continue;
8008                         fprintf(stderr, " %s", ladvise_names[advice_type]);
8009                 }
8010                 fprintf(stderr, "\n");
8011                 return CMD_HELP;
8012         }
8013
8014         if (advice_type == LU_LADVISE_LOCKNOEXPAND) {
8015                 fprintf(stderr, "%s: Lock no expand advice is a per file "
8016                                  "descriptor advice, so when called from lfs, "
8017                                  "it does nothing.\n", argv[0]);
8018                 return CMD_HELP;
8019         }
8020
8021         if (argc <= optind) {
8022                 fprintf(stderr, "%s: please give one or more file names\n",
8023                         argv[0]);
8024                 return CMD_HELP;
8025         }
8026
8027         if (end != LUSTRE_EOF && length != 0 && end != start + length) {
8028                 fprintf(stderr, "%s: conflicting arguments of -l and -e\n",
8029                         argv[0]);
8030                 return CMD_HELP;
8031         }
8032
8033         if (end == LUSTRE_EOF && length != 0)
8034                 end = start + length;
8035
8036         if (end <= start) {
8037                 fprintf(stderr, "%s: range [%llu, %llu] is invalid\n",
8038                         argv[0], start, end);
8039                 return CMD_HELP;
8040         }
8041
8042         if (advice_type != LU_LADVISE_LOCKAHEAD && mode != 0) {
8043                 fprintf(stderr, "%s: mode is only valid with lockahead\n",
8044                         argv[0]);
8045                 return CMD_HELP;
8046         }
8047
8048         if (advice_type == LU_LADVISE_LOCKAHEAD && mode == 0) {
8049                 fprintf(stderr, "%s: mode is required with lockahead\n",
8050                         argv[0]);
8051                 return CMD_HELP;
8052         }
8053
8054         while (optind < argc) {
8055                 int rc2;
8056
8057                 path = argv[optind++];
8058
8059                 fd = open(path, O_RDONLY);
8060                 if (fd < 0) {
8061                         fprintf(stderr, "%s: cannot open file '%s': %s\n",
8062                                 argv[0], path, strerror(errno));
8063                         rc2 = -errno;
8064                         goto next;
8065                 }
8066
8067                 advice.lla_start = start;
8068                 advice.lla_end = end;
8069                 advice.lla_advice = advice_type;
8070                 advice.lla_value1 = 0;
8071                 advice.lla_value2 = 0;
8072                 advice.lla_value3 = 0;
8073                 advice.lla_value4 = 0;
8074                 if (advice_type == LU_LADVISE_LOCKAHEAD) {
8075                         advice.lla_lockahead_mode = mode;
8076                         advice.lla_peradvice_flags = flags;
8077                 }
8078
8079                 rc2 = llapi_ladvise(fd, flags, 1, &advice);
8080                 close(fd);
8081                 if (rc2 < 0) {
8082                         fprintf(stderr, "%s: cannot give advice '%s' to file "
8083                                 "'%s': %s\n", argv[0],
8084                                 ladvise_names[advice_type],
8085                                 path, strerror(errno));
8086
8087                         goto next;
8088                 }
8089
8090 next:
8091                 if (rc == 0 && rc2 < 0)
8092                         rc = rc2;
8093         }
8094         return rc;
8095 }
8096
8097 /** The input string contains a comma delimited list of component ids and
8098  * ranges, for example "1,2-4,7".
8099  */
8100 static int parse_mirror_ids(__u16 *ids, int size, char *arg)
8101 {
8102         bool end_of_loop = false;
8103         char *ptr = NULL;
8104         int nr = 0;
8105         int rc;
8106
8107         if (arg == NULL)
8108                 return -EINVAL;
8109
8110         while (!end_of_loop) {
8111                 int start_index;
8112                 int end_index;
8113                 int i;
8114                 char *endptr = NULL;
8115
8116                 rc = -EINVAL;
8117                 ptr = strchrnul(arg, ',');
8118                 end_of_loop = *ptr == '\0';
8119                 *ptr = '\0';
8120
8121                 start_index = strtol(arg, &endptr, 0);
8122                 if (endptr == arg) /* no data at all */
8123                         break;
8124                 if (*endptr != '-' && *endptr != '\0') /* has invalid data */
8125                         break;
8126                 if (start_index < 0)
8127                         break;
8128
8129                 end_index = start_index;
8130                 if (*endptr == '-') {
8131                         end_index = strtol(endptr + 1, &endptr, 0);
8132                         if (*endptr != '\0')
8133                                 break;
8134                         if (end_index < start_index)
8135                                 break;
8136                 }
8137
8138                 for (i = start_index; i <= end_index && size > 0; i++) {
8139                         int j;
8140
8141                         /* remove duplicate */
8142                         for (j = 0; j < nr; j++) {
8143                                 if (ids[j] == i)
8144                                         break;
8145                         }
8146                         if (j == nr) { /* no duplicate */
8147                                 ids[nr++] = i;
8148                                 --size;
8149                         }
8150                 }
8151
8152                 if (size == 0 && i < end_index)
8153                         break;
8154
8155                 *ptr = ',';
8156                 arg = ++ptr;
8157                 rc = 0;
8158         }
8159         if (!end_of_loop && ptr != NULL)
8160                 *ptr = ',';
8161
8162         return rc < 0 ? rc : nr;
8163 }
8164
8165 /**
8166  * struct verify_mirror_id - Mirror id to be verified.
8167  * @mirror_id:   A specified mirror id.
8168  * @is_valid_id: @mirror_id is valid or not in the mirrored file.
8169  */
8170 struct verify_mirror_id {
8171         __u16 mirror_id;
8172         bool is_valid_id;
8173 };
8174
8175 /**
8176  * compare_mirror_ids() - Compare mirror ids.
8177  * @layout: Mirror component list.
8178  * @cbdata: Callback data in verify_mirror_id structure.
8179  *
8180  * This is a callback function called by llapi_layout_comp_iterate()
8181  * to compare the specified mirror id with the one in the current
8182  * component of @layout. If they are the same, then the specified
8183  * mirror id is valid.
8184  *
8185  * Return: a negative error code on failure or
8186  *         LLAPI_LAYOUT_ITER_CONT: Proceed iteration
8187  *         LLAPI_LAYOUT_ITER_STOP: Stop iteration
8188  */
8189 static inline
8190 int compare_mirror_ids(struct llapi_layout *layout, void *cbdata)
8191 {
8192         struct verify_mirror_id *mirror_id_cbdata =
8193                                  (struct verify_mirror_id *)cbdata;
8194         uint32_t mirror_id;
8195         int rc = 0;
8196
8197         rc = llapi_layout_mirror_id_get(layout, &mirror_id);
8198         if (rc < 0) {
8199                 rc = -errno;
8200                 fprintf(stderr,
8201                         "%s: llapi_layout_mirror_id_get failed: %s.\n",
8202                         progname, strerror(errno));
8203                 return rc;
8204         }
8205
8206         if (mirror_id_cbdata->mirror_id == mirror_id) {
8207                 mirror_id_cbdata->is_valid_id = true;
8208                 return LLAPI_LAYOUT_ITER_STOP;
8209         }
8210
8211         return LLAPI_LAYOUT_ITER_CONT;
8212 }
8213
8214 /**
8215  * verify_mirror_ids() - Verify specified mirror ids.
8216  * @fname:      Mirrored file name.
8217  * @mirror_ids: Specified mirror ids to be verified.
8218  * @ids_nr:     Number of specified mirror ids.
8219  *
8220  * This function verifies that specified @mirror_ids are valid
8221  * in the mirrored file @fname.
8222  *
8223  * Return: 0 on success or a negative error code on failure.
8224  */
8225 static inline
8226 int verify_mirror_ids(const char *fname, __u16 *mirror_ids, int ids_nr)
8227 {
8228         struct llapi_layout *layout = NULL;
8229         struct verify_mirror_id mirror_id_cbdata = { 0 };
8230         struct stat stbuf;
8231         uint32_t flr_state;
8232         int i;
8233         int fd;
8234         int rc = 0;
8235         int rc2 = 0;
8236
8237         if (ids_nr <= 0)
8238                 return -EINVAL;
8239
8240         if (stat(fname, &stbuf) < 0) {
8241                 fprintf(stderr, "%s: cannot stat file '%s': %s.\n",
8242                         progname, fname, strerror(errno));
8243                 rc = -errno;
8244                 goto error;
8245         }
8246
8247         if (!S_ISREG(stbuf.st_mode)) {
8248                 fprintf(stderr, "%s: '%s' is not a regular file.\n",
8249                         progname, fname);
8250                 rc = -EINVAL;
8251                 goto error;
8252         }
8253
8254         fd = open(fname, O_DIRECT | O_RDONLY);
8255         if (fd < 0) {
8256                 fprintf(stderr, "%s: cannot open '%s': %s.\n",
8257                         progname, fname, strerror(errno));
8258                 rc = -errno;
8259                 goto error;
8260         }
8261
8262         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
8263         if (rc < 0) {
8264                 fprintf(stderr, "%s: '%s' llapi_lease_acquire failed: %s.\n",
8265                         progname, fname, strerror(errno));
8266                 goto close_fd;
8267         }
8268
8269         layout = llapi_layout_get_by_fd(fd, 0);
8270         if (layout == NULL) {
8271                 fprintf(stderr, "%s: '%s' llapi_layout_get_by_fd failed: %s.\n",
8272                         progname, fname, strerror(errno));
8273                 rc = -errno;
8274                 llapi_lease_release(fd);
8275                 goto close_fd;
8276         }
8277
8278         rc = llapi_layout_flags_get(layout, &flr_state);
8279         if (rc < 0) {
8280                 fprintf(stderr, "%s: '%s' llapi_layout_flags_get failed: %s.\n",
8281                         progname, fname, strerror(errno));
8282                 rc = -errno;
8283                 goto free_layout;
8284         }
8285
8286         flr_state &= LCM_FL_FLR_MASK;
8287         switch (flr_state) {
8288         case LCM_FL_NONE:
8289                 rc = -EINVAL;
8290                 fprintf(stderr, "%s: '%s' file state error: %s.\n",
8291                         progname, fname, llapi_layout_flags_string(flr_state));
8292                 goto free_layout;
8293         default:
8294                 break;
8295         }
8296
8297         rc2 = 0;
8298         for (i = 0; i < ids_nr; i++) {
8299                 mirror_id_cbdata.mirror_id = mirror_ids[i];
8300                 mirror_id_cbdata.is_valid_id = false;
8301
8302                 rc = llapi_layout_comp_iterate(layout, compare_mirror_ids,
8303                                                &mirror_id_cbdata);
8304                 if (rc < 0) {
8305                         rc = -errno;
8306                         fprintf(stderr,
8307                                 "%s: '%s' failed to verify mirror id: %u.\n",
8308                                 progname, fname, mirror_ids[i]);
8309                         goto free_layout;
8310                 }
8311
8312                 if (!mirror_id_cbdata.is_valid_id) {
8313                         rc2 = -EINVAL;
8314                         fprintf(stderr,
8315                                 "%s: '%s' invalid specified mirror id: %u.\n",
8316                                 progname, fname, mirror_ids[i]);
8317                 }
8318         }
8319         rc = rc2;
8320
8321 free_layout:
8322         llapi_layout_free(layout);
8323         llapi_lease_release(fd);
8324 close_fd:
8325         close(fd);
8326 error:
8327         return rc;
8328 }
8329
8330 static inline
8331 int lfs_mirror_resync_file(const char *fname, struct ll_ioc_lease *ioc,
8332                            __u16 *mirror_ids, int ids_nr)
8333 {
8334         struct llapi_resync_comp comp_array[1024] = { { 0 } };
8335         struct llapi_layout *layout;
8336         struct stat stbuf;
8337         uint32_t flr_state;
8338         uint64_t start;
8339         uint64_t end;
8340         int comp_size = 0;
8341         int idx;
8342         int fd;
8343         int rc;
8344         int rc2;
8345
8346         if (stat(fname, &stbuf) < 0) {
8347                 fprintf(stderr, "%s: cannot stat file '%s': %s.\n",
8348                         progname, fname, strerror(errno));
8349                 rc = -errno;
8350                 goto error;
8351         }
8352         if (!S_ISREG(stbuf.st_mode)) {
8353                 fprintf(stderr, "%s: '%s' is not a regular file.\n",
8354                         progname, fname);
8355                 rc = -EINVAL;
8356                 goto error;
8357         }
8358
8359         fd = open(fname, O_DIRECT | O_RDWR);
8360         if (fd < 0) {
8361                 fprintf(stderr, "%s: cannot open '%s': %s.\n",
8362                         progname, fname, strerror(errno));
8363                 rc = -errno;
8364                 goto error;
8365         }
8366
8367         layout = llapi_layout_get_by_fd(fd, 0);
8368         if (layout == NULL) {
8369                 fprintf(stderr, "%s: '%s' llapi_layout_get_by_fd failed: %s.\n",
8370                         progname, fname, strerror(errno));
8371                 rc = -errno;
8372                 goto close_fd;
8373         }
8374
8375         rc = llapi_layout_flags_get(layout, &flr_state);
8376         if (rc) {
8377                 fprintf(stderr, "%s: '%s' llapi_layout_flags_get failed: %s.\n",
8378                         progname, fname, strerror(errno));
8379                 rc = -errno;
8380                 goto free_layout;
8381         }
8382
8383         flr_state &= LCM_FL_FLR_MASK;
8384         if (flr_state == LCM_FL_NONE) {
8385                 rc = -EINVAL;
8386                 fprintf(stderr, "%s: '%s' is not a FLR file.\n",
8387                         progname, fname);
8388                 goto free_layout;
8389         }
8390
8391         /* get stale component info */
8392         comp_size = llapi_mirror_find_stale(layout, comp_array,
8393                                             ARRAY_SIZE(comp_array),
8394                                             mirror_ids, ids_nr);
8395         if (comp_size <= 0) {
8396                 rc = comp_size;
8397                 goto free_layout;
8398         }
8399
8400         ioc->lil_mode = LL_LEASE_WRLCK;
8401         ioc->lil_flags = LL_LEASE_RESYNC;
8402         rc = llapi_lease_set(fd, ioc);
8403         if (rc < 0) {
8404                 if (rc == -EALREADY)
8405                         rc = 0;
8406                 else
8407                         fprintf(stderr,
8408                             "%s: '%s' llapi_lease_get_ext resync failed: %s.\n",
8409                                 progname, fname, strerror(-rc));
8410                 goto free_layout;
8411         }
8412
8413         /* get the read range [start, end) */
8414         start = comp_array[0].lrc_start;
8415         end = comp_array[0].lrc_end;
8416         for (idx = 1; idx < comp_size; idx++) {
8417                 if (comp_array[idx].lrc_start < start)
8418                         start = comp_array[idx].lrc_start;
8419                 if (end < comp_array[idx].lrc_end)
8420                         end = comp_array[idx].lrc_end;
8421         }
8422
8423         rc = llapi_lease_check(fd);
8424         if (rc != LL_LEASE_WRLCK) {
8425                 fprintf(stderr, "%s: '%s' lost lease lock.\n",
8426                         progname, fname);
8427                 goto free_layout;
8428         }
8429
8430         rc = llapi_mirror_resync_many(fd, layout, comp_array, comp_size,
8431                                       start, end);
8432         if (rc < 0)
8433                 fprintf(stderr, "%s: '%s' llapi_mirror_resync_many: %s.\n",
8434                         progname, fname, strerror(-rc));
8435
8436         /* need to do the lease unlock even resync fails */
8437         ioc->lil_mode = LL_LEASE_UNLCK;
8438         ioc->lil_flags = LL_LEASE_RESYNC_DONE;
8439         ioc->lil_count = 0;
8440         for (idx = 0; idx < comp_size; idx++) {
8441                 if (comp_array[idx].lrc_synced) {
8442                         ioc->lil_ids[ioc->lil_count] = comp_array[idx].lrc_id;
8443                         ioc->lil_count++;
8444                 }
8445         }
8446
8447         rc2 = llapi_lease_set(fd, ioc);
8448         /**
8449          * llapi_lease_set returns lease mode when it request to unlock
8450          * the lease lock.
8451          */
8452         if (rc2 <= 0) {
8453                 /* rc2 == 0 means lost lease lock */
8454                 if (rc2 == 0 && rc == 0)
8455                         rc = -EBUSY;
8456                 fprintf(stderr, "%s: resync file '%s' failed: %s.\n",
8457                         progname, fname,
8458                         rc2 == 0 ? "lost lease lock" : strerror(-rc2));
8459         }
8460
8461 free_layout:
8462         llapi_layout_free(layout);
8463 close_fd:
8464         close(fd);
8465 error:
8466         return rc;
8467 }
8468
8469 static inline int lfs_mirror_resync(int argc, char **argv)
8470 {
8471         struct ll_ioc_lease *ioc = NULL;
8472         __u16 mirror_ids[128] = { 0 };
8473         int ids_nr = 0;
8474         int c;
8475         int rc = 0;
8476
8477         struct option long_opts[] = {
8478         { .val = 'o',   .name = "only",         .has_arg = required_argument },
8479         { .name = NULL } };
8480
8481         while ((c = getopt_long(argc, argv, "o:", long_opts, NULL)) >= 0) {
8482                 switch (c) {
8483                 case 'o':
8484                         rc = parse_mirror_ids(mirror_ids,
8485                                         sizeof(mirror_ids) / sizeof(__u16),
8486                                         optarg);
8487                         if (rc < 0) {
8488                                 fprintf(stderr,
8489                                         "%s: bad mirror ids '%s'.\n",
8490                                         argv[0], optarg);
8491                                 goto error;
8492                         }
8493                         ids_nr = rc;
8494                         break;
8495                 default:
8496                         fprintf(stderr, "%s: options '%s' unrecognized.\n",
8497                                 argv[0], argv[optind - 1]);
8498                         rc = -EINVAL;
8499                         goto error;
8500                 }
8501         }
8502
8503         if (argc == optind) {
8504                 fprintf(stderr, "%s: no file name given.\n", argv[0]);
8505                 rc = CMD_HELP;
8506                 goto error;
8507         }
8508
8509         if (ids_nr > 0 && argc > optind + 1) {
8510                 fprintf(stderr,
8511                     "%s: option '--only' cannot be used upon multiple files.\n",
8512                         argv[0]);
8513                 rc = CMD_HELP;
8514                 goto error;
8515
8516         }
8517
8518         if (ids_nr > 0) {
8519                 rc = verify_mirror_ids(argv[optind], mirror_ids, ids_nr);
8520                 if (rc < 0)
8521                         goto error;
8522         }
8523
8524         /* set the lease on the file */
8525         ioc = calloc(sizeof(*ioc) + sizeof(__u32) * 4096, 1);
8526         if (ioc == NULL) {
8527                 fprintf(stderr, "%s: cannot alloc id array for ioc: %s.\n",
8528                         argv[0], strerror(errno));
8529                 rc = -errno;
8530                 goto error;
8531         }
8532
8533         for (; optind < argc; optind++) {
8534                 rc = lfs_mirror_resync_file(argv[optind], ioc,
8535                                             mirror_ids, ids_nr);
8536                 /* ignore previous file's error, continue with next file */
8537
8538                 /* reset ioc */
8539                 memset(ioc, 0, sizeof(*ioc) + sizeof(__u32) * 4096);
8540         }
8541
8542         free(ioc);
8543 error:
8544         return rc;
8545 }
8546
8547 static inline int verify_mirror_id_by_fd(int fd, __u16 mirror_id)
8548 {
8549         struct llapi_layout *layout;
8550         int rc;
8551
8552         layout = llapi_layout_get_by_fd(fd, 0);
8553         if (layout == NULL) {
8554                 fprintf(stderr, "could not get layout.\n");
8555                 return  -EINVAL;
8556         }
8557
8558         rc = llapi_layout_comp_iterate(layout, find_mirror_id, &mirror_id);
8559         if (rc < 0) {
8560                 fprintf(stderr, "failed to iterate layout\n");
8561                 llapi_layout_free(layout);
8562
8563                 return rc;
8564         } else if (rc == LLAPI_LAYOUT_ITER_CONT) {
8565                 fprintf(stderr, "does not find mirror with ID %u\n", mirror_id);
8566                 llapi_layout_free(layout);
8567
8568                 return -EINVAL;
8569         }
8570         llapi_layout_free(layout);
8571
8572         return 0;
8573 }
8574
8575 /**
8576  * Check whether two files are the same file
8577  * \retval      0  same file
8578  * \retval      1  not the same file
8579  * \retval      <0 error code
8580  */
8581 static inline int check_same_file(const char *f1, const char *f2)
8582 {
8583         struct stat stbuf1;
8584         struct stat stbuf2;
8585
8586         if (stat(f1, &stbuf1) < 0) {
8587                 fprintf(stderr, "%s: cannot stat file '%s': %s\n",
8588                         progname, f1, strerror(errno));
8589                 return -errno;
8590         }
8591
8592         if (stat(f2, &stbuf2) < 0) {
8593                 fprintf(stderr, "%s: cannot stat file '%s': %s\n",
8594                         progname, f2, strerror(errno));
8595                 return -errno;
8596         }
8597
8598         if (stbuf1.st_rdev == stbuf2.st_rdev &&
8599             stbuf1.st_ino == stbuf2.st_ino)
8600                 return 0;
8601
8602         return 1;
8603 }
8604
8605 static inline int lfs_mirror_read(int argc, char **argv)
8606 {
8607         int rc = CMD_HELP;
8608         __u16 mirror_id = 0;
8609         const char *outfile = NULL;
8610         char *fname;
8611         int fd = 0;
8612         int outfd;
8613         int c;
8614         void *buf;
8615         const size_t buflen = 4 << 20;
8616         off_t pos;
8617         struct option long_opts[] = {
8618         { .val = 'N',   .name = "mirror-id",    .has_arg = required_argument },
8619         { .val = 'o',   .name = "outfile",      .has_arg = required_argument },
8620         { .name = NULL } };
8621
8622         while ((c = getopt_long(argc, argv, "N:o:", long_opts, NULL)) >= 0) {
8623                 char *end;
8624
8625                 switch (c) {
8626                 case 'N':
8627                         mirror_id = strtoul(optarg, &end, 0);
8628                         if (*end != '\0' || mirror_id == 0) {
8629                                 fprintf(stderr,
8630                                         "%s %s: invalid mirror ID '%s'\n",
8631                                         progname, argv[0], optarg);
8632                                 return rc;
8633                         }
8634                         break;
8635                 case 'o':
8636                         outfile = optarg;
8637                         break;
8638                 default:
8639                         fprintf(stderr, "%s: option '%s' unrecognized.\n",
8640                                 progname, argv[optind - 1]);
8641                         return -EINVAL;
8642                 }
8643         }
8644
8645         if (argc == optind) {
8646                 fprintf(stderr, "%s %s: no mirrored file provided\n",
8647                         progname, argv[0]);
8648                 return rc;
8649         } else if (argc > optind + 1) {
8650                 fprintf(stderr, "%s %s: too many files\n", progname, argv[0]);
8651                 return rc;
8652         }
8653
8654         if (mirror_id == 0) {
8655                 fprintf(stderr, "%s %s: no valid mirror ID is provided\n",
8656                         progname, argv[0]);
8657                 return rc;
8658         }
8659
8660         /* open mirror file */
8661         fname = argv[optind];
8662
8663         if (outfile) {
8664                 rc = check_same_file(fname, outfile);
8665                 if (rc == 0) {
8666                         fprintf(stderr,
8667                         "%s %s: output file cannot be the mirrored file\n",
8668                                 progname, argv[0]);
8669                         return -EINVAL;
8670                 }
8671                 if (rc < 0)
8672                         return rc;
8673         }
8674
8675         fd = open(fname, O_DIRECT | O_RDONLY);
8676         if (fd < 0) {
8677                 fprintf(stderr, "%s %s: cannot open '%s': %s\n",
8678                         progname, argv[0], fname, strerror(errno));
8679                 return rc;
8680         }
8681
8682         /* verify mirror id */
8683         rc = verify_mirror_id_by_fd(fd, mirror_id);
8684         if (rc) {
8685                 fprintf(stderr,
8686                         "%s %s: cannot find mirror with ID %u in '%s'\n",
8687                         progname, argv[0], mirror_id, fname);
8688                 goto close_fd;
8689         }
8690
8691         /* open output file */
8692         if (outfile) {
8693                 outfd = open(outfile, O_EXCL | O_WRONLY | O_CREAT, 0644);
8694                 if (outfd < 0) {
8695                         fprintf(stderr, "%s %s: cannot create file '%s': %s\n",
8696                                 progname, argv[0], outfile, strerror(errno));
8697                         rc = -errno;
8698                         goto close_fd;
8699                 }
8700         } else {
8701                 outfd = STDOUT_FILENO;
8702         }
8703
8704         /* allocate buffer */
8705         rc = posix_memalign(&buf, sysconf(_SC_PAGESIZE), buflen);
8706         if (rc) {
8707                 fprintf(stderr, "%s %s: posix_memalign returns %d\n",
8708                                 progname, argv[0], rc);
8709                 goto close_outfd;
8710         }
8711
8712         pos = 0;
8713         while (1) {
8714                 ssize_t bytes_read;
8715                 ssize_t written = 0;
8716
8717                 bytes_read = llapi_mirror_read(fd, mirror_id, buf, buflen, pos);
8718                 if (bytes_read < 0) {
8719                         rc = bytes_read;
8720                         fprintf(stderr,
8721                                 "%s %s: fail to read data from mirror %u: %s\n",
8722                                 progname, argv[0], mirror_id, strerror(-rc));
8723                         goto free_buf;
8724                 }
8725
8726                 /* EOF reached */
8727                 if (bytes_read == 0)
8728                         break;
8729
8730                 while (written < bytes_read) {
8731                         ssize_t written2;
8732
8733                         written2 = write(outfd, buf + written,
8734                                          bytes_read - written);
8735                         if (written2 < 0) {
8736                                 fprintf(stderr,
8737                                         "%s %s: fail to write %s: %s\n",
8738                                         progname, argv[0], outfile ? : "STDOUT",
8739                                         strerror(errno));
8740                                 rc = -errno;
8741                                 goto free_buf;
8742                         }
8743                         written += written2;
8744                 }
8745
8746                 if (written != bytes_read) {
8747                         fprintf(stderr,
8748                 "%s %s: written %ld bytes does not match with %ld read.\n",
8749                                 progname, argv[0], written, bytes_read);
8750                         rc = -EIO;
8751                         goto free_buf;
8752                 }
8753
8754                 pos += bytes_read;
8755         }
8756
8757         fsync(outfd);
8758         rc = 0;
8759
8760 free_buf:
8761         free(buf);
8762 close_outfd:
8763         if (outfile)
8764                 close(outfd);
8765 close_fd:
8766         close(fd);
8767
8768         return rc;
8769 }
8770
8771 static inline int lfs_mirror_write(int argc, char **argv)
8772 {
8773         int rc = CMD_HELP;
8774         __u16 mirror_id = 0;
8775         const char *inputfile = NULL;
8776         char *fname;
8777         int fd = 0;
8778         int inputfd;
8779         int c;
8780         void *buf;
8781         const size_t buflen = 4 << 20;
8782         off_t pos;
8783         size_t page_size = sysconf(_SC_PAGESIZE);
8784         struct ll_ioc_lease_id ioc;
8785
8786         struct option long_opts[] = {
8787         { .val = 'N',   .name = "mirror-id",    .has_arg = required_argument },
8788         { .val = 'i',   .name = "inputfile",    .has_arg = required_argument },
8789         { .name = NULL } };
8790
8791         while ((c = getopt_long(argc, argv, "N:i:", long_opts, NULL)) >= 0) {
8792                 char *end;
8793
8794                 switch (c) {
8795                 case 'N':
8796                         mirror_id = strtoul(optarg, &end, 0);
8797                         if (*end != '\0' || mirror_id == 0) {
8798                                 fprintf(stderr,
8799                                         "%s %s: invalid mirror ID '%s'\n",
8800                                         progname, argv[0], optarg);
8801                                 return rc;
8802                         }
8803                         break;
8804                 case 'i':
8805                         inputfile = optarg;
8806                         break;
8807                 default:
8808                         fprintf(stderr, "%s: option '%s' unrecognized\n",
8809                                 progname, argv[optind - 1]);
8810                         return -EINVAL;
8811                 }
8812         }
8813
8814         if (argc == optind) {
8815                 fprintf(stderr, "%s %s: no mirrored file provided\n",
8816                         progname, argv[0]);
8817                 return rc;
8818         } else if (argc > optind + 1) {
8819                 fprintf(stderr, "%s %s: too many files\n", progname, argv[0]);
8820                 return rc;
8821         }
8822
8823         if (mirror_id == 0) {
8824                 fprintf(stderr, "%s %s: no valid mirror ID is provided\n",
8825                         progname, argv[0]);
8826                 return rc;
8827         }
8828
8829         /* open mirror file */
8830         fname = argv[optind];
8831
8832         if (inputfile) {
8833                 rc = check_same_file(fname, inputfile);
8834                 if (rc == 0) {
8835                         fprintf(stderr,
8836                         "%s %s: input file cannot be the mirrored file\n",
8837                                 progname, argv[0]);
8838                         return -EINVAL;
8839                 }
8840                 if (rc < 0)
8841                         return rc;
8842         }
8843
8844         fd = open(fname, O_DIRECT | O_WRONLY);
8845         if (fd < 0) {
8846                 fprintf(stderr, "%s %s: cannot open '%s': %s\n",
8847                         progname, argv[0], fname, strerror(errno));
8848                 return rc;
8849         }
8850
8851         /* verify mirror id */
8852         rc = verify_mirror_id_by_fd(fd, mirror_id);
8853         if (rc) {
8854                 fprintf(stderr,
8855                         "%s %s: cannot find mirror with ID %u in '%s'\n",
8856                         progname, argv[0], mirror_id, fname);
8857                 goto close_fd;
8858         }
8859
8860         /* open input file */
8861         if (inputfile) {
8862                 inputfd = open(inputfile, O_RDONLY, 0644);
8863                 if (inputfd < 0) {
8864                         fprintf(stderr, "%s %s: cannot open file '%s': %s\n",
8865                                 progname, argv[0], inputfile, strerror(errno));
8866                         rc = -errno;
8867                         goto close_fd;
8868                 }
8869         } else {
8870                 inputfd = STDIN_FILENO;
8871         }
8872
8873         /* allocate buffer */
8874         rc = posix_memalign(&buf, page_size, buflen);
8875         if (rc) {
8876                 fprintf(stderr, "%s %s: posix_memalign returns %d\n",
8877                         progname, argv[0], rc);
8878                 goto close_inputfd;
8879         }
8880
8881         /* prepare target mirror components instantiation */
8882         ioc.lil_mode = LL_LEASE_WRLCK;
8883         ioc.lil_flags = LL_LEASE_RESYNC;
8884         ioc.lil_mirror_id = mirror_id;
8885         rc = llapi_lease_set(fd, (struct ll_ioc_lease *)&ioc);
8886         if (rc < 0) {
8887                 fprintf(stderr,
8888                         "%s %s: '%s' llapi_lease_get_ext failed: %s\n",
8889                         progname, argv[0], fname, strerror(errno));
8890                 goto free_buf;
8891         }
8892
8893         pos = 0;
8894         while (1) {
8895                 ssize_t bytes_read;
8896                 ssize_t written;
8897                 size_t to_write;
8898
8899                 rc = llapi_lease_check(fd);
8900                 if (rc != LL_LEASE_WRLCK) {
8901                         fprintf(stderr, "%s %s: '%s' lost lease lock\n",
8902                                 progname, argv[0], fname);
8903                         goto free_buf;
8904                 }
8905
8906                 bytes_read = read(inputfd, buf, buflen);
8907                 if (bytes_read < 0) {
8908                         rc = bytes_read;
8909                         fprintf(stderr,
8910                                 "%s %s: fail to read data from '%s': %s\n",
8911                                 progname, argv[0], inputfile ? : "STDIN",
8912                                 strerror(errno));
8913                         rc = -errno;
8914                         goto free_buf;
8915                 }
8916
8917                 /* EOF reached */
8918                 if (bytes_read == 0)
8919                         break;
8920
8921                 /* round up to page align to make direct IO happy. */
8922                 to_write = (bytes_read + page_size - 1) & ~(page_size - 1);
8923
8924                 written = llapi_mirror_write(fd, mirror_id, buf, to_write,
8925                                              pos);
8926                 if (written < 0) {
8927                         rc = written;
8928                         fprintf(stderr,
8929                               "%s %s: fail to write to mirror %u: %s\n",
8930                                 progname, argv[0], mirror_id,
8931                                 strerror(-rc));
8932                         goto free_buf;
8933                 }
8934
8935                 pos += bytes_read;
8936         }
8937
8938         if (pos & (page_size - 1)) {
8939                 rc = llapi_mirror_truncate(fd, mirror_id, pos);
8940                 if (rc < 0)
8941                         goto free_buf;
8942         }
8943
8944         ioc.lil_mode = LL_LEASE_UNLCK;
8945         ioc.lil_flags = LL_LEASE_RESYNC_DONE;
8946         ioc.lil_count = 0;
8947         rc = llapi_lease_set(fd, (struct ll_ioc_lease *)&ioc);
8948         if (rc <= 0) {
8949                 if (rc == 0)
8950                         rc = -EBUSY;
8951                 fprintf(stderr,
8952                         "%s %s: release lease lock of '%s' failed: %s\n",
8953                         progname, argv[0], fname, strerror(errno));
8954                 goto free_buf;
8955         }
8956
8957         rc = 0;
8958
8959 free_buf:
8960         free(buf);
8961 close_inputfd:
8962         if (inputfile)
8963                 close(inputfd);
8964 close_fd:
8965         close(fd);
8966
8967         return rc;
8968 }
8969
8970 static inline int get_other_mirror_ids(int fd, __u16 *ids, __u16 exclude_id)
8971 {
8972         struct llapi_layout *layout;
8973         struct collect_ids_data cid = { .cid_ids = ids,
8974                                         .cid_count = 0,
8975                                         .cid_exclude = exclude_id, };
8976         int rc;
8977
8978         layout = llapi_layout_get_by_fd(fd, 0);
8979         if (layout == NULL) {
8980                 fprintf(stderr, "could not get layout\n");
8981                 return -EINVAL;
8982         }
8983
8984         rc = llapi_layout_comp_iterate(layout, collect_mirror_id, &cid);
8985         if (rc < 0) {
8986                 fprintf(stderr, "failed to iterate layout\n");
8987                 llapi_layout_free(layout);
8988
8989                 return rc;
8990         }
8991         llapi_layout_free(layout);
8992
8993         return cid.cid_count;
8994 }
8995
8996 static inline int lfs_mirror_copy(int argc, char **argv)
8997 {
8998         int rc = CMD_HELP;
8999         __u16 read_mirror_id = 0;
9000         __u16 ids[128] = { 0 };
9001         int count = 0;
9002         struct llapi_layout *layout = NULL;
9003         struct llapi_resync_comp comp_array[1024] = { { 0 } };
9004         int comp_size = 0;
9005         char *fname;
9006         int fd = 0;
9007         int c;
9008         int i;
9009         ssize_t copied;
9010         struct ll_ioc_lease *ioc = NULL;
9011         struct ll_ioc_lease_id *resync_ioc;
9012
9013         struct option long_opts[] = {
9014         { .val = 'i',   .name = "read-mirror",  .has_arg = required_argument },
9015         { .val = 'o',   .name = "write-mirror", .has_arg = required_argument },
9016         { .name = NULL } };
9017
9018         while ((c = getopt_long(argc, argv, "i:o:", long_opts, NULL)) >= 0) {
9019                 char *end;
9020
9021                 switch (c) {
9022                 case 'i':
9023                         read_mirror_id = strtoul(optarg, &end, 0);
9024                         if (*end != '\0' || read_mirror_id == 0) {
9025                                 fprintf(stderr,
9026                                         "%s %s: invalid read mirror ID '%s'\n",
9027                                         progname, argv[0], optarg);
9028                                 return rc;
9029                         }
9030                         break;
9031                 case 'o':
9032                         if (!strcmp(optarg, "-1")) {
9033                                 /* specify all other mirrors */
9034                                 ids[0] = (__u16)-1;
9035                                 count = 1;
9036                         } else {
9037                                 count = parse_mirror_ids((__u16 *)ids,
9038                                                          ARRAY_SIZE(ids),
9039                                                          optarg);
9040                                 if (count < 0)
9041                                         return rc;
9042                         }
9043                         break;
9044                 default:
9045                         fprintf(stderr, "%s: option '%s' unrecognized\n",
9046                                 progname, argv[optind - 1]);
9047                         return -EINVAL;
9048                 }
9049         }
9050
9051         if (argc == optind) {
9052                 fprintf(stderr, "%s %s: no mirrored file provided\n",
9053                         progname, argv[0]);
9054                 return rc;
9055         } else if (argc > optind + 1) {
9056                 fprintf(stderr, "%s %s: too many files\n", progname, argv[0]);
9057                 return rc;
9058         }
9059
9060         if (read_mirror_id == 0) {
9061                 fprintf(stderr,
9062                         "%s %s: no valid read mirror ID %d is provided\n",
9063                         progname, argv[0], read_mirror_id);
9064                 return rc;
9065         }
9066
9067         if (count == 0) {
9068                 fprintf(stderr,
9069                         "%s %s: no write mirror ID is provided\n",
9070                         progname, argv[0]);
9071                 return rc;
9072         }
9073
9074         for (i = 0; i < count; i++) {
9075                 if (read_mirror_id == ids[i]) {
9076                         fprintf(stderr,
9077                         "%s %s: read and write mirror ID cannot be the same\n",
9078                                 progname, argv[0]);
9079                         return rc;
9080                 }
9081         }
9082
9083         /* open mirror file */
9084         fname = argv[optind];
9085
9086         fd = open(fname, O_DIRECT | O_RDWR);
9087         if (fd < 0) {
9088                 fprintf(stderr, "%s %s: cannot open '%s': %s\n",
9089                         progname, argv[0], fname, strerror(errno));
9090                 return rc;
9091         }
9092
9093         /* write to all other mirrors */
9094         if (ids[0] == (__u16)-1) {
9095                 count = get_other_mirror_ids(fd, ids, read_mirror_id);
9096                 if (count <= 0) {
9097                         rc = count;
9098                         fprintf(stderr,
9099                         "%s %s: failed to get other mirror ids in '%s': %d\n",
9100                                 progname, argv[0], fname, rc);
9101                         goto close_fd;
9102                 }
9103         }
9104
9105         /* verify mirror id */
9106         rc = verify_mirror_id_by_fd(fd, read_mirror_id);
9107         if (rc) {
9108                 fprintf(stderr,
9109                         "%s %s: cannot find mirror with ID %u in '%s'\n",
9110                         progname, argv[0], read_mirror_id, fname);
9111                 goto close_fd;
9112         }
9113
9114         for (i = 0; i < count; i++) {
9115                 rc = verify_mirror_id_by_fd(fd, ids[i]);
9116                 if (rc) {
9117                         fprintf(stderr,
9118                         "%s %s: cannot find mirror with ID %u in '%s'\n",
9119                                 progname, argv[0], ids[i], fname);
9120                         goto close_fd;
9121                 }
9122         }
9123
9124         ioc = calloc(sizeof(*ioc) + sizeof(__u32) * 4096, 1);
9125         if (ioc == NULL) {
9126                 fprintf(stderr,
9127                         "%s %s: cannot alloc comp id array for ioc: %s\n",
9128                         progname, argv[0], strerror(errno));
9129                 rc = -errno;
9130                 goto close_fd;
9131         }
9132
9133         /* get stale component info */
9134         layout = llapi_layout_get_by_fd(fd, 0);
9135         if (layout == NULL) {
9136                 fprintf(stderr, "%s %s: failed to get layout of '%s': %s\n",
9137                         progname, argv[0], fname, strerror(errno));
9138                 rc = -errno;
9139                 goto free_ioc;
9140         }
9141         comp_size = llapi_mirror_find_stale(layout, comp_array,
9142                                             ARRAY_SIZE(comp_array),
9143                                             ids, count);
9144         llapi_layout_free(layout);
9145         if (comp_size < 0) {
9146                 rc = comp_size;
9147                 goto free_ioc;
9148         }
9149
9150         /* prepare target mirror components instantiation */
9151         resync_ioc = (struct ll_ioc_lease_id *)ioc;
9152         resync_ioc->lil_mode = LL_LEASE_WRLCK;
9153         resync_ioc->lil_flags = LL_LEASE_RESYNC;
9154         if (count == 1)
9155                 resync_ioc->lil_mirror_id = ids[0];
9156         else
9157                 resync_ioc->lil_mirror_id = read_mirror_id | MIRROR_ID_NEG;
9158         rc = llapi_lease_set(fd, ioc);
9159         if (rc < 0) {
9160                 fprintf(stderr,
9161                         "%s %s: '%s' llapi_lease_get_ext failed: %s\n",
9162                         progname, argv[0], fname, strerror(errno));
9163                 goto free_ioc;
9164         }
9165
9166         copied = llapi_mirror_copy_many(fd, read_mirror_id, ids, count);
9167         if (copied < 0) {
9168                 rc = copied;
9169                 fprintf(stderr, "%s %s: copy error: %d\n",
9170                         progname, argv[0], rc);
9171                 goto free_ioc;
9172         }
9173
9174         fprintf(stdout, "mirror copied successfully: ");
9175         for (i = 0; i < copied; i++)
9176                 fprintf(stdout, "%d ", ids[i]);
9177         fprintf(stdout, "\n");
9178
9179         ioc->lil_mode = LL_LEASE_UNLCK;
9180         ioc->lil_flags = LL_LEASE_RESYNC_DONE;
9181         ioc->lil_count = 0;
9182         for (i = 0; i < comp_size; i++) {
9183                 int j;
9184
9185                 for (j = 0; j < copied; j++) {
9186                         if (comp_array[i].lrc_mirror_id != ids[j])
9187                                 continue;
9188
9189                         ioc->lil_ids[ioc->lil_count] = comp_array[i].lrc_id;
9190                         ioc->lil_count++;
9191                 }
9192         }
9193         rc = llapi_lease_set(fd, ioc);
9194         if (rc <= 0) {
9195                 if (rc == 0)
9196                         rc = -EBUSY;
9197                 fprintf(stderr,
9198                         "%s %s: release lease lock of '%s' failed: %s\n",
9199                         progname, argv[0], fname, strerror(errno));
9200                 goto free_ioc;
9201         }
9202
9203         rc = 0;
9204
9205 free_ioc:
9206         free(ioc);
9207 close_fd:
9208         close(fd);
9209
9210         return rc;
9211 }
9212 /**
9213  * struct verify_chunk - Mirror chunk to be verified.
9214  * @chunk:        [start, end) of the chunk.
9215  * @mirror_count: Number of mirror ids in @mirror_id array.
9216  * @mirror_id:    Array of valid mirror ids that cover the chunk.
9217  */
9218 struct verify_chunk {
9219         struct lu_extent chunk;
9220         unsigned int mirror_count;
9221         __u16 mirror_id[LUSTRE_MIRROR_COUNT_MAX];
9222 };
9223
9224 /**
9225  * print_chunks() - Print chunk information.
9226  * @fname:       Mirrored file name.
9227  * @chunks:      Array of chunks.
9228  * @chunk_count: Number of chunks in @chunks array.
9229  *
9230  * This function prints [start, end) of each chunk in @chunks
9231  * for mirrored file @fname, and also prints the valid mirror ids
9232  * that cover the chunk.
9233  *
9234  * Return: void.
9235  */
9236 static inline
9237 void print_chunks(const char *fname, struct verify_chunk *chunks,
9238                   int chunk_count)
9239 {
9240         int i;
9241         int j;
9242
9243         fprintf(stdout, "Chunks to be verified in %s:\n", fname);
9244         for (i = 0; i < chunk_count; i++) {
9245                 fprintf(stdout, DEXT, PEXT(&chunks[i].chunk));
9246
9247                 if (chunks[i].mirror_count == 0)
9248                         fprintf(stdout, "\t[");
9249                 else {
9250                         fprintf(stdout, "\t[%u", chunks[i].mirror_id[0]);
9251                         for (j = 1; j < chunks[i].mirror_count; j++)
9252                                 fprintf(stdout, ", %u", chunks[i].mirror_id[j]);
9253                 }
9254                 fprintf(stdout, "]\t%u\n", chunks[i].mirror_count);
9255         }
9256         fprintf(stdout, "\n");
9257 }
9258
9259 /**
9260  * print_checksums() - Print CRC-32 checksum values.
9261  * @chunk: A chunk and its corresponding valid mirror ids.
9262  * @crc:   CRC-32 checksum values on the chunk for each valid mirror.
9263  *
9264  * This function prints CRC-32 checksum values on @chunk for
9265  * each valid mirror that covers it.
9266  *
9267  * Return: void.
9268  */
9269 static inline
9270 void print_checksums(struct verify_chunk *chunk, unsigned long *crc)
9271 {
9272         int i;
9273
9274         fprintf(stdout,
9275                 "CRC-32 checksum value for chunk "DEXT":\n",
9276                 PEXT(&chunk->chunk));
9277         for (i = 0; i < chunk->mirror_count; i++)
9278                 fprintf(stdout, "Mirror %u:\t%#lx\n",
9279                         chunk->mirror_id[i], crc[i]);
9280         fprintf(stdout, "\n");
9281 }
9282
9283 /**
9284  * filter_mirror_id() - Filter specified mirror ids.
9285  * @chunks:      Array of chunks.
9286  * @chunk_count: Number of chunks in @chunks array.
9287  * @mirror_ids:  Specified mirror ids to be verified.
9288  * @ids_nr:      Number of specified mirror ids.
9289  *
9290  * This function scans valid mirror ids that cover each chunk in @chunks
9291  * and filters specified mirror ids.
9292  *
9293  * Return: void.
9294  */
9295 static inline
9296 void filter_mirror_id(struct verify_chunk *chunks, int chunk_count,
9297                       __u16 *mirror_ids, int ids_nr)
9298 {
9299         int i;
9300         int j;
9301         int k;
9302         __u16 valid_id[LUSTRE_MIRROR_COUNT_MAX] = { 0 };
9303         unsigned int valid_count = 0;
9304
9305         for (i = 0; i < chunk_count; i++) {
9306                 if (chunks[i].mirror_count == 0)
9307                         continue;
9308
9309                 valid_count = 0;
9310                 for (j = 0; j < ids_nr; j++) {
9311                         for (k = 0; k < chunks[i].mirror_count; k++) {
9312                                 if (chunks[i].mirror_id[k] == mirror_ids[j]) {
9313                                         valid_id[valid_count] = mirror_ids[j];
9314                                         valid_count++;
9315                                         break;
9316                                 }
9317                         }
9318                 }
9319
9320                 memcpy(chunks[i].mirror_id, valid_id,
9321                        sizeof(__u16) * valid_count);
9322                 chunks[i].mirror_count = valid_count;
9323         }
9324 }
9325
9326 /**
9327  * lfs_mirror_prepare_chunk() - Find mirror chunks to be verified.
9328  * @layout:      Mirror component list.
9329  * @chunks:      Array of chunks.
9330  * @chunks_size: Array size of @chunks.
9331  *
9332  * This function scans the components in @layout from offset 0 to LUSTRE_EOF
9333  * to find out chunk segments and store them in @chunks array.
9334  *
9335  * The @mirror_id array in each element of @chunks will store the valid
9336  * mirror ids that cover the chunk. If a mirror component covering the
9337  * chunk has LCME_FL_STALE or LCME_FL_OFFLINE flag, then the mirror id
9338  * will not be stored into the @mirror_id array, and the chunk for that
9339  * mirror will not be verified.
9340  *
9341  * The @mirror_count in each element of @chunks will store the number of
9342  * mirror ids in @mirror_id array. If @mirror_count is 0, it indicates the
9343  * chunk is invalid in all of the mirrors. And if @mirror_count is 1, it
9344  * indicates the chunk is valid in only one mirror. In both cases, the
9345  * chunk will not be verified.
9346  *
9347  * Here is an example:
9348  *
9349  *  0      1M     2M     3M     4M           EOF
9350  *  +------+-------------+--------------------+
9351  *  |      |             |      S             |       mirror1
9352  *  +------+------+------+------+-------------+
9353  *  |             |   S  |   S  |             |       mirror2
9354  *  +-------------+------+------+-------------+
9355  *
9356  * prepared @chunks array will contain 5 elements:
9357  * (([0, 1M), [1, 2], 2),
9358  *  ([1M, 2M), [1, 2], 2),
9359  *  ([2M, 3M), [1], 1),
9360  *  ([3M, 4M], [], 0),
9361  *  ([4M, EOF), [2], 1))
9362  *
9363  * Return: the actual array size of @chunks on success
9364  *         or a negative error code on failure.
9365  */
9366 static inline
9367 int lfs_mirror_prepare_chunk(struct llapi_layout *layout,
9368                              struct verify_chunk *chunks,
9369                              size_t chunks_size)
9370 {
9371         uint64_t start;
9372         uint64_t end;
9373         uint32_t mirror_id;
9374         uint32_t flags;
9375         int idx = 0;
9376         int i = 0;
9377         int rc = 0;
9378
9379         memset(chunks, 0, sizeof(*chunks) * chunks_size);
9380
9381         while (1) {
9382                 rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_FIRST);
9383                 if (rc < 0) {
9384                         fprintf(stderr,
9385                                 "%s: move to the first layout component: %s.\n",
9386                                 progname, strerror(errno));
9387                         goto error;
9388                 }
9389
9390                 i = 0;
9391                 rc = 0;
9392                 chunks[idx].chunk.e_end = LUSTRE_EOF;
9393                 while (rc == 0) {
9394                         rc = llapi_layout_comp_extent_get(layout, &start, &end);
9395                         if (rc < 0) {
9396                                 fprintf(stderr,
9397                                         "%s: llapi_layout_comp_extent_get failed: %s.\n",
9398                                         progname, strerror(errno));
9399                                 goto error;
9400                         }
9401
9402                         if (start > chunks[idx].chunk.e_start ||
9403                             end <= chunks[idx].chunk.e_start)
9404                                 goto next;
9405
9406                         if (end < chunks[idx].chunk.e_end)
9407                                 chunks[idx].chunk.e_end = end;
9408
9409                         rc = llapi_layout_comp_flags_get(layout, &flags);
9410                         if (rc < 0) {
9411                                 fprintf(stderr,
9412                                         "%s: llapi_layout_comp_flags_get failed: %s.\n",
9413                                         progname, strerror(errno));
9414                                 goto error;
9415                         }
9416
9417                         if (flags & LCME_FL_STALE || flags & LCME_FL_OFFLINE)
9418                                 goto next;
9419
9420                         rc = llapi_layout_mirror_id_get(layout, &mirror_id);
9421                         if (rc < 0) {
9422                                 fprintf(stderr,
9423                                         "%s: llapi_layout_mirror_id_get failed: %s.\n",
9424                                         progname, strerror(errno));
9425                                 goto error;
9426                         }
9427
9428                         chunks[idx].mirror_id[i] = mirror_id;
9429                         i++;
9430                         if (i >= ARRAY_SIZE(chunks[idx].mirror_id)) {
9431                                 fprintf(stderr,
9432                                         "%s: mirror_id array is too small.\n",
9433                                         progname);
9434                                 rc = -EINVAL;
9435                                 goto error;
9436                         }
9437
9438                 next:
9439                         rc = llapi_layout_comp_use(layout,
9440                                                    LLAPI_LAYOUT_COMP_USE_NEXT);
9441                         if (rc < 0) {
9442                                 fprintf(stderr,
9443                                         "%s: move to the next layout component: %s.\n",
9444                                         progname, strerror(errno));
9445                                 goto error;
9446                         }
9447                 } /* loop through all components */
9448
9449                 chunks[idx].mirror_count = i;
9450
9451                 if (chunks[idx].chunk.e_end == LUSTRE_EOF)
9452                         break;
9453
9454                 idx++;
9455                 if (idx >= chunks_size) {
9456                         fprintf(stderr, "%s: chunks array is too small.\n",
9457                                 progname);
9458                         rc = -EINVAL;
9459                         goto error;
9460                 }
9461
9462                 chunks[idx].chunk.e_start = chunks[idx - 1].chunk.e_end;
9463         }
9464
9465 error:
9466         return rc < 0 ? rc : idx + 1;
9467 }
9468
9469 /**
9470  * lfs_mirror_verify_chunk() - Verify a chunk.
9471  * @fd:        File descriptor of the mirrored file.
9472  * @file_size: Size of the mirrored file.
9473  * @chunk:     A chunk and its corresponding valid mirror ids.
9474  * @verbose:   Verbose mode.
9475  *
9476  * This function verifies a @chunk contains exactly the same data
9477  * ammong the mirrors that cover it.
9478  *
9479  * If @verbose is specified, then the function will print where the
9480  * differences are if the data do not match. Otherwise, it will
9481  * just return an error in that case.
9482  *
9483  * Return: 0 on success or a negative error code on failure.
9484  */
9485 static inline
9486 int lfs_mirror_verify_chunk(int fd, size_t file_size,
9487                             struct verify_chunk *chunk, int verbose)
9488 {
9489         const size_t buflen = 4 * 1024 * 1024; /* 4M */
9490         void *buf;
9491         size_t page_size = sysconf(_SC_PAGESIZE);
9492         ssize_t bytes_read;
9493         ssize_t bytes_done;
9494         size_t count;
9495         off_t pos;
9496         unsigned long crc;
9497         unsigned long crc_array[LUSTRE_MIRROR_COUNT_MAX] = { 0 };
9498         int i;
9499         int rc = 0;
9500
9501         if (file_size == 0)
9502                 return 0;
9503
9504         rc = posix_memalign(&buf, page_size, buflen);
9505         if (rc) /* error code is returned directly */
9506                 return -rc;
9507
9508         if (verbose > 1) {
9509                 fprintf(stdout, "Verifying chunk "DEXT" on mirror:",
9510                         PEXT(&chunk->chunk));
9511                 for (i = 0; i < chunk->mirror_count; i++)
9512                         fprintf(stdout, " %u", chunk->mirror_id[i]);
9513                 fprintf(stdout, "\n");
9514         }
9515
9516         bytes_done = 0;
9517         count = MIN(chunk->chunk.e_end, file_size) - chunk->chunk.e_start;
9518         pos = chunk->chunk.e_start;
9519         while (bytes_done < count) {
9520                 /* compute initial CRC-32 checksum */
9521                 crc = crc32(0L, Z_NULL, 0);
9522                 memset(crc_array, 0, sizeof(crc_array));
9523
9524                 bytes_read = 0;
9525                 for (i = 0; i < chunk->mirror_count; i++) {
9526                         bytes_read = llapi_mirror_read(fd, chunk->mirror_id[i],
9527                                                        buf, buflen, pos);
9528                         if (bytes_read < 0) {
9529                                 rc = bytes_read;
9530                                 fprintf(stderr,
9531                                         "%s: failed to read data from mirror %u: %s.\n",
9532                                         progname, chunk->mirror_id[i],
9533                                         strerror(-rc));
9534                                 goto error;
9535                         }
9536
9537                         /* compute new CRC-32 checksum */
9538                         crc_array[i] = crc32(crc, buf, bytes_read);
9539                 }
9540
9541                 if (verbose)
9542                         print_checksums(chunk, crc_array);
9543
9544                 /* compare CRC-32 checksum values */
9545                 for (i = 1; i < chunk->mirror_count; i++) {
9546                         if (crc_array[i] != crc_array[0]) {
9547                                 rc = -EINVAL;
9548
9549                                 fprintf(stderr,
9550                                         "%s: chunk "DEXT" has different checksum value on mirror %u and mirror %u.\n",
9551                                         progname, PEXT(&chunk->chunk),
9552                                         chunk->mirror_id[0],
9553                                         chunk->mirror_id[i]);
9554                         }
9555                 }
9556
9557                 pos += bytes_read;
9558                 bytes_done += bytes_read;
9559         }
9560
9561         if (verbose > 1 && rc == 0) {
9562                 fprintf(stdout, "Verifying chunk "DEXT" on mirror:",
9563                         PEXT(&chunk->chunk));
9564                 for (i = 0; i < chunk->mirror_count; i++)
9565                         fprintf(stdout, " %u", chunk->mirror_id[i]);
9566                 fprintf(stdout, " PASS\n\n");
9567         }
9568
9569 error:
9570         free(buf);
9571         return rc;
9572 }
9573
9574 /**
9575  * lfs_mirror_verify_file() - Verify a mirrored file.
9576  * @fname:      Mirrored file name.
9577  * @mirror_ids: Specified mirror ids to be verified.
9578  * @ids_nr:     Number of specified mirror ids.
9579  * @verbose:    Verbose mode.
9580  *
9581  * This function verifies that each SYNC mirror of a mirrored file
9582  * specified by @fname contains exactly the same data.
9583  *
9584  * If @mirror_ids is specified, then the function will verify the
9585  * mirrors specified by @mirror_ids contain exactly the same data.
9586  *
9587  * If @verbose is specified, then the function will print where the
9588  * differences are if the data do not match. Otherwise, it will
9589  * just return an error in that case.
9590  *
9591  * Return: 0 on success or a negative error code on failure.
9592  */
9593 static inline
9594 int lfs_mirror_verify_file(const char *fname, __u16 *mirror_ids, int ids_nr,
9595                            int verbose)
9596 {
9597         struct verify_chunk chunks_array[1024] = { };
9598         struct llapi_layout *layout = NULL;
9599         struct stat stbuf;
9600         uint32_t flr_state;
9601         int fd;
9602         int chunk_count = 0;
9603         int idx = 0;
9604         int rc = 0;
9605         int rc1 = 0;
9606         int rc2 = 0;
9607
9608         if (stat(fname, &stbuf) < 0) {
9609                 fprintf(stderr, "%s: cannot stat file '%s': %s.\n",
9610                         progname, fname, strerror(errno));
9611                 rc = -errno;
9612                 goto error;
9613         }
9614
9615         if (!S_ISREG(stbuf.st_mode)) {
9616                 fprintf(stderr, "%s: '%s' is not a regular file.\n",
9617                         progname, fname);
9618                 rc = -EINVAL;
9619                 goto error;
9620         }
9621
9622         if (stbuf.st_size == 0) {
9623                 if (verbose)
9624                         fprintf(stdout, "%s: '%s' file size is 0.\n",
9625                                 progname, fname);
9626                 rc = 0;
9627                 goto error;
9628         }
9629
9630         fd = open(fname, O_DIRECT | O_RDONLY);
9631         if (fd < 0) {
9632                 fprintf(stderr, "%s: cannot open '%s': %s.\n",
9633                         progname, fname, strerror(errno));
9634                 rc = -errno;
9635                 goto error;
9636         }
9637
9638         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
9639         if (rc < 0) {
9640                 fprintf(stderr, "%s: '%s' llapi_lease_acquire failed: %s.\n",
9641                         progname, fname, strerror(errno));
9642                 goto close_fd;
9643         }
9644
9645         layout = llapi_layout_get_by_fd(fd, 0);
9646         if (layout == NULL) {
9647                 fprintf(stderr, "%s: '%s' llapi_layout_get_by_fd failed: %s.\n",
9648                         progname, fname, strerror(errno));
9649                 rc = -errno;
9650                 llapi_lease_release(fd);
9651                 goto close_fd;
9652         }
9653
9654         rc = llapi_layout_flags_get(layout, &flr_state);
9655         if (rc < 0) {
9656                 fprintf(stderr, "%s: '%s' llapi_layout_flags_get failed: %s.\n",
9657                         progname, fname, strerror(errno));
9658                 rc = -errno;
9659                 goto free_layout;
9660         }
9661
9662         flr_state &= LCM_FL_FLR_MASK;
9663         switch (flr_state) {
9664         case LCM_FL_NONE:
9665                 rc = -EINVAL;
9666                 fprintf(stderr, "%s: '%s' file state error: %s.\n",
9667                         progname, fname, llapi_layout_flags_string(flr_state));
9668                 goto free_layout;
9669         default:
9670                 break;
9671         }
9672
9673         /* find out mirror chunks to be verified */
9674         chunk_count = lfs_mirror_prepare_chunk(layout, chunks_array,
9675                                                ARRAY_SIZE(chunks_array));
9676         if (chunk_count < 0) {
9677                 rc = chunk_count;
9678                 goto free_layout;
9679         }
9680
9681         if (ids_nr > 0)
9682                 /* filter specified mirror ids */
9683                 filter_mirror_id(chunks_array, chunk_count, mirror_ids, ids_nr);
9684
9685         if (verbose > 2)
9686                 print_chunks(fname, chunks_array, chunk_count);
9687
9688         for (idx = 0; idx < chunk_count; idx++) {
9689                 if (chunks_array[idx].chunk.e_start >= stbuf.st_size) {
9690                         if (verbose)
9691                                 fprintf(stdout,
9692                                         "%s: '%s' chunk "DEXT" exceeds file size %#llx: skipped\n",
9693                                         progname, fname,
9694                                         PEXT(&chunks_array[idx].chunk),
9695                                         (unsigned long long)stbuf.st_size);
9696                         break;
9697                 }
9698
9699                 if (chunks_array[idx].mirror_count == 0) {
9700                         fprintf(stderr,
9701                                 "%s: '%s' chunk "DEXT" is invalid in all of the mirrors: ",
9702                                 progname, fname,
9703                                 PEXT(&chunks_array[idx].chunk));
9704                         if (verbose) {
9705                                 fprintf(stderr, "skipped\n");
9706                                 continue;
9707                         }
9708                         rc = -EINVAL;
9709                         fprintf(stderr, "failed\n");
9710                         goto free_layout;
9711                 }
9712
9713                 if (chunks_array[idx].mirror_count == 1) {
9714                         if (verbose)
9715                                 fprintf(stdout,
9716                                         "%s: '%s' chunk "DEXT" is only valid in mirror %u: skipped\n",
9717                                         progname, fname,
9718                                         PEXT(&chunks_array[idx].chunk),
9719                                         chunks_array[idx].mirror_id[0]);
9720                         continue;
9721                 }
9722
9723                 rc = llapi_lease_check(fd);
9724                 if (rc != LL_LEASE_RDLCK) {
9725                         fprintf(stderr, "%s: '%s' lost lease lock.\n",
9726                                 progname, fname);
9727                         goto free_layout;
9728                 }
9729
9730                 /* verify one chunk */
9731                 rc1 = lfs_mirror_verify_chunk(fd, stbuf.st_size,
9732                                               &chunks_array[idx], verbose);
9733                 if (rc1 < 0) {
9734                         rc2 = rc1;
9735                         if (!verbose) {
9736                                 rc = rc1;
9737                                 goto free_layout;
9738                         }
9739                 }
9740         }
9741
9742         if (rc2 < 0)
9743                 rc = rc2;
9744
9745 free_layout:
9746         llapi_layout_free(layout);
9747         llapi_lease_release(fd);
9748 close_fd:
9749         close(fd);
9750 error:
9751         return rc;
9752 }
9753
9754 /**
9755  * lfs_mirror_verify() - Parse and execute lfs mirror verify command.
9756  * @argc: The count of lfs mirror verify command line arguments.
9757  * @argv: Array of strings for lfs mirror verify command line arguments.
9758  *
9759  * This function parses lfs mirror verify command and verifies the
9760  * specified mirrored file(s).
9761  *
9762  * Return: 0 on success or a negative error code on failure.
9763  */
9764 static inline int lfs_mirror_verify(int argc, char **argv)
9765 {
9766         __u16 mirror_ids[LUSTRE_MIRROR_COUNT_MAX] = { 0 };
9767         int ids_nr = 0;
9768         int c;
9769         int verbose = 0;
9770         int rc = 0;
9771         int rc1 = 0;
9772         char cmd[PATH_MAX];
9773
9774         struct option long_opts[] = {
9775         { .val = 'o',   .name = "only",         .has_arg = required_argument },
9776         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
9777         { .name = NULL } };
9778
9779         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
9780         progname = cmd;
9781         while ((c = getopt_long(argc, argv, "o:v", long_opts, NULL)) >= 0) {
9782                 switch (c) {
9783                 case 'o':
9784                         rc = parse_mirror_ids(mirror_ids,
9785                                               ARRAY_SIZE(mirror_ids),
9786                                               optarg);
9787                         if (rc < 0) {
9788                                 fprintf(stderr,
9789                                         "%s: bad mirror ids '%s'.\n",
9790                                         progname, optarg);
9791                                 goto error;
9792                         }
9793                         ids_nr = rc;
9794                         if (ids_nr < 2) {
9795                                 fprintf(stderr,
9796                                         "%s: at least 2 mirror ids needed with '--only' option.\n",
9797                                         progname);
9798                                 rc = CMD_HELP;
9799                                 goto error;
9800                         }
9801                         break;
9802                 case 'v':
9803                         verbose++;
9804                         break;
9805                 default:
9806                         fprintf(stderr, "%s: option '%s' unrecognized.\n",
9807                                 progname, argv[optind - 1]);
9808                         rc = -EINVAL;
9809                         goto error;
9810                 }
9811         }
9812
9813         if (argc == optind) {
9814                 fprintf(stderr, "%s: no file name given.\n", progname);
9815                 rc = CMD_HELP;
9816                 goto error;
9817         }
9818
9819         if (ids_nr > 0 && argc > optind + 1) {
9820                 fprintf(stderr,
9821                         "%s: '--only' cannot be used upon multiple files.\n",
9822                         progname);
9823                 rc = CMD_HELP;
9824                 goto error;
9825
9826         }
9827
9828         if (ids_nr > 0) {
9829                 rc = verify_mirror_ids(argv[optind], mirror_ids, ids_nr);
9830                 if (rc < 0)
9831                         goto error;
9832         }
9833
9834         rc = 0;
9835         for (; optind < argc; optind++) {
9836                 rc1 = lfs_mirror_verify_file(argv[optind], mirror_ids, ids_nr,
9837                                              verbose);
9838                 if (rc1 < 0)
9839                         rc = rc1;
9840         }
9841 error:
9842         return rc;
9843 }
9844
9845 /**
9846  * lfs_mirror() - Parse and execute lfs mirror commands.
9847  * @argc: The count of lfs mirror command line arguments.
9848  * @argv: Array of strings for lfs mirror command line arguments.
9849  *
9850  * This function parses lfs mirror commands and performs the
9851  * corresponding functions specified in mirror_cmdlist[].
9852  *
9853  * Return: 0 on success or an error code on failure.
9854  */
9855 static int lfs_mirror(int argc, char **argv)
9856 {
9857         char cmd[PATH_MAX];
9858         int rc = 0;
9859
9860         setlinebuf(stdout);
9861
9862         Parser_init("lfs-mirror > ", mirror_cmdlist);
9863
9864         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
9865         progname = cmd;
9866         program_invocation_short_name = cmd;
9867         if (argc > 1)
9868                 rc = Parser_execarg(argc - 1, argv + 1, mirror_cmdlist);
9869         else
9870                 rc = Parser_commands();
9871
9872         return rc < 0 ? -rc : rc;
9873 }
9874
9875 static void lustre_som_swab(struct lustre_som_attrs *attrs)
9876 {
9877 #if __BYTE_ORDER == __BIG_ENDIAN
9878         __swab16s(&attrs->lsa_valid);
9879         __swab64s(&attrs->lsa_size);
9880         __swab64s(&attrs->lsa_blocks);
9881 #endif
9882 }
9883
9884 enum lfs_som_type {
9885         LFS_SOM_SIZE = 0x1,
9886         LFS_SOM_BLOCKS = 0x2,
9887         LFS_SOM_FLAGS = 0x4,
9888         LFS_SOM_ATTR_ALL = LFS_SOM_SIZE | LFS_SOM_BLOCKS |
9889                            LFS_SOM_FLAGS,
9890 };
9891
9892 static int lfs_getsom(int argc, char **argv)
9893 {
9894         const char *path;
9895         struct lustre_som_attrs *attrs;
9896         char buf[sizeof(*attrs) + 64];
9897         enum lfs_som_type type = LFS_SOM_ATTR_ALL;
9898         int rc = 0, c;
9899
9900         while ((c = getopt(argc, argv, "sbf")) != -1) {
9901                 switch (c) {
9902                 case 's':
9903                         type = LFS_SOM_SIZE;
9904                         break;
9905                 case 'b':
9906                         type = LFS_SOM_BLOCKS;
9907                         break;
9908                 case 'f':
9909                         type = LFS_SOM_FLAGS;
9910                         break;
9911                 default:
9912                         fprintf(stderr, "%s: invalid option '%c'\n",
9913                                 progname, optopt);
9914                         return CMD_HELP;
9915                 }
9916         }
9917
9918         argc -= optind;
9919         argv += optind;
9920
9921         if (argc != 1) {
9922                 fprintf(stderr, "%s: %s\n",
9923                         progname, argc == 0 ? "miss file target" :
9924                         "input more than 2 files");
9925                 return CMD_HELP;
9926         }
9927
9928         path = argv[0];
9929         attrs = (void *)buf;
9930         rc = lgetxattr(path, "trusted.som", attrs, sizeof(buf));
9931         if (rc < 0) {
9932                 rc = -errno;
9933                 fprintf(stderr, "%s failed to get som xattr: %s (%d)\n",
9934                         argv[0], strerror(errno), errno);
9935                 return rc;
9936         }
9937
9938         lustre_som_swab(attrs);
9939
9940         switch (type) {
9941         case LFS_SOM_ATTR_ALL:
9942                 printf("file: %s size: %llu blocks: %llu flags: %x\n",
9943                        path, (unsigned long long)attrs->lsa_size,
9944                        (unsigned long long)attrs->lsa_blocks,
9945                        attrs->lsa_valid);
9946                 break;
9947         case LFS_SOM_SIZE:
9948                 printf("%llu\n", (unsigned long long)attrs->lsa_size);
9949                 break;
9950         case LFS_SOM_BLOCKS:
9951                 printf("%llu\n", (unsigned long long)attrs->lsa_blocks);
9952                 break;
9953         case LFS_SOM_FLAGS:
9954                 printf("%x\n", attrs->lsa_valid);
9955                 break;
9956         default:
9957                 fprintf(stderr, "%s: unknown option\n", progname);
9958                 return CMD_HELP;
9959         }
9960
9961         return 0;
9962 }
9963
9964 /**
9965  * lfs_mirror_list_commands() - List lfs mirror commands.
9966  * @argc: The count of command line arguments.
9967  * @argv: Array of strings for command line arguments.
9968  *
9969  * This function lists lfs mirror commands defined in mirror_cmdlist[].
9970  *
9971  * Return: 0 on success.
9972  */
9973 static int lfs_mirror_list_commands(int argc, char **argv)
9974 {
9975         char buffer[81] = "";
9976
9977         Parser_list_commands(mirror_cmdlist, buffer, sizeof(buffer),
9978                              NULL, 0, 4);
9979
9980         return 0;
9981 }
9982
9983 static int lfs_list_commands(int argc, char **argv)
9984 {
9985         char buffer[81] = ""; /* 80 printable chars + terminating NUL */
9986
9987         Parser_list_commands(cmdlist, buffer, sizeof(buffer), NULL, 0, 4);
9988
9989         return 0;
9990 }
9991
9992 int main(int argc, char **argv)
9993 {
9994         int rc;
9995
9996         /* Ensure that liblustreapi constructor has run */
9997         if (!llapi_liblustreapi_initialized())
9998                 fprintf(stderr, "liblustreapi was not properly initialized\n");
9999
10000         setlinebuf(stdout);
10001         opterr = 0;
10002
10003         Parser_init("lfs > ", cmdlist);
10004
10005         progname = program_invocation_short_name; /* Used in error messages */
10006         if (argc > 1) {
10007                 llapi_set_command_name(argv[1]);
10008                 rc = Parser_execarg(argc - 1, argv + 1, cmdlist);
10009                 llapi_clear_command_name();
10010         } else {
10011                 rc = Parser_commands();
10012         }
10013
10014         return rc < 0 ? -rc : rc;
10015 }
10016
10017 #ifdef _LUSTRE_IDL_H_
10018 /* Everything we need here should be included by lustreapi.h. */
10019 # error "lfs should not depend on lustre_idl.h"
10020 #endif /* _LUSTRE_IDL_H_ */