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