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