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