Whamcloud - gitweb
089284dd288702a112ebd85ae0671cfb6cd26b75
[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-index|-i mdt_index[,mdt_index,...]\n"    \
250         "               [--mdt-hash|-H mdt_hash]\n"                     \
251         "               [--default|-D] [--mode|-m mode] <dir>\n"        \
252         "\tstripe_count: stripe count of the striped directory\n"       \
253         "\tmdt_index: MDT index of first stripe\n"                      \
254         "\tmdt_hash:  hash type of the striped directory. mdt types:\n" \
255         "       fnv_1a_64 FNV-1a hash algorithm (default)\n"            \
256         "       all_char  sum of characters % MDT_COUNT (not recommended)\n" \
257         "\tdefault_stripe: set default dirstripe of the directory\n"    \
258         "\tmode: the mode of the directory\n"
259
260 /**
261  * command_t mirror_cmdlist - lfs mirror commands.
262  */
263 command_t mirror_cmdlist[] = {
264         { .pc_name = "create", .pc_func = lfs_mirror_create,
265           .pc_help = "Create a mirrored file.\n"
266                 "usage: lfs mirror create "
267                 "<--mirror-count|-N[mirror_count]> "
268                 "[setstripe options] ... <filename|directory>\n"
269           MIRROR_CREATE_HELP },
270         { .pc_name = "extend", .pc_func = lfs_mirror_extend,
271           .pc_help = "Extend a mirrored file.\n"
272                 "usage: lfs mirror extend "
273                 "<--mirror-count|-N[mirror_count]> [--no-verify] "
274                 "[setstripe options|-f <victim_file>] ... <filename>\n"
275           MIRROR_EXTEND_HELP },
276         { .pc_name = "split", .pc_func = lfs_mirror_split,
277           .pc_help = "Split a mirrored file.\n"
278         "usage: lfs mirror split <--mirror-id <mirror_id> | \n"
279         "\t             <--component-id|-I <comp_id>> [--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          "     [[!] --mdt-index|--mdt|-m <uuid|index,...>]\n"
387          "     [[!] --name|-n <pattern>] [[!] --ost|-O <uuid|index,...>]\n"
388          "     [--print|-P] [--print0|-0] [[!] --size|-s [+-]N[bkMGTPE]]\n"
389          "     [[!] --stripe-count|-c [+-]<stripes>]\n"
390          "     [[!] --stripe-index|-i <index,...>]\n"
391          "     [[!] --stripe-size|-S [+-]N[kMGT]] [[!] --type|-t <filetype>]\n"
392          "     [[!] --gid|-g|--group|-G <gid>|<gname>]\n"
393          "     [[!] --uid|-u|--user|-U <uid>|<uname>] [[!] --pool <pool>]\n"
394          "     [[!] --projid <projid>]\n"
395          "     [[!] --layout|-L released,raid0,mdt]\n"
396          "     [[!] --component-count [+-]<comp_cnt>]\n"
397          "     [[!] --component-start [+-]N[kMGTPE]]\n"
398          "     [[!] --component-end|-E [+-]N[kMGTPE]]\n"
399          "     [[!] --component-flags <comp_flags>]\n"
400          "     [[!] --mirror-count|-N [+-]<n>]\n"
401          "     [[!] --mirror-state <[^]state>]\n"
402          "     [[!] --mdt-count|-T [+-]<stripes>]\n"
403          "     [[!] --mdt-hash|-H <hashtype>\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|-m] <start_mdt_index>\n"
545          "               [--mdt-count|-c] <stripe_count>\n"
546          "               [--mdt-hash|-H] <hash_type>\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                                 }
2294                         } else if (node->cy_type == CYAML_TYPE_NUMBER) {
2295                                 if (!strcmp(string, "lcm_mirror_count")) {
2296                                         lsa->lsa_mirror_count = node->cy_valueint;
2297                                 } else if (!strcmp(string, "lcme_extent.e_start")) {
2298                                         if (node->cy_valueint != 0 || *layout != NULL) {
2299                                                 rc = build_component(layout, lsa, true);
2300                                                 if (rc)
2301                                                         return rc;
2302                                         }
2303
2304                                         if (node->cy_valueint == 0)
2305                                                 lsa->lsa_first_comp = true;
2306
2307                                         /* initialize lsa */
2308                                         setstripe_args_init(lsa);
2309                                         lsa->lsa_tgts = osts;
2310                                 } else if (!strcmp(string, "lcme_extent.e_end")) {
2311                                         if (node->cy_valueint == -1)
2312                                                 lsa->lsa_comp_end = LUSTRE_EOF;
2313                                         else
2314                                                 lsa->lsa_comp_end = node->cy_valueint;
2315                                 } else if (!strcmp(string, "stripe_count")) {
2316                                         lsa->lsa_stripe_count = node->cy_valueint;
2317                                 } else if (!strcmp(string, "stripe_size")) {
2318                                         lsa->lsa_stripe_size = node->cy_valueint;
2319                                 } else if (!strcmp(string, "stripe_offset")) {
2320                                         lsa->lsa_stripe_off = node->cy_valueint;
2321                                 } else if (!strcmp(string, "l_ost_idx")) {
2322                                         osts[lsa->lsa_nr_tgts] = node->cy_valueint;
2323                                         lsa->lsa_nr_tgts++;
2324                                 }
2325                         }
2326                 }
2327                 node = node->cy_next;
2328         }
2329
2330         return rc;
2331 }
2332
2333 static int lfs_comp_create_from_yaml(char *template,
2334                                      struct llapi_layout **layout,
2335                                      struct lfs_setstripe_args *lsa,
2336                                      __u32 *osts)
2337 {
2338         struct cYAML *tree = NULL, *err_rc = NULL;
2339         int rc = 0;
2340
2341         tree = cYAML_build_tree(template, NULL, 0, &err_rc, false);
2342         if (!tree) {
2343                 fprintf(stderr, "%s: cannot parse YAML file %s\n",
2344                         progname, template);
2345                 cYAML_build_error(-EINVAL, -1, "yaml", "from comp yaml",
2346                                   "can't parse", &err_rc);
2347                 cYAML_print_tree2file(stderr, err_rc);
2348                 cYAML_free_tree(err_rc);
2349                 rc = -EINVAL;
2350                 goto err;
2351         }
2352
2353         /* initialize lsa for plain file */
2354         setstripe_args_init(lsa);
2355         lsa->lsa_tgts = osts;
2356
2357         rc = build_layout_from_yaml_node(tree, layout, lsa, osts);
2358         if (rc) {
2359                 fprintf(stderr, "%s: cannot build layout from YAML file %s.\n",
2360                         progname, template);
2361                 goto err;
2362         } else {
2363                 rc = build_component(layout, lsa, *layout != NULL);
2364         }
2365         /* clean clean lsa */
2366         setstripe_args_init(lsa);
2367
2368 err:
2369         if (tree)
2370                 cYAML_free_tree(tree);
2371         return rc;
2372 }
2373
2374 /* In 'lfs setstripe --component-add' mode, we need to fetch the extent
2375  * end of the last component in the existing file, and adjust the
2376  * first extent start of the components to be added accordingly. */
2377 static int adjust_first_extent(char *fname, struct llapi_layout *layout)
2378 {
2379         struct llapi_layout *head;
2380         uint64_t start, end, stripe_size, prev_end = 0;
2381         int rc;
2382
2383         if (layout == NULL) {
2384                 fprintf(stderr,
2385                         "%s setstripe: layout must be specified\n",
2386                         progname);
2387                 return -EINVAL;
2388         }
2389
2390         errno = 0;
2391         head = llapi_layout_get_by_path(fname, 0);
2392         if (head == NULL) {
2393                 fprintf(stderr,
2394                         "%s setstripe: cannot read layout from '%s': %s\n",
2395                         progname, fname, strerror(errno));
2396                 return -EINVAL;
2397         } else if (errno == ENODATA) {
2398                 /* file without LOVEA, this component-add will be turned
2399                  * into a component-create. */
2400                 llapi_layout_free(head);
2401                 return -ENODATA;
2402         } else if (!llapi_layout_is_composite(head)) {
2403                 fprintf(stderr, "%s setstripe: '%s' not a composite file\n",
2404                         progname, fname);
2405                 llapi_layout_free(head);
2406                 return -EINVAL;
2407         }
2408
2409         rc = llapi_layout_comp_extent_get(head, &start, &prev_end);
2410         if (rc) {
2411                 fprintf(stderr, "%s setstripe: cannot get prev extent: %s\n",
2412                         progname, strerror(errno));
2413                 llapi_layout_free(head);
2414                 return rc;
2415         }
2416
2417         llapi_layout_free(head);
2418
2419         /* Make sure we use the first component of the layout to be added. */
2420         rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_FIRST);
2421         if (rc < 0) {
2422                 fprintf(stderr,
2423                         "%s setstripe: cannot move component cursor: %s\n",
2424                         progname, strerror(errno));
2425                 return rc;
2426         }
2427
2428         rc = llapi_layout_comp_extent_get(layout, &start, &end);
2429         if (rc) {
2430                 fprintf(stderr, "%s setstripe: cannot get extent: %s\n",
2431                         progname, strerror(errno));
2432                 return rc;
2433         }
2434
2435         if (start > prev_end || end <= prev_end) {
2436                 fprintf(stderr,
2437                         "%s setstripe: first extent [%lu, %lu) not adjacent with extent end %lu\n",
2438                         progname, start, end, prev_end);
2439                 return -EINVAL;
2440         }
2441
2442         rc = llapi_layout_stripe_size_get(layout, &stripe_size);
2443         if (rc) {
2444                 fprintf(stderr, "%s setstripe: cannot get stripe size: %s\n",
2445                         progname, strerror(errno));
2446                 return rc;
2447         }
2448
2449         if (stripe_size != LLAPI_LAYOUT_DEFAULT &&
2450             (prev_end & (stripe_size - 1))) {
2451                 fprintf(stderr,
2452                         "%s setstripe: stripe size %lu not aligned with %lu\n",
2453                         progname, stripe_size, prev_end);
2454                 return -EINVAL;
2455         }
2456
2457         rc = llapi_layout_comp_extent_set(layout, prev_end, end);
2458         if (rc) {
2459                 fprintf(stderr,
2460                         "%s setstripe: cannot set component extent [%lu, %lu): %s\n",
2461                         progname, prev_end, end, strerror(errno));
2462                 return rc;
2463         }
2464
2465         return 0;
2466 }
2467
2468 static inline bool arg_is_eof(char *arg)
2469 {
2470         return !strncmp(arg, "-1", strlen("-1")) ||
2471                !strncmp(arg, "EOF", strlen("EOF")) ||
2472                !strncmp(arg, "eof", strlen("eof"));
2473 }
2474
2475 /**
2476  * lfs_mirror_alloc() - Allocate a mirror argument structure.
2477  *
2478  * Return: Valid mirror_args pointer on success and
2479  *         NULL if memory allocation fails.
2480  */
2481 static struct mirror_args *lfs_mirror_alloc(void)
2482 {
2483         struct mirror_args *mirror = NULL;
2484
2485         while (1) {
2486                 mirror = calloc(1, sizeof(*mirror));
2487                 if (mirror != NULL)
2488                         break;
2489
2490                 sleep(1);
2491         }
2492
2493         return mirror;
2494 }
2495
2496 /**
2497  * lfs_mirror_free() - Free memory allocated for a mirror argument
2498  *                     structure.
2499  * @mirror: Previously allocated mirror argument structure by
2500  *          lfs_mirror_alloc().
2501  *
2502  * Free memory allocated for @mirror.
2503  *
2504  * Return: void.
2505  */
2506 static void lfs_mirror_free(struct mirror_args *mirror)
2507 {
2508         if (mirror->m_layout != NULL)
2509                 llapi_layout_free(mirror->m_layout);
2510         free(mirror);
2511 }
2512
2513 /**
2514  * lfs_mirror_list_free() - Free memory allocated for a mirror list.
2515  * @mirror_list: Previously allocated mirror list.
2516  *
2517  * Free memory allocated for @mirror_list.
2518  *
2519  * Return: void.
2520  */
2521 static void lfs_mirror_list_free(struct mirror_args *mirror_list)
2522 {
2523         struct mirror_args *next_mirror = NULL;
2524
2525         while (mirror_list != NULL) {
2526                 next_mirror = mirror_list->m_next;
2527                 lfs_mirror_free(mirror_list);
2528                 mirror_list = next_mirror;
2529         }
2530 }
2531
2532 enum {
2533         LFS_POOL_OPT = 3,
2534         LFS_COMP_COUNT_OPT,
2535         LFS_COMP_START_OPT,
2536         LFS_COMP_FLAGS_OPT,
2537         LFS_COMP_DEL_OPT,
2538         LFS_COMP_SET_OPT,
2539         LFS_COMP_ADD_OPT,
2540         LFS_COMP_NO_VERIFY_OPT,
2541         LFS_PROJID_OPT,
2542         LFS_MIRROR_FLAGS_OPT,
2543         LFS_MIRROR_ID_OPT,
2544         LFS_MIRROR_STATE_OPT,
2545         LFS_LAYOUT_COPY,
2546         LFS_MIRROR_INDEX_OPT,
2547 };
2548
2549 /* functions */
2550 static int lfs_setstripe_internal(int argc, char **argv,
2551                                   enum setstripe_origin opc)
2552 {
2553         struct lfs_setstripe_args        lsa = { 0 };
2554         struct llapi_stripe_param       *param = NULL;
2555         struct find_param                migrate_mdt_param = {
2556                 .fp_max_depth = -1,
2557                 .fp_mdt_index = -1,
2558         };
2559         char                            *fname;
2560         int                              result = 0;
2561         int                              result2 = 0;
2562         char                            *end;
2563         int                              c;
2564         int                              delete = 0;
2565         unsigned long long               size_units = 1;
2566         bool                             migrate_mode = false;
2567         bool                             migrate_mdt_mode = false;
2568         bool                             migration_block = false;
2569         __u64                            migration_flags = 0;
2570         __u32                            tgts[LOV_MAX_STRIPE_COUNT] = { 0 };
2571         int                              comp_del = 0, comp_set = 0;
2572         int                              comp_add = 0;
2573         __u32                            comp_id = 0;
2574         struct llapi_layout             *layout = NULL;
2575         struct llapi_layout             **lpp = &layout;
2576         bool                             mirror_mode = false;
2577         bool                             has_m_file = false;
2578         __u32                            mirror_count = 0;
2579         enum mirror_flags                mirror_flags = 0;
2580         struct mirror_args              *mirror_list = NULL;
2581         struct mirror_args              *new_mirror = NULL;
2582         struct mirror_args              *last_mirror = NULL;
2583         __u16                            mirror_id = 0;
2584         char                             cmd[PATH_MAX];
2585         bool from_yaml = false;
2586         bool from_copy = false;
2587         char *template = NULL;
2588
2589         struct option long_opts[] = {
2590 /* find { .val = '0',   .name = "null",         .has_arg = no_argument }, */
2591 /* find { .val = 'A',   .name = "atime",        .has_arg = required_argument }*/
2592         /* --block is only valid in migrate mode */
2593         { .val = 'b',   .name = "block",        .has_arg = no_argument },
2594         { .val = LFS_COMP_ADD_OPT,
2595                         .name = "comp-add",     .has_arg = no_argument },
2596         { .val = LFS_COMP_ADD_OPT,
2597                         .name = "component-add", .has_arg = no_argument },
2598         { .val = LFS_COMP_DEL_OPT,
2599                         .name = "comp-del",     .has_arg = no_argument },
2600         { .val = LFS_COMP_DEL_OPT,
2601                         .name = "component-del", .has_arg = no_argument },
2602         { .val = LFS_COMP_FLAGS_OPT,
2603                         .name = "comp-flags",   .has_arg = required_argument },
2604         { .val = LFS_COMP_FLAGS_OPT,
2605                         .name = "component-flags",
2606                                                 .has_arg = required_argument },
2607         { .val = LFS_COMP_SET_OPT,
2608                         .name = "comp-set",     .has_arg = no_argument },
2609         { .val = LFS_COMP_SET_OPT,
2610                         .name = "component-set",
2611                                                 .has_arg = no_argument},
2612         { .val = LFS_COMP_NO_VERIFY_OPT,
2613                         .name = "no-verify",    .has_arg = no_argument},
2614         { .val = LFS_MIRROR_FLAGS_OPT,
2615                         .name = "flags",        .has_arg = required_argument},
2616         { .val = LFS_MIRROR_ID_OPT,
2617                         .name = "mirror-id",    .has_arg = required_argument},
2618         { .val = LFS_LAYOUT_COPY,
2619                         .name = "copy",         .has_arg = required_argument},
2620         { .val = 'c',   .name = "stripe-count", .has_arg = required_argument},
2621         { .val = 'c',   .name = "stripe_count", .has_arg = required_argument},
2622         { .val = 'c',   .name = "mdt-count",    .has_arg = required_argument},
2623 /* find { .val = 'C',   .name = "ctime",        .has_arg = required_argument }*/
2624         { .val = 'd',   .name = "delete",       .has_arg = no_argument},
2625         { .val = 'd',   .name = "destroy",      .has_arg = no_argument},
2626         /* --non-direct is only valid in migrate mode */
2627         { .val = 'D',   .name = "non-direct",   .has_arg = no_argument },
2628         { .val = 'E',   .name = "comp-end",     .has_arg = required_argument},
2629         { .val = 'E',   .name = "component-end",
2630                                                 .has_arg = required_argument},
2631         { .val = 'f',   .name = "file",         .has_arg = required_argument },
2632 /* find { .val = 'F',   .name = "fid",          .has_arg = no_argument }, */
2633 /* find { .val = 'g',   .name = "gid",          .has_arg = no_argument }, */
2634 /* find { .val = 'G',   .name = "group",        .has_arg = required_argument }*/
2635 /* find { .val = 'h',   .name = "help",         .has_arg = no_argument }, */
2636         { .val = 'H',   .name = "mdt-hash",     .has_arg = required_argument},
2637         { .val = 'i',   .name = "stripe-index", .has_arg = required_argument},
2638         { .val = 'i',   .name = "stripe_index", .has_arg = required_argument},
2639         { .val = 'I',   .name = "comp-id",      .has_arg = required_argument},
2640         { .val = 'I',   .name = "component-id", .has_arg = required_argument},
2641         { .val = 'L',   .name = "layout",       .has_arg = required_argument },
2642         { .val = 'm',   .name = "mdt",          .has_arg = required_argument},
2643         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument},
2644         { .val = 'm',   .name = "mdt_index",    .has_arg = required_argument},
2645         /* --non-block is only valid in migrate mode */
2646         { .val = 'n',   .name = "non-block",    .has_arg = no_argument },
2647         { .val = 'N',   .name = "mirror-count", .has_arg = optional_argument},
2648         { .val = 'o',   .name = "ost",          .has_arg = required_argument },
2649 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
2650         { .val = 'o',   .name = "ost-list",     .has_arg = required_argument },
2651         { .val = 'o',   .name = "ost_list",     .has_arg = required_argument },
2652 #endif
2653         { .val = 'p',   .name = "pool",         .has_arg = required_argument },
2654 /* find { .val = 'P',   .name = "print",        .has_arg = no_argument }, */
2655 /* getstripe { .val = 'q', .name = "quiet",     .has_arg = no_argument }, */
2656 /* getstripe { .val = 'r', .name = "recursive", .has_arg = no_argument }, */
2657 /* getstripe { .val = 'R', .name = "raw",       .has_arg = no_argument }, */
2658         { .val = 'S',   .name = "stripe-size",  .has_arg = required_argument },
2659         { .val = 'S',   .name = "stripe_size",  .has_arg = required_argument },
2660 /* find { .val = 't',   .name = "type",         .has_arg = required_argument }*/
2661 /* dirstripe { .val = 'T', .name = "mdt-count", .has_arg = required_argument }*/
2662 /* find { .val = 'u',   .name = "uid",          .has_arg = required_argument }*/
2663 /* find { .val = 'U',   .name = "user",         .has_arg = required_argument }*/
2664         /* --verbose is only valid in migrate mode */
2665         { .val = 'v',   .name = "verbose",      .has_arg = no_argument},
2666         { .val = 'y',   .name = "yaml",         .has_arg = required_argument },
2667         { .name = NULL } };
2668
2669         setstripe_args_init(&lsa);
2670
2671         migrate_mode = (opc == SO_MIGRATE);
2672         mirror_mode = (opc == SO_MIRROR_CREATE || opc == SO_MIRROR_EXTEND);
2673
2674         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
2675         progname = cmd;
2676         while ((c = getopt_long(argc, argv,
2677                                 "bc:dDE:f:H:i:I:m:N::no:p:L:s:S:vy:", long_opts,
2678                                 NULL)) >= 0) {
2679                 switch (c) {
2680                 case 0:
2681                         /* Long options. */
2682                         break;
2683                 case LFS_COMP_ADD_OPT:
2684                         comp_add = 1;
2685                         break;
2686                 case LFS_COMP_DEL_OPT:
2687                         comp_del = 1;
2688                         break;
2689                 case LFS_COMP_FLAGS_OPT:
2690                         result = comp_str2flags(optarg, &lsa.lsa_comp_flags,
2691                                                 &lsa.lsa_comp_neg_flags);
2692                         if (result != 0)
2693                                 goto usage_error;
2694                         if (mirror_mode && lsa.lsa_comp_neg_flags) {
2695                                 fprintf(stderr, "%s: inverted flags are not supported\n",
2696                                         progname);
2697                                 goto usage_error;
2698                         }
2699                         if (lsa.lsa_comp_neg_flags & LCME_FL_STALE) {
2700                                 fprintf(stderr,
2701                                         "%s: cannot clear 'stale' flags from component. Please use lfs-mirror-resync(1) instead\n",
2702                                         progname);
2703                                 result = -EINVAL;
2704                                 goto error;
2705                         }
2706
2707                         break;
2708                 case LFS_COMP_SET_OPT:
2709                         comp_set = 1;
2710                         break;
2711                 case LFS_COMP_NO_VERIFY_OPT:
2712                         mirror_flags |= MF_NO_VERIFY;
2713                         break;
2714                 case LFS_MIRROR_ID_OPT:
2715                         mirror_id = strtoul(optarg, &end, 0);
2716                         if (*end != '\0' || mirror_id == 0) {
2717                                 fprintf(stderr,
2718                                         "%s %s: invalid mirror ID '%s'\n",
2719                                         progname, argv[0], optarg);
2720                                 goto usage_error;
2721                         }
2722                         break;
2723                 case LFS_MIRROR_FLAGS_OPT: {
2724                         __u32 flags;
2725
2726                         if (!mirror_mode || !last_mirror) {
2727                                 fprintf(stderr, "error: %s: --flags must be specified with --mirror-count|-N option\n",
2728                                         progname);
2729                                 goto usage_error;
2730                         }
2731
2732                         result = comp_str2flags(optarg, &last_mirror->m_flags,
2733                                                 &flags);
2734                         if (result != 0)
2735                                 goto usage_error;
2736
2737                         if (flags) {
2738                                 fprintf(stderr, "%s: inverted flags are not supported\n",
2739                                         progname);
2740                                 result = -EINVAL;
2741                                 goto usage_error;
2742                         }
2743                         if (last_mirror->m_flags & ~LCME_USER_FLAGS) {
2744                                 fprintf(stderr,
2745                                         "%s: unsupported mirror flags: %s\n",
2746                                         progname, optarg);
2747                                 result = -EINVAL;
2748                                 goto error;
2749                         }
2750                         break;
2751                 }
2752                 case LFS_LAYOUT_COPY:
2753                         from_copy = true;
2754                         template = optarg;
2755                         break;
2756                 case 'b':
2757                         if (!migrate_mode) {
2758                                 fprintf(stderr,
2759                                         "%s %s: -b|--block valid only for migrate command\n",
2760                                         progname, argv[0]);
2761                                 goto usage_error;
2762                         }
2763                         migration_block = true;
2764                         break;
2765                 case 'c':
2766                         lsa.lsa_stripe_count = strtoul(optarg, &end, 0);
2767                         if (*end != '\0') {
2768                                 fprintf(stderr,
2769                                         "%s %s: invalid stripe count '%s'\n",
2770                                         progname, argv[0], optarg);
2771                                 goto usage_error;
2772                         }
2773
2774                         if (lsa.lsa_stripe_count == -1)
2775                                 lsa.lsa_stripe_count = LLAPI_LAYOUT_WIDE;
2776                         break;
2777                 case 'd':
2778                         /* delete the default striping pattern */
2779                         delete = 1;
2780                         if (opc == SO_MIRROR_SPLIT) {
2781                                 if (has_m_file) {
2782                                         fprintf(stderr,
2783                                               "%s %s: -d cannot used with -f\n",
2784                                                 progname, argv[0]);
2785                                         goto usage_error;
2786                                 }
2787                                 mirror_flags |= MF_DESTROY;
2788                         }
2789                         break;
2790                 case 'D':
2791                         if (!migrate_mode) {
2792                                 fprintf(stderr,
2793                                         "%s %s: -D|--non-direct is valid "
2794                                         "only for migrate command\n",
2795                                         progname, argv[0]);
2796                                 goto usage_error;
2797                         }
2798                         migration_flags |= MIGRATION_NONDIRECT;
2799                         break;
2800                 case 'E':
2801                         if (lsa.lsa_comp_end != 0) {
2802                                 result = comp_args_to_layout(lpp, &lsa, true);
2803                                 if (result) {
2804                                         fprintf(stderr,
2805                                                 "%s %s: invalid layout\n",
2806                                                 progname, argv[0]);
2807                                         goto usage_error;
2808                                 }
2809
2810                                 setstripe_args_init_inherit(&lsa);
2811                         }
2812
2813                         if (arg_is_eof(optarg)) {
2814                                 lsa.lsa_comp_end = LUSTRE_EOF;
2815                         } else {
2816                                 result = llapi_parse_size(optarg,
2817                                                         &lsa.lsa_comp_end,
2818                                                         &size_units, 0);
2819                                 if (result) {
2820                                         fprintf(stderr,
2821                                                 "%s %s: invalid component end '%s'\n",
2822                                                 progname, argv[0], optarg);
2823                                         goto usage_error;
2824                                 }
2825                         }
2826                         break;
2827                 case 'H':
2828                         if (!migrate_mode) {
2829                                 fprintf(stderr, "--mdt-hash is valid only for migrate command\n");
2830                                 return CMD_HELP;
2831                         }
2832
2833                         lsa.lsa_pattern = check_hashtype(optarg);
2834                         if (lsa.lsa_pattern == 0) {
2835                                 fprintf(stderr,
2836                                         "%s %s: bad stripe hash type '%s'\n",
2837                                         progname, argv[0], optarg);
2838                                 return CMD_HELP;
2839                         }
2840                         break;
2841                 case 'i':
2842                         lsa.lsa_stripe_off = strtol(optarg, &end, 0);
2843                         if (*end != '\0') {
2844                                 fprintf(stderr,
2845                                         "%s %s: invalid stripe offset '%s'\n",
2846                                         progname, argv[0], optarg);
2847                                 goto usage_error;
2848                         }
2849                         if (lsa.lsa_stripe_off == -1)
2850                                 lsa.lsa_stripe_off = LLAPI_LAYOUT_DEFAULT;
2851                         break;
2852                 case 'I':
2853                         comp_id = strtoul(optarg, &end, 0);
2854                         if (*end != '\0' || comp_id == 0 ||
2855                             comp_id > LCME_ID_MAX) {
2856                                 fprintf(stderr,
2857                                         "%s %s: invalid component ID '%s'\n",
2858                                         progname, argv[0], optarg);
2859                                 goto usage_error;
2860                         }
2861                         break;
2862                 case 'f':
2863                         if (opc != SO_MIRROR_EXTEND && opc != SO_MIRROR_SPLIT) {
2864                                 fprintf(stderr,
2865                                         "error: %s: invalid option: %s\n",
2866                                         progname, argv[optopt + 1]);
2867                                 goto usage_error;
2868                         }
2869                         if (opc == SO_MIRROR_EXTEND) {
2870                                 if (last_mirror == NULL) {
2871                                         fprintf(stderr,
2872                                 "error: %s: '-N' must exist in front of '%s'\n",
2873                                                 progname, argv[optopt + 1]);
2874                                         goto usage_error;
2875                                 }
2876                                 last_mirror->m_file = optarg;
2877                                 last_mirror->m_count = 1;
2878                         } else {
2879                                 /* mirror split */
2880                                 if (mirror_list == NULL)
2881                                         mirror_list = lfs_mirror_alloc();
2882                                 mirror_list->m_file = optarg;
2883                         }
2884                         has_m_file = true;
2885                         break;
2886                 case 'L':
2887                         if (strcmp(argv[optind - 1], "mdt") == 0) {
2888                                 /* Can be only the first component */
2889                                 if (layout != NULL) {
2890                                         result = -EINVAL;
2891                                         fprintf(stderr, "error: 'mdt' layout "
2892                                                 "can be only the first one\n");
2893                                         goto error;
2894                                 }
2895                                 if (lsa.lsa_comp_end > (1ULL << 30)) { /* 1Gb */
2896                                         result = -EFBIG;
2897                                         fprintf(stderr, "error: 'mdt' layout "
2898                                                 "size is too big\n");
2899                                         goto error;
2900                                 }
2901                                 lsa.lsa_pattern = LLAPI_LAYOUT_MDT;
2902                         } else if (strcmp(argv[optind - 1], "raid0") != 0) {
2903                                 result = -EINVAL;
2904                                 fprintf(stderr, "error: layout '%s' is "
2905                                         "unknown, supported layouts are: "
2906                                         "'mdt', 'raid0'\n", argv[optind]);
2907                                 goto error;
2908                         }
2909                         break;
2910                 case 'm':
2911                         if (!migrate_mode) {
2912                                 fprintf(stderr,
2913                                         "%s %s: -m|--mdt is valid only for migrate command\n",
2914                                         progname, argv[0]);
2915                                 goto usage_error;
2916                         }
2917                         migrate_mdt_mode = true;
2918                         lsa.lsa_nr_tgts = parse_targets(tgts,
2919                                                 sizeof(tgts) / sizeof(__u32),
2920                                                 lsa.lsa_nr_tgts, optarg);
2921                         if (lsa.lsa_nr_tgts < 0) {
2922                                 fprintf(stderr,
2923                                         "%s %s: invalid MDT target(s) '%s'\n",
2924                                         progname, argv[0], optarg);
2925                                 return CMD_HELP;
2926                         }
2927
2928                         lsa.lsa_tgts = tgts;
2929                         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
2930                                 lsa.lsa_stripe_off = tgts[0];
2931                         break;
2932                 case 'n':
2933                         if (!migrate_mode) {
2934                                 fprintf(stderr,
2935                                         "%s %s: -n|--non-block valid only for migrate command\n",
2936                                         progname, argv[0]);
2937                                 goto usage_error;
2938                         }
2939                         migration_flags |= MIGRATION_NONBLOCK;
2940                         break;
2941                 case 'N':
2942                         if (opc == SO_SETSTRIPE) {
2943                                 opc = SO_MIRROR_CREATE;
2944                                 mirror_mode = true;
2945                         }
2946                         mirror_count = 1;
2947                         if (optarg != NULL) {
2948                                 mirror_count = strtoul(optarg, &end, 0);
2949                                 if (*end != '\0' || mirror_count == 0) {
2950                                         fprintf(stderr,
2951                                                 "error: %s: bad mirror count: %s\n",
2952                                                 progname, optarg);
2953                                         result = -EINVAL;
2954                                         goto error;
2955                                 }
2956                         }
2957
2958                         new_mirror = lfs_mirror_alloc();
2959                         new_mirror->m_count = mirror_count;
2960
2961                         if (mirror_list == NULL)
2962                                 mirror_list = new_mirror;
2963
2964                         if (last_mirror != NULL) {
2965                                 /* wrap up last mirror */
2966                                 if (lsa.lsa_comp_end == 0)
2967                                         lsa.lsa_comp_end = LUSTRE_EOF;
2968
2969                                 result = comp_args_to_layout(lpp, &lsa, true);
2970                                 if (result) {
2971                                         lfs_mirror_free(new_mirror);
2972                                         goto error;
2973                                 }
2974
2975                                 setstripe_args_init_inherit(&lsa);
2976
2977                                 last_mirror->m_next = new_mirror;
2978                         }
2979
2980                         last_mirror = new_mirror;
2981                         lpp = &last_mirror->m_layout;
2982                         break;
2983                 case 'o':
2984 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
2985                         if (strcmp(argv[optind - 1], "--ost-list") == 0)
2986                                 fprintf(stderr, "warning: '--ost-list' is "
2987                                         "deprecated, use '--ost' instead\n");
2988 #endif
2989                         lsa.lsa_nr_tgts = parse_targets(tgts,
2990                                                 sizeof(tgts) / sizeof(__u32),
2991                                                 lsa.lsa_nr_tgts, optarg);
2992                         if (lsa.lsa_nr_tgts < 0) {
2993                                 fprintf(stderr,
2994                                         "%s %s: invalid OST target(s) '%s'\n",
2995                                         progname, argv[0], optarg);
2996                                 goto usage_error;
2997                         }
2998
2999                         lsa.lsa_tgts = tgts;
3000                         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
3001                                 lsa.lsa_stripe_off = tgts[0];
3002                         break;
3003                 case 'p':
3004                         if (optarg == NULL)
3005                                 goto usage_error;
3006                         lsa.lsa_pool_name = optarg;
3007
3008                         if (strlen(lsa.lsa_pool_name) == 0 ||
3009                             strncmp(lsa.lsa_pool_name, "none",
3010                                     LOV_MAXPOOLNAME) == 0)
3011                                 lsa.lsa_pool_name = NULL;
3012                         break;
3013                 case 'S':
3014                         result = llapi_parse_size(optarg, &lsa.lsa_stripe_size,
3015                                                   &size_units, 0);
3016                         if (result) {
3017                                 fprintf(stderr,
3018                                         "%s %s: invalid stripe size '%s'\n",
3019                                         progname, argv[0], optarg);
3020                                 goto usage_error;
3021                         }
3022                         break;
3023                 case 'v':
3024                         if (!migrate_mode) {
3025                                 fprintf(stderr,
3026                                         "%s %s: -v|--verbose valid only for migrate command\n",
3027                                         progname, argv[0]);
3028                                 goto usage_error;
3029                         }
3030                         migrate_mdt_param.fp_verbose = VERBOSE_DETAIL;
3031                         migration_flags = MIGRATION_VERBOSE;
3032                         break;
3033                 case 'y':
3034                         from_yaml = true;
3035                         template = optarg;
3036                         break;
3037                 default:
3038                         fprintf(stderr, "%s %s: unrecognized option '%s'\n",
3039                                 progname, argv[0], argv[optind - 1]);
3040                         goto usage_error;
3041                 }
3042         }
3043
3044         fname = argv[optind];
3045
3046         if (optind == argc) {
3047                 fprintf(stderr, "%s %s: FILE must be specified\n",
3048                         progname, argv[0]);
3049                 goto usage_error;
3050         }
3051
3052         if (mirror_mode && mirror_count == 0) {
3053                 fprintf(stderr,
3054                         "error: %s: --mirror-count|-N option is required\n",
3055                         progname);
3056                 result = -EINVAL;
3057                 goto error;
3058         }
3059
3060         if (mirror_mode) {
3061                 if (lsa.lsa_comp_end == 0)
3062                         lsa.lsa_comp_end = LUSTRE_EOF;
3063         }
3064
3065         if (lsa.lsa_comp_end != 0) {
3066                 result = comp_args_to_layout(lpp, &lsa, true);
3067                 if (result)
3068                         goto error;
3069         }
3070
3071         if (mirror_flags & MF_NO_VERIFY) {
3072                 if (opc != SO_MIRROR_EXTEND) {
3073                         fprintf(stderr,
3074                                 "error: %s: --no-verify is valid only for lfs mirror extend command\n",
3075                                 progname);
3076                         result = -EINVAL;
3077                         goto error;
3078                 } else if (!has_m_file) {
3079                         fprintf(stderr,
3080                                 "error: %s: --no-verify must be specified with -f <victim_file> option\n",
3081                                 progname);
3082                         result = -EINVAL;
3083                         goto error;
3084                 }
3085         }
3086
3087         /* Only LCME_FL_INIT flags is used in PFL, and it shouldn't be
3088          * altered by user space tool, so we don't need to support the
3089          * --component-set for this moment. */
3090         if (comp_set && !comp_id) {
3091                 fprintf(stderr, "%s %s: --component-set doesn't have component-id set\n",
3092                         progname, argv[0]);
3093                 goto usage_error;
3094         }
3095
3096         if ((delete + comp_set + comp_del + comp_add) > 1) {
3097                 fprintf(stderr,
3098                         "%s %s: options --component-set, --component-del, --component-add and -d are mutually exclusive\n",
3099                         progname, argv[0]);
3100                 goto usage_error;
3101         }
3102
3103         if (delete && (setstripe_args_specified(&lsa) || comp_id != 0 ||
3104                        lsa.lsa_comp_flags != 0 || layout != NULL)) {
3105                 fprintf(stderr,
3106                         "%s %s: option -d is mutually exclusive with -s, -c, -o, -p, -I, -F and -E options\n",
3107                         progname, argv[0]);
3108                 goto usage_error;
3109         }
3110
3111         if ((comp_set || comp_del) &&
3112             (setstripe_args_specified(&lsa) || layout != NULL)) {
3113                 fprintf(stderr,
3114                         "%s %s: options --component-del and --component-set are mutually exclusive when used with -c, -E, -o, -p, or -s\n",
3115                         progname, argv[0]);
3116                 goto usage_error;
3117         }
3118
3119         if (comp_del && comp_id != 0 && lsa.lsa_comp_flags != 0) {
3120                 fprintf(stderr,
3121                         "%s %s: options -I and -F are mutually exclusive when used with --component-del\n",
3122                         progname, argv[0]);
3123                 goto usage_error;
3124         }
3125
3126         if (comp_add || comp_del) {
3127                 struct stat st;
3128
3129                 result = lstat(fname, &st);
3130                 if (result == 0 && S_ISDIR(st.st_mode)) {
3131                         fprintf(stderr,
3132                                 "%s setstripe: cannot use --component-add or --component-del for directory\n",
3133                                 progname);
3134                         goto usage_error;
3135                 }
3136
3137                 if (mirror_mode) {
3138                         fprintf(stderr, "error: %s: can't use --component-add "
3139                                 "or --component-del for mirror operation\n",
3140                                 progname);
3141                         goto usage_error;
3142                 }
3143         }
3144
3145         if (comp_add) {
3146                 if (layout == NULL) {
3147                         fprintf(stderr,
3148                                 "%s %s: option -E must be specified with --component-add\n",
3149                                 progname, argv[0]);
3150                         goto usage_error;
3151                 }
3152
3153                 result = adjust_first_extent(fname, layout);
3154                 if (result == -ENODATA)
3155                         comp_add = 0;
3156                 else if (result != 0)
3157                         goto error;
3158         }
3159
3160         if (from_yaml && from_copy) {
3161                 fprintf(stderr,
3162                         "%s: can't specify --yaml and --copy together\n",
3163                         progname);
3164                 goto error;
3165         }
3166
3167         if ((from_yaml || from_copy) &&
3168             (setstripe_args_specified(&lsa) || layout != NULL)) {
3169                 fprintf(stderr, "error: %s: can't specify --yaml with "
3170                         "-c, -S, -i, -o, -p or -E options.\n",
3171                         argv[0]);
3172                 goto error;
3173         }
3174
3175         if ((migration_flags & MIGRATION_NONBLOCK) && migration_block) {
3176                 fprintf(stderr,
3177                         "%s %s: options --non-block and --block are mutually exclusive\n",
3178                         progname, argv[0]);
3179                 goto usage_error;
3180         }
3181
3182         if (!comp_del && !comp_set && (opc != SO_MIRROR_SPLIT) &&
3183             comp_id != 0) {
3184                 fprintf(stderr,
3185                 "%s %s: option -I can only be used with --component-del or --component-set or lfs mirror split\n",
3186                         progname, argv[0]);
3187                 goto usage_error;
3188         }
3189
3190         if (migrate_mdt_mode) {
3191                 struct lmv_user_md *lmu;
3192
3193                 /* initialize migrate mdt parameters */
3194                 lmu = calloc(1, lmv_user_md_size(lsa.lsa_nr_tgts,
3195                                                  LMV_USER_MAGIC_SPECIFIC));
3196                 if (!lmu) {
3197                         fprintf(stderr,
3198                                 "%s %s: cannot allocate memory for lmv_user_md: %s\n",
3199                                 progname, argv[0], strerror(ENOMEM));
3200                         result = -ENOMEM;
3201                         goto error;
3202                 }
3203                 if (lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT)
3204                         lmu->lum_stripe_count = lsa.lsa_stripe_count;
3205                 if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT) {
3206                         fprintf(stderr,
3207                                 "%s %s: migrate should specify MDT index\n",
3208                                 progname, argv[0]);
3209                         free(lmu);
3210                         goto usage_error;
3211                 }
3212                 lmu->lum_stripe_offset = lsa.lsa_stripe_off;
3213                 if (lsa.lsa_pattern != LLAPI_LAYOUT_RAID0)
3214                         lmu->lum_hash_type = lsa.lsa_pattern;
3215                 else
3216                         lmu->lum_hash_type = LMV_HASH_TYPE_FNV_1A_64;
3217                 if (lsa.lsa_pool_name)
3218                         strncpy(lmu->lum_pool_name, lsa.lsa_pool_name,
3219                                 sizeof(lmu->lum_pool_name));
3220                 if (lsa.lsa_nr_tgts > 1) {
3221                         int i;
3222
3223                         if (lsa.lsa_stripe_count > 0 &&
3224                             lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT &&
3225                             lsa.lsa_stripe_count != lsa.lsa_nr_tgts) {
3226                                 fprintf(stderr,
3227                                         "error: %s: stripe count %lld doesn't match the number of MDTs: %d\n",
3228                                         progname, lsa.lsa_stripe_count,
3229                                                 lsa.lsa_nr_tgts);
3230                                 free(lmu);
3231                                 goto usage_error;
3232                         }
3233
3234                         lmu->lum_magic = LMV_USER_MAGIC_SPECIFIC;
3235                         lmu->lum_stripe_count = lsa.lsa_nr_tgts;
3236                         for (i = 0; i < lsa.lsa_nr_tgts; i++)
3237                                 lmu->lum_objects[i].lum_mds = lsa.lsa_tgts[i];
3238                 } else {
3239                         lmu->lum_magic = LMV_USER_MAGIC;
3240                 }
3241
3242                 migrate_mdt_param.fp_lmv_md = lmu;
3243                 migrate_mdt_param.fp_migrate = 1;
3244         } else if (layout == NULL) {
3245                 /* initialize stripe parameters */
3246                 param = calloc(1, offsetof(typeof(*param),
3247                                lsp_osts[lsa.lsa_nr_tgts]));
3248                 if (param == NULL) {
3249                         fprintf(stderr,
3250                                 "%s %s: cannot allocate memory for parameters: %s\n",
3251                                 progname, argv[0], strerror(ENOMEM));
3252                         result = -ENOMEM;
3253                         goto error;
3254                 }
3255
3256                 if (lsa.lsa_stripe_size != LLAPI_LAYOUT_DEFAULT)
3257                         param->lsp_stripe_size = lsa.lsa_stripe_size;
3258                 if (lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT) {
3259                         if (lsa.lsa_stripe_count == LLAPI_LAYOUT_WIDE)
3260                                 param->lsp_stripe_count = -1;
3261                         else
3262                                 param->lsp_stripe_count = lsa.lsa_stripe_count;
3263                 }
3264                 if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
3265                         param->lsp_stripe_offset = -1;
3266                 else
3267                         param->lsp_stripe_offset = lsa.lsa_stripe_off;
3268                 param->lsp_pool = lsa.lsa_pool_name;
3269                 param->lsp_is_specific = false;
3270                 if (lsa.lsa_nr_tgts > 0) {
3271                         if (lsa.lsa_stripe_count > 0 &&
3272                             lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT &&
3273                             lsa.lsa_stripe_count != LLAPI_LAYOUT_WIDE &&
3274                             lsa.lsa_nr_tgts != lsa.lsa_stripe_count) {
3275                                 fprintf(stderr, "error: %s: stripe count %lld "
3276                                         "doesn't match the number of OSTs: %d\n"
3277                                         , argv[0], lsa.lsa_stripe_count,
3278                                         lsa.lsa_nr_tgts);
3279                                 free(param);
3280                                 goto usage_error;
3281                         }
3282
3283                         param->lsp_is_specific = true;
3284                         param->lsp_stripe_count = lsa.lsa_nr_tgts;
3285                         memcpy(param->lsp_osts, tgts,
3286                                sizeof(*tgts) * lsa.lsa_nr_tgts);
3287                 }
3288         }
3289
3290         if (from_yaml) {
3291                 /* generate a layout from a YAML template */
3292                 result = lfs_comp_create_from_yaml(template, &layout,
3293                                                    &lsa, tgts);
3294                 if (result) {
3295                         fprintf(stderr, "error: %s: can't create composite "
3296                                 "layout from template file %s\n",
3297                                 argv[0], template);
3298                         goto error;
3299                 }
3300         } else if (from_copy) {
3301                 layout = llapi_layout_get_by_path(template, 0);
3302                 if (layout == NULL) {
3303                         fprintf(stderr,
3304                             "%s: can't create composite layout from file %s.\n",
3305                                 progname, template);
3306                         goto error;
3307                 }
3308         }
3309
3310         for (fname = argv[optind]; fname != NULL; fname = argv[++optind]) {
3311                 if (migrate_mdt_mode) {
3312                         result = llapi_migrate_mdt(fname, &migrate_mdt_param);
3313                 } else if (migrate_mode) {
3314                         result = lfs_migrate(fname, migration_flags, param,
3315                                              layout);
3316                 } else if (comp_set != 0) {
3317                         result = lfs_component_set(fname, comp_id,
3318                                                    lsa.lsa_comp_flags,
3319                                                    lsa.lsa_comp_neg_flags);
3320                 } else if (comp_del != 0) {
3321                         result = lfs_component_del(fname, comp_id,
3322                                                    lsa.lsa_comp_flags,
3323                                                    lsa.lsa_comp_neg_flags);
3324                 } else if (comp_add != 0) {
3325                         result = lfs_component_add(fname, layout);
3326                 } else if (opc == SO_MIRROR_CREATE) {
3327                         result = mirror_create(fname, mirror_list);
3328                 } else if (opc == SO_MIRROR_EXTEND) {
3329                         result = mirror_extend(fname, mirror_list,
3330                                                mirror_flags);
3331                 } else if (opc == SO_MIRROR_SPLIT) {
3332                         if (mirror_id == 0 && comp_id == 0) {
3333                                 fprintf(stderr,
3334                         "%s %s: no mirror id or component id is specified\n",
3335                                         progname, argv[0]);
3336                                 goto usage_error;
3337                         }
3338                         if (mirror_id != 0)
3339                                 comp_id = mirror_id;
3340                         else
3341                                 mirror_flags |= MF_COMP_ID;
3342                         result = mirror_split(fname, comp_id, mirror_flags,
3343                                               has_m_file ? mirror_list->m_file :
3344                                               NULL);
3345                 } else if (layout != NULL) {
3346                         result = lfs_component_create(fname, O_CREAT | O_WRONLY,
3347                                                       0666, layout);
3348                         if (result >= 0) {
3349                                 close(result);
3350                                 result = 0;
3351                         }
3352                 } else {
3353                         result = llapi_file_open_param(fname,
3354                                                        O_CREAT | O_WRONLY,
3355                                                        0666, param);
3356                         if (result >= 0) {
3357                                 close(result);
3358                                 result = 0;
3359                         }
3360                 }
3361                 if (result) {
3362                         /* Save the first error encountered. */
3363                         if (result2 == 0)
3364                                 result2 = result;
3365                         continue;
3366                 }
3367         }
3368
3369         free(param);
3370         free(migrate_mdt_param.fp_lmv_md);
3371         llapi_layout_free(layout);
3372         lfs_mirror_list_free(mirror_list);
3373         return result2;
3374 usage_error:
3375         result = CMD_HELP;
3376 error:
3377         llapi_layout_free(layout);
3378         lfs_mirror_list_free(mirror_list);
3379         return result;
3380 }
3381
3382 static int lfs_poollist(int argc, char **argv)
3383 {
3384         if (argc != 2)
3385                 return CMD_HELP;
3386
3387         return llapi_poollist(argv[1]);
3388 }
3389
3390 static int set_time(time_t *time, time_t *set, char *str)
3391 {
3392         time_t t;
3393         int res = 0;
3394         char *endptr;
3395
3396         if (str[0] == '+')
3397                 res = 1;
3398         else if (str[0] == '-')
3399                 res = -1;
3400
3401         if (res)
3402                 str++;
3403
3404         t = strtol(str, &endptr, 0);
3405         if (*endptr != '\0') {
3406                 fprintf(stderr,
3407                         "%s find: bad time '%s': %s\n",
3408                         progname, str, strerror(EINVAL));
3409                 return INT_MAX;
3410         }
3411         if (*time < t * 24 * 60 * 60) {
3412                 if (res != 0)
3413                         str--;
3414                 fprintf(stderr,
3415                         "%s find: bad time '%s': too large\n",
3416                         progname, str);
3417                 return INT_MAX;
3418         }
3419
3420         *set = *time - t * 24 * 60 * 60;
3421         return res;
3422 }
3423
3424 static int name2uid(unsigned int *id, const char *name)
3425 {
3426         struct passwd *passwd;
3427
3428         passwd = getpwnam(name);
3429         if (passwd == NULL)
3430                 return -ENOENT;
3431         *id = passwd->pw_uid;
3432
3433         return 0;
3434 }
3435
3436 static int name2gid(unsigned int *id, const char *name)
3437 {
3438         struct group *group;
3439
3440         group = getgrnam(name);
3441         if (group == NULL)
3442                 return -ENOENT;
3443         *id = group->gr_gid;
3444
3445         return 0;
3446 }
3447
3448 static inline int name2projid(unsigned int *id, const char *name)
3449 {
3450         return -ENOTSUP;
3451 }
3452
3453 static int uid2name(char **name, unsigned int id)
3454 {
3455         struct passwd *passwd;
3456
3457         passwd = getpwuid(id);
3458         if (passwd == NULL)
3459                 return -ENOENT;
3460         *name = passwd->pw_name;
3461
3462         return 0;
3463 }
3464
3465 static inline int gid2name(char **name, unsigned int id)
3466 {
3467         struct group *group;
3468
3469         group = getgrgid(id);
3470         if (group == NULL)
3471                 return -ENOENT;
3472         *name = group->gr_name;
3473
3474         return 0;
3475 }
3476
3477 static int name2layout(__u32 *layout, char *name)
3478 {
3479         char *ptr, *layout_name;
3480
3481         *layout = 0;
3482         for (ptr = name; ; ptr = NULL) {
3483                 layout_name = strtok(ptr, ",");
3484                 if (layout_name == NULL)
3485                         break;
3486                 if (strcmp(layout_name, "released") == 0)
3487                         *layout |= LOV_PATTERN_F_RELEASED;
3488                 else if (strcmp(layout_name, "raid0") == 0)
3489                         *layout |= LOV_PATTERN_RAID0;
3490                 else if (strcmp(layout_name, "mdt") == 0)
3491                         *layout |= LOV_PATTERN_MDT;
3492                 else
3493                         return -1;
3494         }
3495         return 0;
3496 }
3497
3498 static int lfs_find(int argc, char **argv)
3499 {
3500         int c, rc;
3501         int ret = 0;
3502         time_t t;
3503         struct find_param param = {
3504                 .fp_max_depth = -1,
3505                 .fp_quiet = 1,
3506         };
3507         struct option long_opts[] = {
3508         { .val = 'A',   .name = "atime",        .has_arg = required_argument },
3509         { .val = 'b',   .name = "blocks",       .has_arg = required_argument },
3510         { .val = LFS_COMP_COUNT_OPT,
3511                         .name = "comp-count",   .has_arg = required_argument },
3512         { .val = LFS_COMP_COUNT_OPT,
3513                         .name = "component-count",
3514                                                 .has_arg = required_argument },
3515         { .val = LFS_COMP_FLAGS_OPT,
3516                         .name = "comp-flags",   .has_arg = required_argument },
3517         { .val = LFS_COMP_FLAGS_OPT,
3518                         .name = "component-flags",
3519                                                 .has_arg = required_argument },
3520         { .val = LFS_COMP_START_OPT,
3521                         .name = "comp-start",   .has_arg = required_argument },
3522         { .val = LFS_COMP_START_OPT,
3523                         .name = "component-start",
3524                                                 .has_arg = required_argument },
3525         { .val = LFS_MIRROR_STATE_OPT,
3526                         .name = "mirror-state", .has_arg = required_argument },
3527         { .val = 'c',   .name = "stripe-count", .has_arg = required_argument },
3528         { .val = 'c',   .name = "stripe_count", .has_arg = required_argument },
3529         { .val = 'C',   .name = "ctime",        .has_arg = required_argument },
3530 /* getstripe { .val = 'd', .name = "directory", .has_arg = no_argument }, */
3531         { .val = 'D',   .name = "maxdepth",     .has_arg = required_argument },
3532         { .val = 'E',   .name = "comp-end",     .has_arg = required_argument },
3533         { .val = 'E',   .name = "component-end",
3534                                                 .has_arg = required_argument },
3535 /* find { .val = 'F',   .name = "fid",          .has_arg = no_argument }, */
3536         { .val = 'g',   .name = "gid",          .has_arg = required_argument },
3537         { .val = 'G',   .name = "group",        .has_arg = required_argument },
3538         { .val = 'H',   .name = "mdt-hash",     .has_arg = required_argument },
3539         { .val = 'i',   .name = "stripe-index", .has_arg = required_argument },
3540         { .val = 'i',   .name = "stripe_index", .has_arg = required_argument },
3541 /* getstripe { .val = 'I', .name = "comp-id",   .has_arg = required_argument }*/
3542         { .val = 'L',   .name = "layout",       .has_arg = required_argument },
3543         { .val = 'm',   .name = "mdt",          .has_arg = required_argument },
3544         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument },
3545         { .val = 'm',   .name = "mdt_index",    .has_arg = required_argument },
3546         { .val = 'M',   .name = "mtime",        .has_arg = required_argument },
3547         { .val = 'n',   .name = "name",         .has_arg = required_argument },
3548         { .val = 'N',   .name = "mirror-count", .has_arg = required_argument },
3549 /* find { .val = 'o'    .name = "or", .has_arg = no_argument }, like find(1) */
3550         { .val = 'O',   .name = "obd",          .has_arg = required_argument },
3551         { .val = 'O',   .name = "ost",          .has_arg = required_argument },
3552         /* no short option for pool yet, can be 'p' after 2.18 */
3553         { .val = LFS_POOL_OPT,
3554                         .name = "pool",         .has_arg = required_argument },
3555         { .val = '0',   .name = "print0",       .has_arg = no_argument },
3556         { .val = 'P',   .name = "print",        .has_arg = no_argument },
3557         { .val = LFS_PROJID_OPT,
3558                         .name = "projid",       .has_arg = required_argument },
3559 /* getstripe { .val = 'q', .name = "quiet",     .has_arg = no_argument }, */
3560 /* getstripe { .val = 'r', .name = "recursive", .has_arg = no_argument }, */
3561 /* getstripe { .val = 'R', .name = "raw",       .has_arg = no_argument }, */
3562         { .val = 's',   .name = "size",         .has_arg = required_argument },
3563         { .val = 'S',   .name = "stripe-size",  .has_arg = required_argument },
3564         { .val = 'S',   .name = "stripe_size",  .has_arg = required_argument },
3565         { .val = 't',   .name = "type",         .has_arg = required_argument },
3566         { .val = 'T',   .name = "mdt-count",    .has_arg = required_argument },
3567         { .val = 'u',   .name = "uid",          .has_arg = required_argument },
3568         { .val = 'U',   .name = "user",         .has_arg = required_argument },
3569 /* getstripe { .val = 'v', .name = "verbose",   .has_arg = no_argument }, */
3570 /* getstripe { .val = 'y', .name = "yaml",      .has_arg = no_argument }, */
3571         { .name = NULL } };
3572         int pathstart = -1;
3573         int pathend = -1;
3574         int neg_opt = 0;
3575         time_t *xtime;
3576         int *xsign;
3577         int isoption;
3578         char *endptr;
3579
3580         time(&t);
3581
3582         /* when getopt_long_only() hits '!' it returns 1, puts "!" in optarg */
3583         while ((c = getopt_long_only(argc, argv,
3584                         "-0A:b:c:C:D:E:g:G:H:i:L:m:M:n:N:O:Ppqrs:S:t:T:u:U:v",
3585                         long_opts, NULL)) >= 0) {
3586                 xtime = NULL;
3587                 xsign = NULL;
3588                 if (neg_opt)
3589                         --neg_opt;
3590                 /* '!' is part of option */
3591                 /* when getopt_long_only() finds a string which is not
3592                  * an option nor a known option argument it returns 1
3593                  * in that case if we already have found pathstart and pathend
3594                  * (i.e. we have the list of pathnames),
3595                  * the only supported value is "!"
3596                  */
3597                 isoption = (c != 1) || (strcmp(optarg, "!") == 0);
3598                 if (!isoption && pathend != -1) {
3599                         fprintf(stderr, "err: %s: filename|dirname must either "
3600                                         "precede options or follow options\n",
3601                                         argv[0]);
3602                         ret = CMD_HELP;
3603                         goto err;
3604                 }
3605                 if (!isoption && pathstart == -1)
3606                         pathstart = optind - 1;
3607                 if (isoption && pathstart != -1 && pathend == -1)
3608                         pathend = optind - 2;
3609                 switch (c) {
3610                 case 0:
3611                         /* Long options. */
3612                         break;
3613                 case 1:
3614                         /* unknown; opt is "!" or path component,
3615                          * checking done above.
3616                          */
3617                         if (strcmp(optarg, "!") == 0)
3618                                 neg_opt = 2;
3619                         break;
3620                 case 'A':
3621                         xtime = &param.fp_atime;
3622                         xsign = &param.fp_asign;
3623                         param.fp_exclude_atime = !!neg_opt;
3624                         /* no break, this falls through to 'C' for ctime */
3625                 case 'C':
3626                         if (c == 'C') {
3627                                 xtime = &param.fp_ctime;
3628                                 xsign = &param.fp_csign;
3629                                 param.fp_exclude_ctime = !!neg_opt;
3630                         }
3631                         /* no break, this falls through to 'M' for mtime */
3632                 case 'M':
3633                         if (c == 'M') {
3634                                 xtime = &param.fp_mtime;
3635                                 xsign = &param.fp_msign;
3636                                 param.fp_exclude_mtime = !!neg_opt;
3637                         }
3638                         rc = set_time(&t, xtime, optarg);
3639                         if (rc == INT_MAX) {
3640                                 ret = -1;
3641                                 goto err;
3642                         }
3643                         if (rc)
3644                                 *xsign = rc;
3645                         break;
3646                 case 'b':
3647                         if (optarg[0] == '+') {
3648                                 param.fp_blocks_sign = -1;
3649                                 optarg++;
3650                         } else if (optarg[0] == '-') {
3651                                 param.fp_blocks_sign =  1;
3652                                 optarg++;
3653                         }
3654
3655                         param.fp_blocks_units = 1024;
3656                         ret = llapi_parse_size(optarg, &param.fp_blocks,
3657                                                &param.fp_blocks_units, 0);
3658                         if (ret) {
3659                                 fprintf(stderr, "error: bad blocks '%s'\n",
3660                                         optarg);
3661                                 goto err;
3662                         }
3663                         param.fp_check_blocks = 1;
3664                         param.fp_exclude_blocks = !!neg_opt;
3665                         break;
3666                 case LFS_COMP_COUNT_OPT:
3667                         if (optarg[0] == '+') {
3668                                 param.fp_comp_count_sign = -1;
3669                                 optarg++;
3670                         } else if (optarg[0] == '-') {
3671                                 param.fp_comp_count_sign =  1;
3672                                 optarg++;
3673                         }
3674
3675                         param.fp_comp_count = strtoul(optarg, &endptr, 0);
3676                         if (*endptr != '\0') {
3677                                 fprintf(stderr, "error: bad component count "
3678                                         "'%s'\n", optarg);
3679                                 goto err;
3680                         }
3681                         param.fp_check_comp_count = 1;
3682                         param.fp_exclude_comp_count = !!neg_opt;
3683                         break;
3684                 case LFS_COMP_FLAGS_OPT:
3685                         rc = comp_str2flags(optarg, &param.fp_comp_flags,
3686                                             &param.fp_comp_neg_flags);
3687                         if (rc) {
3688                                 fprintf(stderr, "error: bad component flags "
3689                                         "'%s'\n", optarg);
3690                                 goto err;
3691                         }
3692                         param.fp_check_comp_flags = 1;
3693                         if (neg_opt) {
3694                                 __u32 flags = param.fp_comp_neg_flags;
3695                                 param.fp_comp_neg_flags = param.fp_comp_flags;
3696                                 param.fp_comp_flags = flags;
3697                         }
3698                         break;
3699                 case LFS_COMP_START_OPT:
3700                         if (optarg[0] == '+') {
3701                                 param.fp_comp_start_sign = -1;
3702                                 optarg++;
3703                         } else if (optarg[0] == '-') {
3704                                 param.fp_comp_start_sign =  1;
3705                                 optarg++;
3706                         }
3707
3708                         rc = llapi_parse_size(optarg, &param.fp_comp_start,
3709                                               &param.fp_comp_start_units, 0);
3710                         if (rc) {
3711                                 fprintf(stderr, "error: bad component start "
3712                                         "'%s'\n", optarg);
3713                                 goto err;
3714                         }
3715                         param.fp_check_comp_start = 1;
3716                         param.fp_exclude_comp_start = !!neg_opt;
3717                         break;
3718                 case LFS_MIRROR_STATE_OPT:
3719                         rc = mirror_str2state(optarg, &param.fp_mirror_state,
3720                                               &param.fp_mirror_neg_state);
3721                         if (rc) {
3722                                 fprintf(stderr,
3723                                         "error: bad mirrored file state '%s'\n",
3724                                         optarg);
3725                                 goto err;
3726                         }
3727                         param.fp_check_mirror_state = 1;
3728                         if (neg_opt) {
3729                                 __u16 state = param.fp_mirror_neg_state;
3730                                 param.fp_mirror_neg_state =
3731                                         param.fp_mirror_state;
3732                                 param.fp_mirror_state = state;
3733                         }
3734                         break;
3735                 case 'c':
3736                         if (optarg[0] == '+') {
3737                                 param.fp_stripe_count_sign = -1;
3738                                 optarg++;
3739                         } else if (optarg[0] == '-') {
3740                                 param.fp_stripe_count_sign =  1;
3741                                 optarg++;
3742                         }
3743
3744                         param.fp_stripe_count = strtoul(optarg, &endptr, 0);
3745                         if (*endptr != '\0') {
3746                                 fprintf(stderr,"error: bad stripe_count '%s'\n",
3747                                         optarg);
3748                                 ret = -1;
3749                                 goto err;
3750                         }
3751                         param.fp_check_stripe_count = 1;
3752                         param.fp_exclude_stripe_count = !!neg_opt;
3753                         break;
3754                 case 'D':
3755                         param.fp_max_depth = strtol(optarg, 0, 0);
3756                         break;
3757                 case 'E':
3758                         if (optarg[0] == '+') {
3759                                 param.fp_comp_end_sign = -1;
3760                                 optarg++;
3761                         } else if (optarg[0] == '-') {
3762                                 param.fp_comp_end_sign =  1;
3763                                 optarg++;
3764                         }
3765
3766                         if (arg_is_eof(optarg)) {
3767                                 param.fp_comp_end = LUSTRE_EOF;
3768                                 param.fp_comp_end_units = 1;
3769                                 rc = 0;
3770                         } else {
3771                                 rc = llapi_parse_size(optarg,
3772                                                 &param.fp_comp_end,
3773                                                 &param.fp_comp_end_units, 0);
3774                         }
3775                         if (rc) {
3776                                 fprintf(stderr, "error: bad component end "
3777                                         "'%s'\n", optarg);
3778                                 goto err;
3779                         }
3780                         param.fp_check_comp_end = 1;
3781                         param.fp_exclude_comp_end = !!neg_opt;
3782                         break;
3783                 case 'g':
3784                 case 'G':
3785                         rc = name2gid(&param.fp_gid, optarg);
3786                         if (rc) {
3787                                 param.fp_gid = strtoul(optarg, &endptr, 10);
3788                                 if (*endptr != '\0') {
3789                                         fprintf(stderr, "Group/GID: %s cannot "
3790                                                 "be found.\n", optarg);
3791                                         ret = -1;
3792                                         goto err;
3793                                 }
3794                         }
3795                         param.fp_exclude_gid = !!neg_opt;
3796                         param.fp_check_gid = 1;
3797                         break;
3798                 case 'H':
3799                         param.fp_hash_type = check_hashtype(optarg);
3800                         if (param.fp_hash_type == 0) {
3801                                 fprintf(stderr, "error: bad hash_type '%s'\n",
3802                                         optarg);
3803                                 ret = -1;
3804                                 goto err;
3805                         }
3806                         param.fp_check_hash_type = 1;
3807                         param.fp_exclude_hash_type = !!neg_opt;
3808                         break;
3809                 case 'L':
3810                         ret = name2layout(&param.fp_layout, optarg);
3811                         if (ret)
3812                                 goto err;
3813                         param.fp_exclude_layout = !!neg_opt;
3814                         param.fp_check_layout = 1;
3815                         break;
3816                 case 'u':
3817                 case 'U':
3818                         rc = name2uid(&param.fp_uid, optarg);
3819                         if (rc) {
3820                                 param.fp_uid = strtoul(optarg, &endptr, 10);
3821                                 if (*endptr != '\0') {
3822                                         fprintf(stderr, "User/UID: %s cannot "
3823                                                 "be found.\n", optarg);
3824                                         ret = -1;
3825                                         goto err;
3826                                 }
3827                         }
3828                         param.fp_exclude_uid = !!neg_opt;
3829                         param.fp_check_uid = 1;
3830                         break;
3831                 case 'n':
3832                         param.fp_pattern = (char *)optarg;
3833                         param.fp_exclude_pattern = !!neg_opt;
3834                         break;
3835                 case 'N':
3836                         if (optarg[0] == '+') {
3837                                 param.fp_mirror_count_sign = -1;
3838                                 optarg++;
3839                         } else if (optarg[0] == '-') {
3840                                 param.fp_mirror_count_sign =  1;
3841                                 optarg++;
3842                         }
3843
3844                         param.fp_mirror_count = strtoul(optarg, &endptr, 0);
3845                         if (*endptr != '\0') {
3846                                 fprintf(stderr,
3847                                         "error: bad mirror count '%s'\n",
3848                                         optarg);
3849                                 goto err;
3850                         }
3851                         param.fp_check_mirror_count = 1;
3852                         param.fp_exclude_mirror_count = !!neg_opt;
3853                         break;
3854                 case 'm':
3855                 case 'i':
3856                 case 'O': {
3857                         char *buf, *token, *next, *p;
3858                         int len = 1;
3859                         void *tmp;
3860
3861                         buf = strdup(optarg);
3862                         if (buf == NULL) {
3863                                 ret = -ENOMEM;
3864                                 goto err;
3865                         }
3866
3867                         param.fp_exclude_obd = !!neg_opt;
3868
3869                         token = buf;
3870                         while (token && *token) {
3871                                 token = strchr(token, ',');
3872                                 if (token) {
3873                                         len++;
3874                                         token++;
3875                                 }
3876                         }
3877                         if (c == 'm') {
3878                                 param.fp_exclude_mdt = !!neg_opt;
3879                                 param.fp_num_alloc_mdts += len;
3880                                 tmp = realloc(param.fp_mdt_uuid,
3881                                               param.fp_num_alloc_mdts *
3882                                               sizeof(*param.fp_mdt_uuid));
3883                                 if (tmp == NULL) {
3884                                         ret = -ENOMEM;
3885                                         goto err_free;
3886                                 }
3887
3888                                 param.fp_mdt_uuid = tmp;
3889                         } else {
3890                                 param.fp_exclude_obd = !!neg_opt;
3891                                 param.fp_num_alloc_obds += len;
3892                                 tmp = realloc(param.fp_obd_uuid,
3893                                               param.fp_num_alloc_obds *
3894                                               sizeof(*param.fp_obd_uuid));
3895                                 if (tmp == NULL) {
3896                                         ret = -ENOMEM;
3897                                         goto err_free;
3898                                 }
3899
3900                                 param.fp_obd_uuid = tmp;
3901                         }
3902                         for (token = buf; token && *token; token = next) {
3903                                 struct obd_uuid *puuid;
3904                                 if (c == 'm') {
3905                                         puuid =
3906                                         &param.fp_mdt_uuid[param.fp_num_mdts++];
3907                                 } else {
3908                                         puuid =
3909                                         &param.fp_obd_uuid[param.fp_num_obds++];
3910                                 }
3911                                 p = strchr(token, ',');
3912                                 next = 0;
3913                                 if (p) {
3914                                         *p = 0;
3915                                         next = p+1;
3916                                 }
3917
3918                                 if (strlen(token) > sizeof(puuid->uuid) - 1) {
3919                                         ret = -E2BIG;
3920                                         goto err_free;
3921                                 }
3922
3923                                 strncpy(puuid->uuid, token,
3924                                         sizeof(puuid->uuid));
3925                         }
3926 err_free:
3927                         if (buf)
3928                                 free(buf);
3929                         break;
3930                 }
3931 #if LUSTRE_VERSION_CODE >= OBD_OCD_VERSION(2, 18, 53, 0)
3932                 case 'p':
3933 #endif
3934                 case LFS_POOL_OPT:
3935                         if (strlen(optarg) > LOV_MAXPOOLNAME) {
3936                                 fprintf(stderr,
3937                                         "Pool name %s is too long (max %d)\n",
3938                                         optarg, LOV_MAXPOOLNAME);
3939                                 ret = -1;
3940                                 goto err;
3941                         }
3942                         /*
3943                          * We do check for empty pool because empty pool
3944                          * is used to find V1 LOV attributes
3945                          */
3946                         strncpy(param.fp_poolname, optarg, LOV_MAXPOOLNAME);
3947                         param.fp_poolname[LOV_MAXPOOLNAME] = '\0';
3948                         param.fp_exclude_pool = !!neg_opt;
3949                         param.fp_check_pool = 1;
3950                         break;
3951 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 14, 53, 0)
3952                 case 'p': /* want this for --pool, to match getstripe/find */
3953                         fprintf(stderr,
3954                                 "warning: -p deprecated, use --print0 or -0\n");
3955 #endif
3956                 case '0':
3957                         param.fp_zero_end = 1;
3958                         break;
3959                 case 'P': /* we always print, this option is a no-op */
3960                         break;
3961                 case LFS_PROJID_OPT:
3962                         rc = name2projid(&param.fp_projid, optarg);
3963                         if (rc) {
3964                                 param.fp_projid = strtoul(optarg, &endptr, 10);
3965                                 if (*endptr != '\0') {
3966                                         fprintf(stderr,
3967                                                 "Invalid project ID: %s",
3968                                                 optarg);
3969                                         ret = -1;
3970                                         goto err;
3971                                 }
3972                         }
3973                         param.fp_exclude_projid = !!neg_opt;
3974                         param.fp_check_projid = 1;
3975                         break;
3976                 case 's':
3977                         if (optarg[0] == '+') {
3978                                 param.fp_size_sign = -1;
3979                                 optarg++;
3980                         } else if (optarg[0] == '-') {
3981                                 param.fp_size_sign =  1;
3982                                 optarg++;
3983                         }
3984
3985                         ret = llapi_parse_size(optarg, &param.fp_size,
3986                                                &param.fp_size_units, 0);
3987                         if (ret) {
3988                                 fprintf(stderr, "error: bad file size '%s'\n",
3989                                         optarg);
3990                                 goto err;
3991                         }
3992                         param.fp_check_size = 1;
3993                         param.fp_exclude_size = !!neg_opt;
3994                         break;
3995                 case 'S':
3996                         if (optarg[0] == '+') {
3997                                 param.fp_stripe_size_sign = -1;
3998                                 optarg++;
3999                         } else if (optarg[0] == '-') {
4000                                 param.fp_stripe_size_sign =  1;
4001                                 optarg++;
4002                         }
4003
4004                         ret = llapi_parse_size(optarg, &param.fp_stripe_size,
4005                                                &param.fp_stripe_size_units, 0);
4006                         if (ret) {
4007                                 fprintf(stderr, "error: bad stripe_size '%s'\n",
4008                                         optarg);
4009                                 goto err;
4010                         }
4011                         param.fp_check_stripe_size = 1;
4012                         param.fp_exclude_stripe_size = !!neg_opt;
4013                         break;
4014                 case 't':
4015                         param.fp_exclude_type = !!neg_opt;
4016                         switch (optarg[0]) {
4017                         case 'b':
4018                                 param.fp_type = S_IFBLK;
4019                                 break;
4020                         case 'c':
4021                                 param.fp_type = S_IFCHR;
4022                                 break;
4023                         case 'd':
4024                                 param.fp_type = S_IFDIR;
4025                                 break;
4026                         case 'f':
4027                                 param.fp_type = S_IFREG;
4028                                 break;
4029                         case 'l':
4030                                 param.fp_type = S_IFLNK;
4031                                 break;
4032                         case 'p':
4033                                 param.fp_type = S_IFIFO;
4034                                 break;
4035                         case 's':
4036                                 param.fp_type = S_IFSOCK;
4037                                 break;
4038                         default:
4039                                 fprintf(stderr, "error: %s: bad type '%s'\n",
4040                                         argv[0], optarg);
4041                                 ret = CMD_HELP;
4042                                 goto err;
4043                         };
4044                         break;
4045                 case 'T':
4046                         if (optarg[0] == '+') {
4047                                 param.fp_mdt_count_sign = -1;
4048                                 optarg++;
4049                         } else if (optarg[0] == '-') {
4050                                 param.fp_mdt_count_sign =  1;
4051                                 optarg++;
4052                         }
4053
4054                         param.fp_mdt_count = strtoul(optarg, &endptr, 0);
4055                         if (*endptr != '\0') {
4056                                 fprintf(stderr, "error: bad mdt_count '%s'\n",
4057                                         optarg);
4058                                 ret = -1;
4059                                 goto err;
4060                         }
4061                         param.fp_check_mdt_count = 1;
4062                         param.fp_exclude_mdt_count = !!neg_opt;
4063                         break;
4064                 default:
4065                         ret = CMD_HELP;
4066                         goto err;
4067                 };
4068         }
4069
4070         if (pathstart == -1) {
4071                 fprintf(stderr, "error: %s: no filename|pathname\n",
4072                         argv[0]);
4073                 ret = CMD_HELP;
4074                 goto err;
4075         } else if (pathend == -1) {
4076                 /* no options */
4077                 pathend = argc;
4078         }
4079
4080         do {
4081                 rc = llapi_find(argv[pathstart], &param);
4082                 if (rc != 0 && ret == 0)
4083                         ret = rc;
4084         } while (++pathstart < pathend);
4085
4086         if (ret)
4087                 fprintf(stderr, "error: %s failed for %s.\n",
4088                         argv[0], argv[optind - 1]);
4089 err:
4090         if (param.fp_obd_uuid && param.fp_num_alloc_obds)
4091                 free(param.fp_obd_uuid);
4092
4093         if (param.fp_mdt_uuid && param.fp_num_alloc_mdts)
4094                 free(param.fp_mdt_uuid);
4095
4096         return ret;
4097 }
4098
4099 static int lfs_getstripe_internal(int argc, char **argv,
4100                                   struct find_param *param)
4101 {
4102         struct option long_opts[] = {
4103 /* find { .val = 'A',   .name = "atime",        .has_arg = required_argument }*/
4104 /* find { .val = 'b',   .name = "blocks",       .has_arg = required_argument }*/
4105         { .val = LFS_COMP_COUNT_OPT,
4106                         .name = "comp-count",   .has_arg = no_argument },
4107         { .val = LFS_COMP_COUNT_OPT,
4108                 .name = "component-count",      .has_arg = no_argument },
4109         { .val = LFS_COMP_FLAGS_OPT,
4110                         .name = "comp-flags",   .has_arg = optional_argument },
4111         { .val = LFS_COMP_FLAGS_OPT,
4112                 .name = "component-flags",      .has_arg = optional_argument },
4113         { .val = LFS_COMP_START_OPT,
4114                         .name = "comp-start",   .has_arg = optional_argument },
4115         { .val = LFS_COMP_START_OPT,
4116                 .name = "component-start",      .has_arg = optional_argument },
4117         { .val = LFS_MIRROR_INDEX_OPT,
4118                 .name = "mirror-index",         .has_arg = required_argument },
4119         { .val = LFS_MIRROR_ID_OPT,
4120                 .name = "mirror-id",            .has_arg = required_argument },
4121         { .val = 'c',   .name = "stripe-count", .has_arg = no_argument },
4122         { .val = 'c',   .name = "stripe_count", .has_arg = no_argument },
4123 /* find { .val = 'C',   .name = "ctime",        .has_arg = required_argument }*/
4124         { .val = 'd',   .name = "directory",    .has_arg = no_argument },
4125         { .val = 'D',   .name = "default",      .has_arg = no_argument },
4126         { .val = 'E',   .name = "comp-end",     .has_arg = optional_argument },
4127         { .val = 'E',   .name = "component-end", .has_arg = optional_argument },
4128         { .val = 'F',   .name = "fid",          .has_arg = no_argument },
4129         { .val = 'g',   .name = "generation",   .has_arg = no_argument },
4130 /* find { .val = 'G',   .name = "group",        .has_arg = required_argument }*/
4131 /* dirstripe { .val = 'H', .name = "mdt-hash",  .has_arg = required_argument }*/
4132         { .val = 'i',   .name = "stripe-index", .has_arg = no_argument },
4133         { .val = 'i',   .name = "stripe_index", .has_arg = no_argument },
4134         { .val = 'I',   .name = "comp-id",      .has_arg = optional_argument },
4135         { .val = 'I',   .name = "component-id", .has_arg = optional_argument },
4136         { .val = 'L',   .name = "layout",       .has_arg = no_argument },
4137         { .val = 'm',   .name = "mdt",          .has_arg = no_argument },
4138         { .val = 'm',   .name = "mdt-index",    .has_arg = no_argument },
4139         { .val = 'm',   .name = "mdt_index",    .has_arg = no_argument },
4140 /* find { .val = 'M',   .name = "mtime",        .has_arg = required_argument }*/
4141 /* find { .val = 'n',   .name = "name",         .has_arg = required_argument }*/
4142         { .val = 'N',   .name = "mirror-count", .has_arg = no_argument },
4143         { .val = 'O',   .name = "obd",          .has_arg = required_argument },
4144         { .val = 'O',   .name = "ost",          .has_arg = required_argument },
4145         { .val = 'p',   .name = "pool",         .has_arg = no_argument },
4146 /* find { .val = 'P',   .name = "print",        .has_arg = no_argument }, */
4147         { .val = 'q',   .name = "quiet",        .has_arg = no_argument },
4148         { .val = 'r',   .name = "recursive",    .has_arg = no_argument },
4149         { .val = 'R',   .name = "raw",          .has_arg = no_argument },
4150         { .val = 'S',   .name = "stripe-size",  .has_arg = no_argument },
4151         { .val = 'S',   .name = "stripe_size",  .has_arg = no_argument },
4152 /* find { .val = 't',   .name = "type",         .has_arg = required_argument }*/
4153 /* dirstripe { .val = 'T', .name = "mdt-count", .has_arg = required_argument }*/
4154 /* find { .val = 'u',   .name = "uid",          .has_arg = required_argument }*/
4155 /* find { .val = 'U',   .name = "user",         .has_arg = required_argument }*/
4156         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
4157         { .val = 'y',   .name = "yaml",         .has_arg = no_argument },
4158         { .name = NULL } };
4159         int c, rc;
4160         int neg_opt = 0;
4161         int pathstart = -1, pathend = -1;
4162         int isoption;
4163         char *end, *tmp;
4164
4165         while ((c = getopt_long(argc, argv,
4166                         "-cdDE::FghiI::LmMNoO:pqrRsSvy",
4167                         long_opts, NULL)) != -1) {
4168                 if (neg_opt)
4169                         --neg_opt;
4170
4171                 /* '!' is part of option */
4172                 isoption = (c != 1) || (strcmp(optarg, "!") == 0);
4173                 if (!isoption && pathend != -1) {
4174                         fprintf(stderr,
4175                                 "error: %s: filename|dirname must either precede options or follow options\n",
4176                                 argv[0]);
4177                         return CMD_HELP;
4178                 }
4179                 if (!isoption && pathstart == -1)
4180                         pathstart = optind - 1;
4181                 if (isoption && pathstart != -1 && pathend == -1)
4182                         pathend = optind - 2;
4183
4184                 switch (c) {
4185                 case 1:
4186                         /* unknown: opt is "!" */
4187                         if (strcmp(optarg, "!") == 0)
4188                                 neg_opt = 2;
4189                         break;
4190                 case 'c':
4191                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
4192                                 param->fp_verbose |= VERBOSE_COUNT;
4193                                 param->fp_max_depth = 0;
4194                         }
4195                         break;
4196                 case LFS_COMP_COUNT_OPT:
4197                         param->fp_verbose |= VERBOSE_COMP_COUNT;
4198                         param->fp_max_depth = 0;
4199                         break;
4200                 case LFS_COMP_FLAGS_OPT:
4201                         if (optarg != NULL) {
4202                                 rc = comp_str2flags(optarg,
4203                                                     &param->fp_comp_flags,
4204                                                     &param->fp_comp_neg_flags);
4205                                 if (rc != 0) {
4206                                         fprintf(stderr, "error: %s bad "
4207                                                 "component flags '%s'.\n",
4208                                                 argv[0], optarg);
4209                                         return CMD_HELP;
4210                                 }
4211                                 param->fp_check_comp_flags = 1;
4212                         } else {
4213                                 param->fp_verbose |= VERBOSE_COMP_FLAGS;
4214                                 param->fp_max_depth = 0;
4215                         }
4216                         break;
4217                 case LFS_COMP_START_OPT:
4218                         if (optarg != NULL) {
4219                                 tmp = optarg;
4220                                 if (tmp[0] == '+') {
4221                                         param->fp_comp_start_sign = -1;
4222                                         tmp++;
4223                                 } else if (tmp[0] == '-') {
4224                                         param->fp_comp_start_sign = 1;
4225                                         tmp++;
4226                                 }
4227                                 rc = llapi_parse_size(tmp,
4228                                                 &param->fp_comp_start,
4229                                                 &param->fp_comp_start_units, 0);
4230                                 if (rc != 0) {
4231                                         fprintf(stderr, "error: %s bad "
4232                                                 "component start '%s'.\n",
4233                                                 argv[0], tmp);
4234                                         return CMD_HELP;
4235                                 } else {
4236                                         param->fp_check_comp_start = 1;
4237                                 }
4238                         } else {
4239                                 param->fp_verbose |= VERBOSE_COMP_START;
4240                                 param->fp_max_depth = 0;
4241                         }
4242                         break;
4243                 case LFS_MIRROR_INDEX_OPT:
4244                         if (optarg[0] == '+') {
4245                                 param->fp_mirror_index_sign = -1;
4246                                 optarg++;
4247                         } else if (optarg[0] == '-') {
4248                                 param->fp_mirror_index_sign = 1;
4249                                 optarg++;
4250                         }
4251
4252                         param->fp_mirror_index = strtoul(optarg, &end, 0);
4253                         if (*end != '\0' || (param->fp_mirror_index == 0 &&
4254                             param->fp_mirror_index_sign == 0 && neg_opt == 0)) {
4255                                 fprintf(stderr,
4256                                         "%s %s: invalid mirror index '%s'\n",
4257                                         progname, argv[0], optarg);
4258                                 return CMD_HELP;
4259                         }
4260                         if (param->fp_mirror_id != 0) {
4261                                 fprintf(stderr,
4262                                         "%s %s: can't specify both mirror index and mirror ID\n",
4263                                         progname, argv[0]);
4264                                 return CMD_HELP;
4265                         }
4266                         param->fp_check_mirror_index = 1;
4267                         param->fp_exclude_mirror_index = !!neg_opt;
4268                         break;
4269                 case LFS_MIRROR_ID_OPT:
4270                         if (optarg[0] == '+') {
4271                                 param->fp_mirror_id_sign = -1;
4272                                 optarg++;
4273                         } else if (optarg[0] == '-') {
4274                                 param->fp_mirror_id_sign = 1;
4275                                 optarg++;
4276                         }
4277
4278                         param->fp_mirror_id = strtoul(optarg, &end, 0);
4279                         if (*end != '\0' || (param->fp_mirror_id == 0 &&
4280                             param->fp_mirror_id_sign == 0 && neg_opt == 0)) {
4281                                 fprintf(stderr,
4282                                         "%s %s: invalid mirror ID '%s'\n",
4283                                         progname, argv[0], optarg);
4284                                 return CMD_HELP;
4285                         }
4286                         if (param->fp_mirror_index != 0) {
4287                                 fprintf(stderr,
4288                                         "%s %s: can't specify both mirror index and mirror ID\n",
4289                                         progname, argv[0]);
4290                                 return CMD_HELP;
4291                         }
4292                         param->fp_check_mirror_id = 1;
4293                         param->fp_exclude_mirror_id = !!neg_opt;
4294                         break;
4295                 case 'd':
4296                         param->fp_max_depth = 0;
4297                         break;
4298                 case 'D':
4299                         param->fp_get_default_lmv = 1;
4300                         break;
4301                 case 'E':
4302                         if (optarg != NULL) {
4303                                 tmp = optarg;
4304                                 if (tmp[0] == '+') {
4305                                         param->fp_comp_end_sign = -1;
4306                                         tmp++;
4307                                 } else if (tmp[0] == '-') {
4308                                         param->fp_comp_end_sign = 1;
4309                                         tmp++;
4310                                 }
4311
4312                                 if (arg_is_eof(tmp)) {
4313                                         param->fp_comp_end = LUSTRE_EOF;
4314                                         param->fp_comp_end_units = 1;
4315                                         rc = 0;
4316                                 } else {
4317                                         rc = llapi_parse_size(tmp,
4318                                                 &param->fp_comp_end,
4319                                                 &param->fp_comp_end_units, 0);
4320                                 }
4321                                 if (rc != 0) {
4322                                         fprintf(stderr, "error: %s bad "
4323                                                 "component end '%s'.\n",
4324                                                 argv[0], tmp);
4325                                         return CMD_HELP;
4326                                 }
4327                                 param->fp_check_comp_end = 1;
4328                         } else {
4329                                 param->fp_verbose |= VERBOSE_COMP_END;
4330                                 param->fp_max_depth = 0;
4331                         }
4332                         break;
4333                 case 'F':
4334                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
4335                                 param->fp_verbose |= VERBOSE_DFID;
4336                                 param->fp_max_depth = 0;
4337                         }
4338                         break;
4339                 case 'g':
4340                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
4341                                 param->fp_verbose |= VERBOSE_GENERATION;
4342                                 param->fp_max_depth = 0;
4343                         }
4344                         break;
4345                 case 'i':
4346                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
4347                                 param->fp_verbose |= VERBOSE_STRIPE_OFFSET;
4348                                 param->fp_max_depth = 0;
4349                         }
4350                         break;
4351                 case 'I':
4352                         if (optarg != NULL) {
4353                                 param->fp_comp_id = strtoul(optarg, &end, 0);
4354                                 if (*end != '\0' || param->fp_comp_id == 0 ||
4355                                     param->fp_comp_id > LCME_ID_MAX) {
4356                                         fprintf(stderr, "error: %s bad "
4357                                                 "component id '%s'\n",
4358                                                 argv[0], optarg);
4359                                         return CMD_HELP;
4360                                 } else {
4361                                         param->fp_check_comp_id = 1;
4362                                 }
4363                         } else {
4364                                 param->fp_max_depth = 0;
4365                                 param->fp_verbose |= VERBOSE_COMP_ID;
4366                         }
4367                         break;
4368                 case 'L':
4369                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
4370                                 param->fp_verbose |= VERBOSE_PATTERN;
4371                                 param->fp_max_depth = 0;
4372                         }
4373                         break;
4374 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
4375                 case 'M':
4376                         fprintf(stderr, "warning: '-M' deprecated"
4377                                 ", use '--mdt-index' or '-m' instead\n");
4378 #endif
4379                 case 'm':
4380                         if (!(param->fp_verbose & VERBOSE_DETAIL))
4381                                 param->fp_max_depth = 0;
4382                         param->fp_verbose |= VERBOSE_MDTINDEX;
4383                         break;
4384                 case 'N':
4385                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
4386                                 param->fp_verbose |= VERBOSE_MIRROR_COUNT;
4387                                 param->fp_max_depth = 0;
4388                         }
4389                         break;
4390                 case 'O':
4391                         if (param->fp_obd_uuid) {
4392                                 fprintf(stderr,
4393                                         "error: %s: only one obduuid allowed",
4394                                         argv[0]);
4395                                 return CMD_HELP;
4396                         }
4397                         param->fp_obd_uuid = (struct obd_uuid *)optarg;
4398                         break;
4399                 case 'p':
4400                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
4401                                 param->fp_verbose |= VERBOSE_POOL;
4402                                 param->fp_max_depth = 0;
4403                         }
4404                         break;
4405                 case 'q':
4406                         param->fp_quiet++;
4407                         break;
4408                 case 'r':
4409                         param->fp_recursive = 1;
4410                         break;
4411                 case 'R':
4412                         param->fp_raw = 1;
4413                         break;
4414                 case 'S':
4415                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
4416                                 param->fp_verbose |= VERBOSE_STRIPE_SIZE;
4417                                 param->fp_max_depth = 0;
4418                         }
4419                         break;
4420                 case 'v':
4421                         param->fp_verbose = VERBOSE_DEFAULT | VERBOSE_DETAIL;
4422                         break;
4423                 case 'y':
4424                         param->fp_yaml = 1;
4425                         break;
4426                 default:
4427                         return CMD_HELP;
4428                 }
4429         }
4430
4431         if (pathstart == -1) {
4432                 fprintf(stderr, "error: %s: no filename|pathname\n",
4433                                 argv[0]);
4434                 return CMD_HELP;
4435         } else if (pathend == -1) {
4436                 /* no options */
4437                 pathend = argc;
4438         }
4439
4440         if (pathend > argc)
4441                 return CMD_HELP;
4442
4443         if (param->fp_recursive)
4444                 param->fp_max_depth = -1;
4445         else if (param->fp_verbose & VERBOSE_DETAIL)
4446                 param->fp_max_depth = 1;
4447
4448         if (!param->fp_verbose)
4449                 param->fp_verbose = VERBOSE_DEFAULT;
4450         if (param->fp_quiet)
4451                 param->fp_verbose = VERBOSE_OBJID;
4452
4453         do {
4454                 rc = llapi_getstripe(argv[pathstart], param);
4455         } while (++pathstart < pathend && !rc);
4456
4457         if (rc)
4458                 fprintf(stderr, "error: %s failed for %s.\n",
4459                         argv[0], argv[optind - 1]);
4460         return rc;
4461 }
4462
4463 static int lfs_tgts(int argc, char **argv)
4464 {
4465         char mntdir[PATH_MAX] = {'\0'}, path[PATH_MAX] = {'\0'};
4466         struct find_param param;
4467         int index = 0, rc=0;
4468
4469         if (argc > 2)
4470                 return CMD_HELP;
4471
4472         if (argc == 2 && !realpath(argv[1], path)) {
4473                 rc = -errno;
4474                 fprintf(stderr, "error: invalid path '%s': %s\n",
4475                         argv[1], strerror(-rc));
4476                 return rc;
4477         }
4478
4479         while (!llapi_search_mounts(path, index++, mntdir, NULL)) {
4480                 /* Check if we have a mount point */
4481                 if (mntdir[0] == '\0')
4482                         continue;
4483
4484                 memset(&param, 0, sizeof(param));
4485                 if (!strcmp(argv[0], "mdts"))
4486                         param.fp_get_lmv = 1;
4487
4488                 rc = llapi_ostlist(mntdir, &param);
4489                 if (rc) {
4490                         fprintf(stderr, "error: %s: failed on %s\n",
4491                                 argv[0], mntdir);
4492                 }
4493                 if (path[0] != '\0')
4494                         break;
4495                 memset(mntdir, 0, PATH_MAX);
4496         }
4497
4498         return rc;
4499 }
4500
4501 static int lfs_getstripe(int argc, char **argv)
4502 {
4503         struct find_param param = { 0 };
4504
4505         param.fp_max_depth = 1;
4506         return lfs_getstripe_internal(argc, argv, &param);
4507 }
4508
4509 /* functions */
4510 static int lfs_getdirstripe(int argc, char **argv)
4511 {
4512         struct find_param param = { 0 };
4513         struct option long_opts[] = {
4514         { .val = 'c',   .name = "mdt-count",    .has_arg = no_argument },
4515         { .val = 'D',   .name = "default",      .has_arg = no_argument },
4516         { .val = 'H',   .name = "mdt-hash",     .has_arg = no_argument },
4517         { .val = 'i',   .name = "mdt-index",    .has_arg = no_argument },
4518         { .val = 'm',   .name = "mdt-index",    .has_arg = no_argument },
4519         { .val = 'O',   .name = "obd",          .has_arg = required_argument },
4520         { .val = 'r',   .name = "recursive",    .has_arg = no_argument },
4521         { .val = 'T',   .name = "mdt-count",    .has_arg = no_argument },
4522         { .val = 'y',   .name = "yaml",         .has_arg = no_argument },
4523         { .name = NULL } };
4524         int c, rc;
4525
4526         param.fp_get_lmv = 1;
4527
4528         while ((c = getopt_long(argc, argv,
4529                                 "cDHimO:rtTy", long_opts, NULL)) != -1)
4530         {
4531                 switch (c) {
4532                 case 'c':
4533                 case 'T':
4534                         param.fp_verbose |= VERBOSE_COUNT;
4535                         break;
4536                 case 'D':
4537                         param.fp_get_default_lmv = 1;
4538                         break;
4539                 case 'i':
4540                 case 'm':
4541                         param.fp_verbose |= VERBOSE_STRIPE_OFFSET;
4542                         break;
4543 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
4544                 case 't':
4545                         fprintf(stderr, "warning: '-t' deprecated, "
4546                                 "use '--mdt-hash' or '-H' instead\n");
4547 #endif
4548                 case 'H':
4549                         param.fp_verbose |= VERBOSE_HASH_TYPE;
4550                         break;
4551                 case 'O':
4552                         if (param.fp_obd_uuid) {
4553                                 fprintf(stderr,
4554                                         "error: %s: only one obduuid allowed",
4555                                         argv[0]);
4556                                 return CMD_HELP;
4557                         }
4558                         param.fp_obd_uuid = (struct obd_uuid *)optarg;
4559                         break;
4560                 case 'r':
4561                         param.fp_recursive = 1;
4562                         break;
4563                 case 'y':
4564                         param.fp_yaml = 1;
4565                         break;
4566                 default:
4567                         return CMD_HELP;
4568                 }
4569         }
4570
4571         if (optind >= argc)
4572                 return CMD_HELP;
4573
4574         if (param.fp_recursive)
4575                 param.fp_max_depth = -1;
4576
4577         if (!param.fp_verbose)
4578                 param.fp_verbose = VERBOSE_DEFAULT;
4579
4580         do {
4581                 rc = llapi_getstripe(argv[optind], &param);
4582         } while (++optind < argc && !rc);
4583
4584         if (rc)
4585                 fprintf(stderr, "error: %s failed for %s.\n",
4586                         argv[0], argv[optind - 1]);
4587         return rc;
4588 }
4589
4590 enum mntdf_flags {
4591         MNTDF_INODES    = 0x0001,
4592         MNTDF_COOKED    = 0x0002,
4593         MNTDF_LAZY      = 0x0004,
4594         MNTDF_VERBOSE   = 0x0008,
4595         MNTDF_SHOW      = 0x0010,
4596 };
4597
4598 #define COOK(value)                                             \
4599 ({                                                              \
4600         int radix = 0;                                          \
4601         while (value > 1024) {                                  \
4602                 value /= 1024;                                  \
4603                 radix++;                                        \
4604         }                                                       \
4605         radix;                                                  \
4606 })
4607 #define UUF     "%-20s"
4608 #define CSF     "%11s"
4609 #define CDF     "%11llu"
4610 #define HDF     "%8.1f%c"
4611 #define RSF     "%4s"
4612 #define RDF     "%3d%%"
4613
4614 static inline int obd_statfs_ratio(const struct obd_statfs *st, bool inodes)
4615 {
4616         double avail, used, ratio = 0;
4617
4618         if (inodes) {
4619                 avail = st->os_ffree;
4620                 used = st->os_files - st->os_ffree;
4621         } else {
4622                 avail = st->os_bavail;
4623                 used = st->os_blocks - st->os_bfree;
4624         }
4625         if (avail + used > 0)
4626                 ratio = used / (used + avail) * 100;
4627
4628         /* Round up to match df(1) usage percentage */
4629         return (ratio - (int)ratio) > 0 ? (int)(ratio + 1) : (int)ratio;
4630 }
4631
4632 static int showdf(char *mntdir, struct obd_statfs *stat,
4633                   char *uuid, enum mntdf_flags flags,
4634                   char *type, int index, int rc)
4635 {
4636         long long avail, used, total;
4637         int ratio = 0;
4638         char *suffix = "KMGTPEZY";
4639         /* Note if we have >2^64 bytes/fs these buffers will need to be grown */
4640         char tbuf[3 * sizeof(__u64)];
4641         char ubuf[3 * sizeof(__u64)];
4642         char abuf[3 * sizeof(__u64)];
4643         char rbuf[3 * sizeof(__u64)];
4644
4645         if (!uuid || !stat)
4646                 return -EINVAL;
4647
4648         switch (rc) {
4649         case 0:
4650                 if (flags & MNTDF_INODES) {
4651                         avail = stat->os_ffree;
4652                         used = stat->os_files - stat->os_ffree;
4653                         total = stat->os_files;
4654                 } else {
4655                         int shift = flags & MNTDF_COOKED ? 0 : 10;
4656
4657                         avail = (stat->os_bavail * stat->os_bsize) >> shift;
4658                         used  = ((stat->os_blocks - stat->os_bfree) *
4659                                  stat->os_bsize) >> shift;
4660                         total = (stat->os_blocks * stat->os_bsize) >> shift;
4661                 }
4662
4663                 ratio = obd_statfs_ratio(stat, flags & MNTDF_INODES);
4664
4665                 if (flags & MNTDF_COOKED) {
4666                         int i;
4667                         double cook_val;
4668
4669                         cook_val = (double)total;
4670                         i = COOK(cook_val);
4671                         if (i > 0)
4672                                 snprintf(tbuf, sizeof(tbuf), HDF, cook_val,
4673                                          suffix[i - 1]);
4674                         else
4675                                 snprintf(tbuf, sizeof(tbuf), CDF, total);
4676
4677                         cook_val = (double)used;
4678                         i = COOK(cook_val);
4679                         if (i > 0)
4680                                 snprintf(ubuf, sizeof(ubuf), HDF, cook_val,
4681                                          suffix[i - 1]);
4682                         else
4683                                 snprintf(ubuf, sizeof(ubuf), CDF, used);
4684
4685                         cook_val = (double)avail;
4686                         i = COOK(cook_val);
4687                         if (i > 0)
4688                                 snprintf(abuf, sizeof(abuf), HDF, cook_val,
4689                                          suffix[i - 1]);
4690                         else
4691                                 snprintf(abuf, sizeof(abuf), CDF, avail);
4692                 } else {
4693                         snprintf(tbuf, sizeof(tbuf), CDF, total);
4694                         snprintf(ubuf, sizeof(tbuf), CDF, used);
4695                         snprintf(abuf, sizeof(tbuf), CDF, avail);
4696                 }
4697
4698                 sprintf(rbuf, RDF, ratio);
4699                 printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s",
4700                        uuid, tbuf, ubuf, abuf, rbuf, mntdir);
4701                 if (type)
4702                         printf("[%s:%d]", type, index);
4703
4704                 if (stat->os_state) {
4705                         /*
4706                          * Each character represents the matching
4707                          * OS_STATE_* bit.
4708                          */
4709                         const char state_names[] = "DRSI";
4710                         __u32      state;
4711                         __u32      i;
4712
4713                         printf(" ");
4714                         for (i = 0, state = stat->os_state;
4715                              state && i < sizeof(state_names); i++) {
4716                                 if (!(state & (1 << i)))
4717                                         continue;
4718                                 printf("%c", state_names[i]);
4719                                 state ^= 1 << i;
4720                         }
4721                 }
4722
4723                 printf("\n");
4724                 break;
4725         case -ENODATA:
4726                 printf(UUF": inactive device\n", uuid);
4727                 break;
4728         default:
4729                 printf(UUF": %s\n", uuid, strerror(-rc));
4730                 break;
4731         }
4732
4733         return 0;
4734 }
4735
4736 struct ll_stat_type {
4737         int   st_op;
4738         char *st_name;
4739 };
4740
4741 #define LL_STATFS_MAX   LOV_MAX_STRIPE_COUNT
4742
4743 struct ll_statfs_data {
4744         int                     sd_index;
4745         struct obd_statfs       sd_st;
4746 };
4747
4748 struct ll_statfs_buf {
4749         int                     sb_count;
4750         struct ll_statfs_data   sb_buf[LL_STATFS_MAX];
4751 };
4752
4753 static int mntdf(char *mntdir, char *fsname, char *pool, enum mntdf_flags flags,
4754                  int ops, struct ll_statfs_buf *lsb)
4755 {
4756         struct obd_statfs stat_buf, sum = { .os_bsize = 1 };
4757         struct obd_uuid uuid_buf;
4758         char *poolname = NULL;
4759         struct ll_stat_type types[] = {
4760                 { .st_op = LL_STATFS_LMV,       .st_name = "MDT" },
4761                 { .st_op = LL_STATFS_LOV,       .st_name = "OST" },
4762                 { .st_name = NULL } };
4763         struct ll_stat_type *tp;
4764         __u64 ost_ffree = 0;
4765         __u32 index;
4766         __u32 type;
4767         int fd;
4768         int rc = 0;
4769         int rc2;
4770
4771         if (pool) {
4772                 poolname = strchr(pool, '.');
4773                 if (poolname != NULL) {
4774                         if (strncmp(fsname, pool, strlen(fsname))) {
4775                                 fprintf(stderr, "filesystem name incorrect\n");
4776                                 return -ENODEV;
4777                         }
4778                         poolname++;
4779                 } else
4780                         poolname = pool;
4781         }
4782
4783         fd = open(mntdir, O_RDONLY);
4784         if (fd < 0) {
4785                 rc = -errno;
4786                 fprintf(stderr, "%s: cannot open '%s': %s\n", progname, mntdir,
4787                         strerror(errno));
4788                 return rc;
4789         }
4790
4791         if (flags & MNTDF_SHOW) {
4792                 if (flags & MNTDF_INODES)
4793                         printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s\n",
4794                                "UUID", "Inodes", "IUsed", "IFree",
4795                                "IUse%", "Mounted on");
4796                 else
4797                         printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s\n",
4798                                "UUID",
4799                                flags & MNTDF_COOKED ? "bytes" : "1K-blocks",
4800                                "Used", "Available", "Use%", "Mounted on");
4801         }
4802
4803         for (tp = types; tp->st_name != NULL; tp++) {
4804                 bool have_ost = false;
4805
4806                 if (!(tp->st_op & ops))
4807                         continue;
4808
4809                 for (index = 0; ; index++) {
4810                         memset(&stat_buf, 0, sizeof(struct obd_statfs));
4811                         memset(&uuid_buf, 0, sizeof(struct obd_uuid));
4812                         type = flags & MNTDF_LAZY ?
4813                                 tp->st_op | LL_STATFS_NODELAY : tp->st_op;
4814                         rc2 = llapi_obd_fstatfs(fd, type, index,
4815                                                &stat_buf, &uuid_buf);
4816                         if (rc2 == -ENODEV)
4817                                 break;
4818                         if (rc2 == -EAGAIN)
4819                                 continue;
4820                         if (rc2 == -ENODATA) { /* Inactive device, OK. */
4821                                 if (!(flags & MNTDF_VERBOSE))
4822                                         continue;
4823                         } else if (rc2 < 0 && rc == 0) {
4824                                 rc = rc2;
4825                         }
4826
4827                         /* If we have OSTs then don't report MDT block counts.
4828                          * For MDT-only filesystems the expectation is that all
4829                          * layouts have a DoM component.  For filesystems with
4830                          * OSTs, files are not necessarily going to store data
4831                          * on MDTs, and MDT space is limited to a fraction of
4832                          * OST space, so don't include it in the summary.
4833                          */
4834                         if (tp->st_op == LL_STATFS_LOV && !have_ost) {
4835                                 have_ost = true;
4836                                 sum.os_blocks = 0;
4837                                 sum.os_bfree = 0;
4838                                 sum.os_bavail = 0;
4839                         }
4840
4841                         if (poolname && tp->st_op == LL_STATFS_LOV &&
4842                             llapi_search_ost(fsname, poolname,
4843                                              obd_uuid2str(&uuid_buf)) != 1)
4844                                 continue;
4845
4846                         /* the llapi_obd_statfs() call may have returned with
4847                          * an error, but if it filled in uuid_buf we will at
4848                          * lease use that to print out a message for that OBD.
4849                          * If we didn't get anything in the uuid_buf, then fill
4850                          * it in so that we can print an error message. */
4851                         if (uuid_buf.uuid[0] == '\0')
4852                                 snprintf(uuid_buf.uuid, sizeof(uuid_buf.uuid),
4853                                          "%s%04x", tp->st_name, index);
4854                         if (!rc && lsb) {
4855                                 lsb->sb_buf[lsb->sb_count].sd_index = index;
4856                                 lsb->sb_buf[lsb->sb_count].sd_st = stat_buf;
4857                                 lsb->sb_count++;
4858                         }
4859                         if (flags & MNTDF_SHOW)
4860                                 showdf(mntdir, &stat_buf,
4861                                        obd_uuid2str(&uuid_buf), flags,
4862                                        tp->st_name, index, rc2);
4863
4864                         if (rc2)
4865                                 continue;
4866
4867                         if (tp->st_op == LL_STATFS_LMV) {
4868                                 sum.os_ffree += stat_buf.os_ffree;
4869                                 sum.os_files += stat_buf.os_files;
4870                         } else /* if (tp->st_op == LL_STATFS_LOV) */ {
4871                                 ost_ffree += stat_buf.os_ffree;
4872                         }
4873                         sum.os_blocks += stat_buf.os_blocks *
4874                                          stat_buf.os_bsize;
4875                         sum.os_bfree  += stat_buf.os_bfree *
4876                                          stat_buf.os_bsize;
4877                         sum.os_bavail += stat_buf.os_bavail *
4878                                          stat_buf.os_bsize;
4879                 }
4880         }
4881
4882         close(fd);
4883
4884         /* If we don't have as many objects free on the OST as inodes
4885          * on the MDS, we reduce the total number of inodes to
4886          * compensate, so that the "inodes in use" number is correct.
4887          * Matches ll_statfs_internal() so the results are consistent. */
4888         if (ost_ffree < sum.os_ffree) {
4889                 sum.os_files = (sum.os_files - sum.os_ffree) + ost_ffree;
4890                 sum.os_ffree = ost_ffree;
4891         }
4892         if (flags & MNTDF_SHOW) {
4893                 printf("\n");
4894                 showdf(mntdir, &sum, "filesystem_summary:", flags, NULL, 0, 0);
4895                 printf("\n");
4896         }
4897
4898         return rc;
4899 }
4900
4901 static int ll_statfs_data_comp(const void *sd1, const void *sd2)
4902 {
4903         const struct obd_statfs *st1 = &((const struct ll_statfs_data *)sd1)->
4904                                                 sd_st;
4905         const struct obd_statfs *st2 = &((const struct ll_statfs_data *)sd2)->
4906                                                 sd_st;
4907         int r1 = obd_statfs_ratio(st1, false);
4908         int r2 = obd_statfs_ratio(st2, false);
4909         int64_t result = r1 - r2;
4910
4911         /* if both space usage are above 90, compare free inodes */
4912         if (r1 > 90 && r2 > 90)
4913                 result = st2->os_ffree - st1->os_ffree;
4914
4915         if (result < 0)
4916                 return -1;
4917         else if (result == 0)
4918                 return 0;
4919         else
4920                 return 1;
4921 }
4922
4923 /* functions */
4924 static int lfs_setdirstripe(int argc, char **argv)
4925 {
4926         char                    *dname;
4927         int                     result;
4928         struct lfs_setstripe_args        lsa = { 0 };
4929         struct llapi_stripe_param       *param = NULL;
4930         __u32                   mdts[LMV_MAX_STRIPE_COUNT] = { 0 };
4931         char                    *end;
4932         int                     c;
4933         char                    *mode_opt = NULL;
4934         bool                    default_stripe = false;
4935         mode_t                  mode = S_IRWXU | S_IRWXG | S_IRWXO;
4936         mode_t                  previous_mode = 0;
4937         bool                    delete = false;
4938         struct ll_statfs_buf    *lsb = NULL;
4939         char                    mntdir[PATH_MAX] = "";
4940         bool                    auto_distributed = false;
4941
4942         struct option long_opts[] = {
4943         { .val = 'c',   .name = "count",        .has_arg = required_argument },
4944         { .val = 'c',   .name = "mdt-count",    .has_arg = required_argument },
4945         { .val = 'd',   .name = "delete",       .has_arg = no_argument },
4946         { .val = 'D',   .name = "default",      .has_arg = no_argument },
4947         { .val = 'D',   .name = "default_stripe", .has_arg = no_argument },
4948         { .val = 'H',   .name = "mdt-hash",     .has_arg = required_argument },
4949         { .val = 'i',   .name = "mdt-index",    .has_arg = required_argument },
4950 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
4951         { .val = 'i',   .name = "index",        .has_arg = required_argument },
4952 #endif
4953         { .val = 'o',   .name = "mode",         .has_arg = required_argument },
4954 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
4955         { .val = 't',   .name = "hash-type",    .has_arg = required_argument },
4956 #endif
4957         { .val = 'T',   .name = "mdt-count",    .has_arg = required_argument },
4958 /* setstripe { .val = 'y', .name = "yaml",      .has_arg = no_argument }, */
4959         { .name = NULL } };
4960
4961         setstripe_args_init(&lsa);
4962
4963         while ((c = getopt_long(argc, argv, "c:dDi:H:m:o:t:T:", long_opts,
4964                                 NULL)) >= 0) {
4965                 switch (c) {
4966                 case 0:
4967                         /* Long options. */
4968                         break;
4969                 case 'c':
4970                 case 'T':
4971                         lsa.lsa_stripe_count = strtoul(optarg, &end, 0);
4972                         if (*end != '\0') {
4973                                 fprintf(stderr,
4974                                         "%s %s: invalid stripe count '%s'\n",
4975                                         progname, argv[0], optarg);
4976                                 return CMD_HELP;
4977                         }
4978                         break;
4979                 case 'd':
4980                         delete = true;
4981                         default_stripe = true;
4982                         break;
4983                 case 'D':
4984                         default_stripe = true;
4985                         break;
4986 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
4987                 case 't':
4988                         fprintf(stderr, "warning: '--hash-type' and '-t' "
4989                               "deprecated, use '--mdt-hash' or '-H' instead\n");
4990 #endif
4991                 case 'H':
4992                         lsa.lsa_pattern = check_hashtype(optarg);
4993                         if (lsa.lsa_pattern == 0) {
4994                                 fprintf(stderr,
4995                                         "%s %s: bad stripe hash type '%s'\n",
4996                                         progname, argv[0], optarg);
4997                                 return CMD_HELP;
4998                         }
4999                         break;
5000                 case 'i':
5001 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
5002                         if (strcmp(argv[optind - 1], "--index") == 0)
5003                                 fprintf(stderr,
5004                                         "%s %s: warning: '--index' deprecated, use '--mdt-index' instead\n",
5005                                         progname, argv[0]);
5006 #endif
5007                         lsa.lsa_nr_tgts = parse_targets(mdts,
5008                                                 sizeof(mdts) / sizeof(__u32),
5009                                                 lsa.lsa_nr_tgts, optarg);
5010                         if (lsa.lsa_nr_tgts < 0) {
5011                                 fprintf(stderr,
5012                                         "%s %s: invalid MDT target(s) '%s'\n",
5013                                         progname, argv[0], optarg);
5014                                 return CMD_HELP;
5015                         }
5016
5017                         lsa.lsa_tgts = mdts;
5018                         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
5019                                 lsa.lsa_stripe_off = mdts[0];
5020                         break;
5021 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 16, 53, 0)
5022                 case 'm':
5023                         fprintf(stderr, "warning: '-m' is deprecated, "
5024                                 "use '--mode' or '-o' instead\n");
5025 #endif
5026                 case 'o':
5027                         mode_opt = optarg;
5028                         break;
5029                 default:
5030                         fprintf(stderr, "%s %s: unrecognized option '%s'\n",
5031                                 progname, argv[0], argv[optind - 1]);
5032                         return CMD_HELP;
5033                 }
5034         }
5035
5036         if (optind == argc) {
5037                 fprintf(stderr, "%s %s: DIR must be specified\n",
5038                         progname, argv[0]);
5039                 return CMD_HELP;
5040         }
5041
5042         if (!delete && lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT &&
5043             lsa.lsa_stripe_count == LLAPI_LAYOUT_DEFAULT) {
5044                 fprintf(stderr,
5045                         "%s %s: stripe offset and count must be specified\n",
5046                         progname, argv[0]);
5047                 return CMD_HELP;
5048         }
5049
5050         if (delete &&
5051             (lsa.lsa_stripe_off != LLAPI_LAYOUT_DEFAULT ||
5052              lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT)) {
5053                 fprintf(stderr,
5054                         "%s %s: cannot specify -d with -c or -i options\n",
5055                         progname, argv[0]);
5056                 return CMD_HELP;
5057         }
5058
5059         if (mode_opt != NULL) {
5060                 mode = strtoul(mode_opt, &end, 8);
5061                 if (*end != '\0') {
5062                         fprintf(stderr,
5063                                 "%s %s: bad MODE '%s'\n",
5064                                 progname, argv[0], mode_opt);
5065                         return CMD_HELP;
5066                 }
5067                 previous_mode = umask(0);
5068         }
5069
5070         /*
5071          * initialize stripe parameters, in case param is converted to specific,
5072          * i.e, 'lfs mkdir -i -1 -c N', always allocate space for lsp_tgts.
5073          */
5074         param = calloc(1, offsetof(typeof(*param),
5075                        lsp_tgts[lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT ?
5076                                 lsa.lsa_stripe_count : lsa.lsa_nr_tgts]));
5077         if (param == NULL) {
5078                 fprintf(stderr,
5079                         "%s %s: cannot allocate memory for parameters: %s\n",
5080                         progname, argv[0], strerror(ENOMEM));
5081                 return CMD_HELP;
5082         }
5083
5084         if (lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT)
5085                 param->lsp_stripe_count = lsa.lsa_stripe_count;
5086         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
5087                 param->lsp_stripe_offset = -1;
5088         else
5089                 param->lsp_stripe_offset = lsa.lsa_stripe_off;
5090         if (lsa.lsa_pattern != LLAPI_LAYOUT_RAID0)
5091                 param->lsp_stripe_pattern = lsa.lsa_pattern;
5092         else
5093                 param->lsp_stripe_pattern = LMV_HASH_TYPE_FNV_1A_64;
5094         param->lsp_pool = lsa.lsa_pool_name;
5095         param->lsp_is_specific = false;
5096         if (lsa.lsa_nr_tgts > 1) {
5097                 if (lsa.lsa_stripe_count > 0 &&
5098                     lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT &&
5099                     lsa.lsa_stripe_count != lsa.lsa_nr_tgts) {
5100                         fprintf(stderr, "error: %s: stripe count %lld doesn't "
5101                                 "match the number of MDTs: %d\n",
5102                                 argv[0], lsa.lsa_stripe_count, lsa.lsa_nr_tgts);
5103                         free(param);
5104                         return CMD_HELP;
5105                 }
5106
5107                 param->lsp_is_specific = true;
5108                 param->lsp_stripe_count = lsa.lsa_nr_tgts;
5109                 memcpy(param->lsp_tgts, mdts, sizeof(*mdts) * lsa.lsa_nr_tgts);
5110         }
5111
5112         dname = argv[optind];
5113         do {
5114                 if (default_stripe) {
5115                         result = llapi_dir_set_default_lmv(dname, param);
5116                 } else {
5117                         /* if current \a dname isn't under the same \a mntdir
5118                          * as the last one, and the last one was
5119                          * auto-distributed, restore \a param.
5120                          */
5121                         if (mntdir[0] != '\0' &&
5122                             strncmp(dname, mntdir, strlen(mntdir)) &&
5123                             auto_distributed) {
5124                                 param->lsp_is_specific = false;
5125                                 param->lsp_stripe_offset = -1;
5126                                 auto_distributed = false;
5127                         }
5128
5129                         if (!param->lsp_is_specific &&
5130                             param->lsp_stripe_offset == -1) {
5131                                 char path[PATH_MAX] = "";
5132
5133                                 if (!lsb) {
5134                                         lsb = malloc(sizeof(*lsb));
5135                                         if (!lsb) {
5136                                                 result = -ENOMEM;
5137                                                 break;
5138                                         }
5139                                 }
5140                                 lsb->sb_count = 0;
5141
5142                                 /* use mntdir for dirname() temporarily */
5143                                 strncpy(mntdir, dname, sizeof(mntdir));
5144                                 if (!realpath(dirname(mntdir), path)) {
5145                                         result = -errno;
5146                                         fprintf(stderr,
5147                                                 "error: invalid path '%s': %s\n",
5148                                                 argv[optind], strerror(errno));
5149                                         break;
5150                                 }
5151                                 mntdir[0] = '\0';
5152
5153                                 result = llapi_search_mounts(path, 0, mntdir,
5154                                                              NULL);
5155                                 if (result < 0 || mntdir[0] == '\0') {
5156                                         fprintf(stderr,
5157                                                 "No suitable Lustre mount found\n");
5158                                         break;
5159                                 }
5160
5161                                 result = mntdf(mntdir, NULL, NULL, 0,
5162                                                LL_STATFS_LMV, lsb);
5163                                 if (result < 0)
5164                                         break;
5165
5166                                 if (param->lsp_stripe_count > lsb->sb_count) {
5167                                         fprintf(stderr,
5168                                                 "error: stripe count %d is too big\n",
5169                                                 param->lsp_stripe_count);
5170                                         result = -ERANGE;
5171                                         break;
5172                                 }
5173
5174                                 qsort(lsb->sb_buf, lsb->sb_count,
5175                                       sizeof(struct ll_statfs_data),
5176                                       ll_statfs_data_comp);
5177
5178                                 auto_distributed = true;
5179                         }
5180
5181                         if (auto_distributed) {
5182                                 int r;
5183                                 int nr = MAX(param->lsp_stripe_count,
5184                                              lsb->sb_count / 2);
5185
5186                                 /* don't use server whose usage is above 90% */
5187                                 while (nr != param->lsp_stripe_count &&
5188                                        obd_statfs_ratio(&lsb->sb_buf[nr].sd_st,
5189                                                         false) > 90)
5190                                         nr = MAX(param->lsp_stripe_count,
5191                                                  nr / 2);
5192
5193                                 /* get \a r between [0, nr) */
5194                                 r = rand() % nr;
5195
5196                                 param->lsp_stripe_offset =
5197                                         lsb->sb_buf[r].sd_index;
5198                                 if (param->lsp_stripe_count > 1) {
5199                                         int i = 0;
5200
5201                                         param->lsp_is_specific = true;
5202                                         for (; i < param->lsp_stripe_count; i++)
5203                                                 param->lsp_tgts[(i + r) % nr] =
5204                                                         lsb->sb_buf[i].sd_index;
5205                                 }
5206                         }
5207
5208                         result = llapi_dir_create(dname, mode, param);
5209                 }
5210
5211                 if (result) {
5212                         fprintf(stderr,
5213                                 "%s setdirstripe: cannot create stripe dir '%s': %s\n",
5214                                 progname, dname, strerror(-result));
5215                         break;
5216                 }
5217                 dname = argv[++optind];
5218         } while (dname != NULL);
5219
5220         if (mode_opt != NULL)
5221                 umask(previous_mode);
5222
5223         free(lsb);
5224         free(param);
5225         return result;
5226 }
5227
5228 /* functions */
5229 static int lfs_rmentry(int argc, char **argv)
5230 {
5231         char *dname;
5232         int   index;
5233         int   result = 0;
5234
5235         if (argc <= 1) {
5236                 fprintf(stderr, "error: %s: missing dirname\n",
5237                         argv[0]);
5238                 return CMD_HELP;
5239         }
5240
5241         index = 1;
5242         dname = argv[index];
5243         while (dname != NULL) {
5244                 result = llapi_direntry_remove(dname);
5245                 if (result) {
5246                         fprintf(stderr, "error: %s: remove dir entry '%s' "
5247                                 "failed\n", argv[0], dname);
5248                         break;
5249                 }
5250                 dname = argv[++index];
5251         }
5252         return result;
5253 }
5254
5255 static int lfs_mv(int argc, char **argv)
5256 {
5257         struct lmv_user_md lmu = { LMV_USER_MAGIC };
5258         struct find_param param = {
5259                 .fp_max_depth = -1,
5260                 .fp_mdt_index = -1,
5261         };
5262         char *end;
5263         int c;
5264         int rc = 0;
5265         struct option long_opts[] = {
5266         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument },
5267         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
5268         { .name = NULL } };
5269
5270         while ((c = getopt_long(argc, argv, "m:M:v", long_opts, NULL)) != -1) {
5271                 switch (c) {
5272 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
5273                 case 'M':
5274                         fprintf(stderr, "warning: '-M' deprecated"
5275                                 ", use '--mdt-index' or '-m' instead\n");
5276 #endif
5277                 case 'm':
5278                         lmu.lum_stripe_offset = strtoul(optarg, &end, 0);
5279                         if (*end != '\0') {
5280                                 fprintf(stderr, "%s mv: bad MDT index '%s'\n",
5281                                         progname, optarg);
5282                                 return CMD_HELP;
5283                         }
5284                         break;
5285                 case 'v':
5286                         param.fp_verbose = VERBOSE_DETAIL;
5287                         break;
5288                 default:
5289                         fprintf(stderr, "%s mv: unrecognized option '%s'\n",
5290                                 progname, argv[optind - 1]);
5291                         return CMD_HELP;
5292                 }
5293         }
5294
5295         if (lmu.lum_stripe_offset == -1) {
5296                 fprintf(stderr, "%s mv: MDT index must be specified\n",
5297                         progname);
5298                 return CMD_HELP;
5299         }
5300
5301         if (optind >= argc) {
5302                 fprintf(stderr, "%s mv: DIR must be specified\n", progname);
5303                 return CMD_HELP;
5304         }
5305
5306
5307         /* initialize migrate mdt parameters */
5308         param.fp_lmv_md = &lmu;
5309         param.fp_migrate = 1;
5310         rc = llapi_migrate_mdt(argv[optind], &param);
5311         if (rc != 0)
5312                 fprintf(stderr, "%s mv: cannot migrate '%s' to MDT%04x: %s\n",
5313                         progname, argv[optind], param.fp_mdt_index,
5314                         strerror(-rc));
5315         return rc;
5316 }
5317
5318 static int lfs_osts(int argc, char **argv)
5319 {
5320         return lfs_tgts(argc, argv);
5321 }
5322
5323 static int lfs_mdts(int argc, char **argv)
5324 {
5325         return lfs_tgts(argc, argv);
5326 }
5327
5328 static int lfs_df(int argc, char **argv)
5329 {
5330         char mntdir[PATH_MAX] = {'\0'}, path[PATH_MAX] = {'\0'};
5331         enum mntdf_flags flags = MNTDF_SHOW;
5332         int ops = LL_STATFS_LMV | LL_STATFS_LOV;
5333         int c, rc = 0, index = 0;
5334         char fsname[PATH_MAX] = "", *pool_name = NULL;
5335         struct option long_opts[] = {
5336         { .val = 'h',   .name = "human-readable",
5337                                                 .has_arg = no_argument },
5338         { .val = 'i',   .name = "inodes",       .has_arg = no_argument },
5339         { .val = 'l',   .name = "lazy",         .has_arg = no_argument },
5340         { .val = 'p',   .name = "pool",         .has_arg = required_argument },
5341         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
5342         { .name = NULL} };
5343
5344         while ((c = getopt_long(argc, argv, "hilp:v", long_opts, NULL)) != -1) {
5345                 switch (c) {
5346                 case 'h':
5347                         flags |= MNTDF_COOKED;
5348                         break;
5349                 case 'i':
5350                         flags |= MNTDF_INODES;
5351                         break;
5352                 case 'l':
5353                         flags |= MNTDF_LAZY;
5354                         break;
5355                 case 'p':
5356                         pool_name = optarg;
5357                         break;
5358                 case 'v':
5359                         flags |= MNTDF_VERBOSE;
5360                         break;
5361                 default:
5362                         return CMD_HELP;
5363                 }
5364         }
5365         if (optind < argc && !realpath(argv[optind], path)) {
5366                 rc = -errno;
5367                 fprintf(stderr, "error: invalid path '%s': %s\n",
5368                         argv[optind], strerror(-rc));
5369                 return rc;
5370         }
5371
5372         while (!llapi_search_mounts(path, index++, mntdir, fsname)) {
5373                 /* Check if we have a mount point */
5374                 if (mntdir[0] == '\0')
5375                         continue;
5376
5377                 rc = mntdf(mntdir, fsname, pool_name, flags, ops, NULL);
5378                 if (rc || path[0] != '\0')
5379                         break;
5380                 fsname[0] = '\0'; /* avoid matching in next loop */
5381                 mntdir[0] = '\0'; /* avoid matching in next loop */
5382         }
5383
5384         return rc;
5385 }
5386
5387 static int lfs_getname(int argc, char **argv)
5388 {
5389         char mntdir[PATH_MAX] = "", path[PATH_MAX] = "", fsname[PATH_MAX] = "";
5390         int rc = 0, index = 0, c;
5391         char buf[sizeof(struct obd_uuid)];
5392
5393         while ((c = getopt(argc, argv, "h")) != -1)
5394                 return CMD_HELP;
5395
5396         if (optind == argc) { /* no paths specified, get all paths. */
5397                 while (!llapi_search_mounts(path, index++, mntdir, fsname)) {
5398                         rc = llapi_getname(mntdir, buf, sizeof(buf));
5399                         if (rc < 0) {
5400                                 fprintf(stderr,
5401                                         "cannot get name for `%s': %s\n",
5402                                         mntdir, strerror(-rc));
5403                                 break;
5404                         }
5405
5406                         printf("%s %s\n", buf, mntdir);
5407
5408                         path[0] = fsname[0] = mntdir[0] = 0;
5409                 }
5410         } else { /* paths specified, only attempt to search these. */
5411                 for (; optind < argc; optind++) {
5412                         rc = llapi_getname(argv[optind], buf, sizeof(buf));
5413                         if (rc < 0) {
5414                                 fprintf(stderr,
5415                                         "cannot get name for `%s': %s\n",
5416                                         argv[optind], strerror(-rc));
5417                                 break;
5418                         }
5419
5420                         printf("%s %s\n", buf, argv[optind]);
5421                 }
5422         }
5423         return rc;
5424 }
5425
5426 static int lfs_check(int argc, char **argv)
5427 {
5428         char mntdir[PATH_MAX] = {'\0'};
5429         int num_types = 1;
5430         char *obd_types[3];
5431         char obd_type1[4];
5432         char obd_type2[4];
5433         char obd_type3[4];
5434         int rc;
5435
5436         if (argc != 2) {
5437                 fprintf(stderr, "%s check: server type must be specified\n",
5438                         progname);
5439                 return CMD_HELP;
5440         }
5441
5442         obd_types[0] = obd_type1;
5443         obd_types[1] = obd_type2;
5444         obd_types[2] = obd_type3;
5445
5446         if (strcmp(argv[1], "osts") == 0) {
5447                 strcpy(obd_types[0], "osc");
5448         } else if (strcmp(argv[1], "mdts") == 0 ||
5449                    strcmp(argv[1], "mds") == 0) {
5450                 strcpy(obd_types[0], "mdc");
5451         } else if (strcmp(argv[1], "mgts") == 0) {
5452                 strcpy(obd_types[0], "mgc");
5453         } else if (strcmp(argv[1], "all") == 0 ||
5454                    strcmp(argv[1], "servers") == 0) {
5455                 num_types = 3;
5456                 strcpy(obd_types[0], "osc");
5457                 strcpy(obd_types[1], "mdc");
5458                 strcpy(obd_types[2], "mgc");
5459         } else {
5460                 fprintf(stderr, "%s check: unrecognized option '%s'\n",
5461                         progname, argv[1]);
5462                 return CMD_HELP;
5463         }
5464
5465         rc = llapi_search_mounts(NULL, 0, mntdir, NULL);
5466         if (rc < 0 || mntdir[0] == '\0') {
5467                 fprintf(stderr,
5468                         "%s check: cannot find mounted Lustre filesystem: %s\n",
5469                         progname, (rc < 0) ? strerror(-rc) : strerror(ENODEV));
5470                 return rc;
5471         }
5472
5473         rc = llapi_target_check(num_types, obd_types, mntdir);
5474         if (rc)
5475                 fprintf(stderr, "%s check: cannot check target '%s': %s\n",
5476                         progname, argv[1], strerror(-rc));
5477
5478         return rc;
5479
5480 }
5481
5482 #ifdef HAVE_SYS_QUOTA_H
5483 #define ARG2INT(nr, str, msg)                                           \
5484 do {                                                                    \
5485         char *endp;                                                     \
5486         nr = strtol(str, &endp, 0);                                     \
5487         if (*endp != '\0') {                                            \
5488                 fprintf(stderr, "%s: bad %s '%s'\n",                    \
5489                         progname, msg, str);                            \
5490                 return CMD_HELP;                                        \
5491         }                                                               \
5492 } while (0)
5493
5494 #define ADD_OVERFLOW(a,b) ((a + b) < a) ? (a = ULONG_MAX) : (a = a + b)
5495
5496 /* Convert format time string "XXwXXdXXhXXmXXs" into seconds value
5497  * returns the value or ULONG_MAX on integer overflow or incorrect format
5498  * Notes:
5499  *        1. the order of specifiers is arbitrary (may be: 5w3s or 3s5w)
5500  *        2. specifiers may be encountered multiple times (2s3s is 5 seconds)
5501  *        3. empty integer value is interpreted as 0
5502  */
5503 static unsigned long str2sec(const char* timestr)
5504 {
5505         const char spec[] = "smhdw";
5506         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
5507         unsigned long val = 0;
5508         char *tail;
5509
5510         if (strpbrk(timestr, spec) == NULL) {
5511                 /* no specifiers inside the time string,
5512                    should treat it as an integer value */
5513                 val = strtoul(timestr, &tail, 10);
5514                 return *tail ? ULONG_MAX : val;
5515         }
5516
5517         /* format string is XXwXXdXXhXXmXXs */
5518         while (*timestr) {
5519                 unsigned long v;
5520                 int ind;
5521                 char* ptr;
5522
5523                 v = strtoul(timestr, &tail, 10);
5524                 if (v == ULONG_MAX || *tail == '\0')
5525                         /* value too large (ULONG_MAX or more)
5526                            or missing specifier */
5527                         goto error;
5528
5529                 ptr = strchr(spec, *tail);
5530                 if (ptr == NULL)
5531                         /* unknown specifier */
5532                         goto error;
5533
5534                 ind = ptr - spec;
5535
5536                 /* check if product will overflow the type */
5537                 if (!(v < ULONG_MAX / mult[ind]))
5538                         goto error;
5539
5540                 ADD_OVERFLOW(val, mult[ind] * v);
5541                 if (val == ULONG_MAX)
5542                         goto error;
5543
5544                 timestr = tail + 1;
5545         }
5546
5547         return val;
5548
5549 error:
5550         return ULONG_MAX;
5551 }
5552
5553 #define ARG2ULL(nr, str, def_units)                                     \
5554 do {                                                                    \
5555         unsigned long long limit, units = def_units;                    \
5556         int rc;                                                         \
5557                                                                         \
5558         rc = llapi_parse_size(str, &limit, &units, 1);                  \
5559         if (rc < 0) {                                                   \
5560                 fprintf(stderr, "%s: invalid limit '%s'\n",             \
5561                         progname, str);                                 \
5562                 return CMD_HELP;                                        \
5563         }                                                               \
5564         nr = limit;                                                     \
5565 } while (0)
5566
5567 static inline int has_times_option(int argc, char **argv)
5568 {
5569         int i;
5570
5571         for (i = 1; i < argc; i++)
5572                 if (!strcmp(argv[i], "-t"))
5573                         return 1;
5574
5575         return 0;
5576 }
5577
5578 int lfs_setquota_times(int argc, char **argv)
5579 {
5580         int c, rc;
5581         struct if_quotactl qctl;
5582         char *mnt, *obd_type = (char *)qctl.obd_type;
5583         struct obd_dqblk *dqb = &qctl.qc_dqblk;
5584         struct obd_dqinfo *dqi = &qctl.qc_dqinfo;
5585         struct option long_opts[] = {
5586         { .val = 'b',   .name = "block-grace",  .has_arg = required_argument },
5587         { .val = 'g',   .name = "group",        .has_arg = no_argument },
5588         { .val = 'i',   .name = "inode-grace",  .has_arg = required_argument },
5589         { .val = 'p',   .name = "projid",       .has_arg = no_argument },
5590         { .val = 't',   .name = "times",        .has_arg = no_argument },
5591         { .val = 'u',   .name = "user",         .has_arg = no_argument },
5592         { .name = NULL } };
5593         int qtype;
5594
5595         memset(&qctl, 0, sizeof(qctl));
5596         qctl.qc_cmd  = LUSTRE_Q_SETINFO;
5597         qctl.qc_type = ALLQUOTA;
5598
5599         while ((c = getopt_long(argc, argv, "b:gi:ptu",
5600                                 long_opts, NULL)) != -1) {
5601                 switch (c) {
5602                 case 'u':
5603                         qtype = USRQUOTA;
5604                         goto quota_type;
5605                 case 'g':
5606                         qtype = GRPQUOTA;
5607                         goto quota_type;
5608                 case 'p':
5609                         qtype = PRJQUOTA;
5610 quota_type:
5611                         if (qctl.qc_type != ALLQUOTA) {
5612                                 fprintf(stderr, "error: -u/g/p can't be used "
5613                                                 "more than once\n");
5614                                 return CMD_HELP;
5615                         }
5616                         qctl.qc_type = qtype;
5617                         break;
5618                 case 'b':
5619                         if ((dqi->dqi_bgrace = str2sec(optarg)) == ULONG_MAX) {
5620                                 fprintf(stderr, "error: bad block-grace: %s\n",
5621                                         optarg);
5622                                 return CMD_HELP;
5623                         }
5624                         dqb->dqb_valid |= QIF_BTIME;
5625                         break;
5626                 case 'i':
5627                         if ((dqi->dqi_igrace = str2sec(optarg)) == ULONG_MAX) {
5628                                 fprintf(stderr, "error: bad inode-grace: %s\n",
5629                                         optarg);
5630                                 return CMD_HELP;
5631                         }
5632                         dqb->dqb_valid |= QIF_ITIME;
5633                         break;
5634                 case 't': /* Yes, of course! */
5635                         break;
5636                 default: /* getopt prints error message for us when opterr != 0 */
5637                         return CMD_HELP;
5638                 }
5639         }
5640
5641         if (qctl.qc_type == ALLQUOTA) {
5642                 fprintf(stderr, "error: neither -u, -g nor -p specified\n");
5643                 return CMD_HELP;
5644         }
5645
5646         if (optind != argc - 1) {
5647                 fprintf(stderr, "error: unexpected parameters encountered\n");
5648                 return CMD_HELP;
5649         }
5650
5651         if ((dqb->dqb_valid | QIF_BTIME && dqi->dqi_bgrace >= UINT_MAX) ||
5652             (dqb->dqb_valid | QIF_ITIME && dqi->dqi_igrace >= UINT_MAX)) {
5653                 fprintf(stderr, "error: grace time is too large\n");
5654                 return CMD_HELP;
5655         }
5656
5657         mnt = argv[optind];
5658         rc = llapi_quotactl(mnt, &qctl);
5659         if (rc) {
5660                 if (*obd_type)
5661                         fprintf(stderr, "%s %s ", obd_type,
5662                                 obd_uuid2str(&qctl.obd_uuid));
5663                 fprintf(stderr, "setquota failed: %s\n", strerror(-rc));
5664                 return rc;
5665         }
5666
5667         return 0;
5668 }
5669
5670 #define BSLIMIT (1 << 0)
5671 #define BHLIMIT (1 << 1)
5672 #define ISLIMIT (1 << 2)
5673 #define IHLIMIT (1 << 3)
5674
5675 int lfs_setquota(int argc, char **argv)
5676 {
5677         int c, rc = 0;
5678         struct if_quotactl qctl;
5679         char *mnt, *obd_type = (char *)qctl.obd_type;
5680         struct obd_dqblk *dqb = &qctl.qc_dqblk;
5681         struct option long_opts[] = {
5682         { .val = 'b',   .name = "block-softlimit",
5683                                                 .has_arg = required_argument },
5684         { .val = 'B',   .name = "block-hardlimit",
5685                                                 .has_arg = required_argument },
5686         { .val = 'd',   .name = "default",      .has_arg = no_argument },
5687         { .val = 'g',   .name = "group",        .has_arg = required_argument },
5688         { .val = 'G',   .name = "default-grp",  .has_arg = no_argument },
5689         { .val = 'i',   .name = "inode-softlimit",
5690                                                 .has_arg = required_argument },
5691         { .val = 'I',   .name = "inode-hardlimit",
5692                                                 .has_arg = required_argument },
5693         { .val = 'p',   .name = "projid",       .has_arg = required_argument },
5694         { .val = 'P',   .name = "default-prj",  .has_arg = no_argument },
5695         { .val = 'u',   .name = "user",         .has_arg = required_argument },
5696         { .val = 'U',   .name = "default-usr",  .has_arg = no_argument },
5697         { .name = NULL } };
5698         unsigned limit_mask = 0;
5699         char *endptr;
5700         bool use_default = false;
5701         int qtype;
5702
5703         if (has_times_option(argc, argv))
5704                 return lfs_setquota_times(argc, argv);
5705
5706         memset(&qctl, 0, sizeof(qctl));
5707         qctl.qc_cmd  = LUSTRE_Q_SETQUOTA;
5708         qctl.qc_type = ALLQUOTA; /* ALLQUOTA makes no sense for setquota,
5709                                   * so it can be used as a marker that qc_type
5710                                   * isn't reinitialized from command line */
5711
5712         while ((c = getopt_long(argc, argv, "b:B:dg:Gi:I:p:Pu:U",
5713                 long_opts, NULL)) != -1) {
5714                 switch (c) {
5715                 case 'U':
5716                         qctl.qc_cmd = LUSTRE_Q_SETDEFAULT;
5717                         qtype = USRQUOTA;
5718                         qctl.qc_id = 0;
5719                         goto quota_type_def;
5720                 case 'u':
5721                         qtype = USRQUOTA;
5722                         rc = name2uid(&qctl.qc_id, optarg);
5723                         goto quota_type;
5724                 case 'G':
5725                         qctl.qc_cmd = LUSTRE_Q_SETDEFAULT;
5726                         qtype = GRPQUOTA;
5727                         qctl.qc_id = 0;
5728                         goto quota_type_def;
5729                 case 'g':
5730                         qtype = GRPQUOTA;
5731                         rc = name2gid(&qctl.qc_id, optarg);
5732                         goto quota_type;
5733                 case 'P':
5734                         qctl.qc_cmd = LUSTRE_Q_SETDEFAULT;
5735                         qtype = PRJQUOTA;
5736                         qctl.qc_id = 0;
5737                         goto quota_type_def;
5738                 case 'p':
5739                         qtype = PRJQUOTA;
5740                         rc = name2projid(&qctl.qc_id, optarg);
5741 quota_type:
5742                         if (rc) {
5743                                 qctl.qc_id = strtoul(optarg, &endptr, 10);
5744                                 if (*endptr != '\0') {
5745                                         fprintf(stderr, "%s setquota: invalid"
5746                                                 " id '%s'\n", progname, optarg);
5747                                         return -1;
5748                                 }
5749                         }
5750
5751                         if (qctl.qc_id == 0) {
5752                                 fprintf(stderr, "%s setquota: can't set quota"
5753                                         " for root usr/group/project.\n",
5754                                         progname);
5755                                 return -1;
5756                         }
5757
5758 quota_type_def:
5759                         if (qctl.qc_type != ALLQUOTA) {
5760                                 fprintf(stderr,
5761                                         "%s setquota: only one of -u, -U, -g,"
5762                                         " -G, -p or -P may be specified\n",
5763                                         progname);
5764                                 return CMD_HELP;
5765                         }
5766                         qctl.qc_type = qtype;
5767                         break;
5768                 case 'd':
5769                         qctl.qc_cmd = LUSTRE_Q_SETDEFAULT;
5770                         use_default = true;
5771                         break;
5772                 case 'b':
5773                         ARG2ULL(dqb->dqb_bsoftlimit, optarg, 1024);
5774                         dqb->dqb_bsoftlimit >>= 10;
5775                         limit_mask |= BSLIMIT;
5776                         if (dqb->dqb_bsoftlimit &&
5777                             dqb->dqb_bsoftlimit <= 1024) /* <= 1M? */
5778                                 fprintf(stderr,
5779                                         "%s setquota: warning: block softlimit '%llu' smaller than minimum qunit size\n"
5780                                         "See '%s help setquota' or Lustre manual for details\n",
5781                                         progname, dqb->dqb_bsoftlimit,
5782                                         progname);
5783                         break;
5784                 case 'B':
5785                         ARG2ULL(dqb->dqb_bhardlimit, optarg, 1024);
5786                         dqb->dqb_bhardlimit >>= 10;
5787                         limit_mask |= BHLIMIT;
5788                         if (dqb->dqb_bhardlimit &&
5789                             dqb->dqb_bhardlimit <= 1024) /* <= 1M? */
5790                                 fprintf(stderr,
5791                                         "%s setquota: warning: block hardlimit '%llu' smaller than minimum qunit size\n"
5792                                         "See '%s help setquota' or Lustre manual for details\n",
5793                                         progname, dqb->dqb_bhardlimit,
5794                                         progname);
5795                         break;
5796                 case 'i':
5797                         ARG2ULL(dqb->dqb_isoftlimit, optarg, 1);
5798                         limit_mask |= ISLIMIT;
5799                         if (dqb->dqb_isoftlimit &&
5800                             dqb->dqb_isoftlimit <= 1024) /* <= 1K inodes? */
5801                                 fprintf(stderr,
5802                                         "%s setquota: warning: inode softlimit '%llu' smaller than minimum qunit size\n"
5803                                         "See '%s help setquota' or Lustre manual for details\n",
5804                                         progname, dqb->dqb_isoftlimit,
5805                                         progname);
5806                         break;
5807                 case 'I':
5808                         ARG2ULL(dqb->dqb_ihardlimit, optarg, 1);
5809                         limit_mask |= IHLIMIT;
5810                         if (dqb->dqb_ihardlimit &&
5811                             dqb->dqb_ihardlimit <= 1024) /* <= 1K inodes? */
5812                                 fprintf(stderr,
5813                                         "%s setquota: warning: inode hardlimit '%llu' smaller than minimum qunit size\n"
5814                                         "See '%s help setquota' or Lustre manual for details\n",
5815                                         progname, dqb->dqb_ihardlimit,
5816                                         progname);
5817                         break;
5818                 default:
5819                         fprintf(stderr,
5820                                 "%s setquota: unrecognized option '%s'\n",
5821                                 progname, argv[optind - 1]);
5822                         return CMD_HELP;
5823                 }
5824         }
5825
5826         if (qctl.qc_type == ALLQUOTA) {
5827                 fprintf(stderr,
5828                         "%s setquota: either -u or -g must be specified\n",
5829                         progname);
5830                 return CMD_HELP;
5831         }
5832
5833         if (!use_default && limit_mask == 0) {
5834                 fprintf(stderr,
5835                         "%s setquota: at least one limit must be specified\n",
5836                         progname);
5837                 return CMD_HELP;
5838         }
5839
5840         if (use_default && limit_mask != 0) {
5841                 fprintf(stderr,
5842                         "%s setquota: limits should not be specified when"
5843                         " using default quota\n",
5844                         progname);
5845                 return CMD_HELP;
5846         }
5847
5848         if (use_default && qctl.qc_id == 0) {
5849                 fprintf(stderr,
5850                         "%s setquota: can not set default quota for root"
5851                         " user/group/project\n",
5852                         progname);
5853                 return CMD_HELP;
5854         }
5855
5856         if (optind != argc - 1) {
5857                 fprintf(stderr,
5858                         "%s setquota: filesystem not specified or unexpected argument '%s'\n",
5859                         progname, argv[optind]);
5860                 return CMD_HELP;
5861         }
5862
5863         mnt = argv[optind];
5864
5865         if (use_default) {
5866                 dqb->dqb_bhardlimit = 0;
5867                 dqb->dqb_bsoftlimit = 0;
5868                 dqb->dqb_ihardlimit = 0;
5869                 dqb->dqb_isoftlimit = 0;
5870                 dqb->dqb_itime = 0;
5871                 dqb->dqb_btime = 0;
5872                 dqb->dqb_valid |= QIF_LIMITS | QIF_TIMES;
5873         } else if ((!(limit_mask & BHLIMIT) ^ !(limit_mask & BSLIMIT)) ||
5874                    (!(limit_mask & IHLIMIT) ^ !(limit_mask & ISLIMIT))) {
5875                 /* sigh, we can't just set blimits/ilimits */
5876                 struct if_quotactl tmp_qctl = {.qc_cmd  = LUSTRE_Q_GETQUOTA,
5877                                                .qc_type = qctl.qc_type,
5878                                                .qc_id   = qctl.qc_id};
5879
5880                 rc = llapi_quotactl(mnt, &tmp_qctl);
5881                 if (rc < 0)
5882                         return rc;
5883
5884                 if (!(limit_mask & BHLIMIT))
5885                         dqb->dqb_bhardlimit = tmp_qctl.qc_dqblk.dqb_bhardlimit;
5886                 if (!(limit_mask & BSLIMIT))
5887                         dqb->dqb_bsoftlimit = tmp_qctl.qc_dqblk.dqb_bsoftlimit;
5888                 if (!(limit_mask & IHLIMIT))
5889                         dqb->dqb_ihardlimit = tmp_qctl.qc_dqblk.dqb_ihardlimit;
5890                 if (!(limit_mask & ISLIMIT))
5891                         dqb->dqb_isoftlimit = tmp_qctl.qc_dqblk.dqb_isoftlimit;
5892
5893                 /* Keep grace times if we have got no softlimit arguments */
5894                 if ((limit_mask & BHLIMIT) && !(limit_mask & BSLIMIT)) {
5895                         dqb->dqb_valid |= QIF_BTIME;
5896                         dqb->dqb_btime = tmp_qctl.qc_dqblk.dqb_btime;
5897                 }
5898
5899                 if ((limit_mask & IHLIMIT) && !(limit_mask & ISLIMIT)) {
5900                         dqb->dqb_valid |= QIF_ITIME;
5901                         dqb->dqb_itime = tmp_qctl.qc_dqblk.dqb_itime;
5902                 }
5903         }
5904
5905         dqb->dqb_valid |= (limit_mask & (BHLIMIT | BSLIMIT)) ? QIF_BLIMITS : 0;
5906         dqb->dqb_valid |= (limit_mask & (IHLIMIT | ISLIMIT)) ? QIF_ILIMITS : 0;
5907
5908         rc = llapi_quotactl(mnt, &qctl);
5909         if (rc) {
5910                 if (*obd_type)
5911                         fprintf(stderr,
5912                                 "%s setquota: cannot quotactl '%s' '%s': %s",
5913                                 progname, obd_type,
5914                                 obd_uuid2str(&qctl.obd_uuid), strerror(-rc));
5915                 return rc;
5916         }
5917
5918         return 0;
5919 }
5920
5921 /* Converts seconds value into format string
5922  * result is returned in buf
5923  * Notes:
5924  *        1. result is in descenting order: 1w2d3h4m5s
5925  *        2. zero fields are not filled (except for p. 3): 5d1s
5926  *        3. zero seconds value is presented as "0s"
5927  */
5928 static char * __sec2str(time_t seconds, char *buf)
5929 {
5930         const char spec[] = "smhdw";
5931         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
5932         unsigned long c;
5933         char *tail = buf;
5934         int i;
5935
5936         for (i = sizeof(mult) / sizeof(mult[0]) - 1 ; i >= 0; i--) {
5937                 c = seconds / mult[i];
5938
5939                 if (c > 0 || (i == 0 && buf == tail))
5940                         tail += snprintf(tail, 40-(tail-buf), "%lu%c", c, spec[i]);
5941
5942                 seconds %= mult[i];
5943         }
5944
5945         return tail;
5946 }
5947
5948 static void sec2str(time_t seconds, char *buf, int rc)
5949 {
5950         char *tail = buf;
5951
5952         if (rc)
5953                 *tail++ = '[';
5954
5955         tail = __sec2str(seconds, tail);
5956
5957         if (rc && tail - buf < 39) {
5958                 *tail++ = ']';
5959                 *tail++ = 0;
5960         }
5961 }
5962
5963 static void diff2str(time_t seconds, char *buf, time_t now)
5964 {
5965
5966         buf[0] = 0;
5967         if (!seconds)
5968                 return;
5969         if (seconds <= now) {
5970                 strcpy(buf, "none");
5971                 return;
5972         }
5973         __sec2str(seconds - now, buf);
5974 }
5975
5976 static void print_quota_title(char *name, struct if_quotactl *qctl,
5977                               bool human_readable, bool show_default)
5978 {
5979         if (show_default) {
5980                 printf("Disk default %s quota:\n", qtype_name(qctl->qc_type));
5981                 printf("%15s %8s%8s%8s %8s%8s%8s\n",
5982                        "Filesystem", "bquota", "blimit", "bgrace",
5983                        "iquota", "ilimit", "igrace");
5984         } else {
5985                 printf("Disk quotas for %s %s (%cid %u):\n",
5986                        qtype_name(qctl->qc_type), name,
5987                        *qtype_name(qctl->qc_type), qctl->qc_id);
5988                 printf("%15s%8s %7s%8s%8s%8s %7s%8s%8s\n",
5989                        "Filesystem", human_readable ? "used" : "kbytes",
5990                        "quota", "limit", "grace",
5991                        "files", "quota", "limit", "grace");
5992         }
5993 }
5994
5995 static void kbytes2str(__u64 num, char *buf, int buflen, bool h)
5996 {
5997         if (!h) {
5998                 snprintf(buf, buflen, "%ju", (uintmax_t)num);
5999         } else {
6000                 if (num >> 40)
6001                         snprintf(buf, buflen, "%5.4gP",
6002                                  (double)num / ((__u64)1 << 40));
6003                 else if (num >> 30)
6004                         snprintf(buf, buflen, "%5.4gT",
6005                                  (double)num / (1 << 30));
6006                 else if (num >> 20)
6007                         snprintf(buf, buflen, "%5.4gG",
6008                                  (double)num / (1 << 20));
6009                 else if (num >> 10)
6010                         snprintf(buf, buflen, "%5.4gM",
6011                                  (double)num / (1 << 10));
6012                 else
6013                         snprintf(buf, buflen, "%ju%s", (uintmax_t)num, "k");
6014         }
6015 }
6016
6017 #define STRBUF_LEN      32
6018 static void print_quota(char *mnt, struct if_quotactl *qctl, int type,
6019                         int rc, bool h, bool show_default)
6020 {
6021         time_t now;
6022
6023         time(&now);
6024
6025         if (qctl->qc_cmd == LUSTRE_Q_GETQUOTA || qctl->qc_cmd == Q_GETOQUOTA ||
6026             qctl->qc_cmd == LUSTRE_Q_GETDEFAULT) {
6027                 int bover = 0, iover = 0;
6028                 struct obd_dqblk *dqb = &qctl->qc_dqblk;
6029                 char numbuf[3][STRBUF_LEN];
6030                 char timebuf[40];
6031                 char strbuf[STRBUF_LEN];
6032
6033                 if (dqb->dqb_bhardlimit &&
6034                     lustre_stoqb(dqb->dqb_curspace) >= dqb->dqb_bhardlimit) {
6035                         bover = 1;
6036                 } else if (dqb->dqb_bsoftlimit && dqb->dqb_btime) {
6037                         if (dqb->dqb_btime > now) {
6038                                 bover = 2;
6039                         } else {
6040                                 bover = 3;
6041                         }
6042                 }
6043
6044                 if (dqb->dqb_ihardlimit &&
6045                     dqb->dqb_curinodes >= dqb->dqb_ihardlimit) {
6046                         iover = 1;
6047                 } else if (dqb->dqb_isoftlimit && dqb->dqb_itime) {
6048                         if (dqb->dqb_itime > now) {
6049                                 iover = 2;
6050                         } else {
6051                                 iover = 3;
6052                         }
6053                 }
6054
6055
6056                 if (strlen(mnt) > 15)
6057                         printf("%s\n%15s", mnt, "");
6058                 else
6059                         printf("%15s", mnt);
6060
6061                 if (bover)
6062                         diff2str(dqb->dqb_btime, timebuf, now);
6063                 else if (show_default)
6064                         snprintf(timebuf, sizeof(timebuf), "%llu",
6065                                  dqb->dqb_btime);
6066
6067                 kbytes2str(lustre_stoqb(dqb->dqb_curspace),
6068                            strbuf, sizeof(strbuf), h);
6069                 if (rc == -EREMOTEIO)
6070                         sprintf(numbuf[0], "%s*", strbuf);
6071                 else
6072                         sprintf(numbuf[0], (dqb->dqb_valid & QIF_SPACE) ?
6073                                 "%s" : "[%s]", strbuf);
6074
6075                 kbytes2str(dqb->dqb_bsoftlimit, strbuf, sizeof(strbuf), h);
6076                 if (type == QC_GENERAL)
6077                         sprintf(numbuf[1], (dqb->dqb_valid & QIF_BLIMITS) ?
6078                                 "%s" : "[%s]", strbuf);
6079                 else
6080                         sprintf(numbuf[1], "%s", "-");
6081
6082                 kbytes2str(dqb->dqb_bhardlimit, strbuf, sizeof(strbuf), h);
6083                 sprintf(numbuf[2], (dqb->dqb_valid & QIF_BLIMITS) ?
6084                         "%s" : "[%s]", strbuf);
6085
6086                 if (show_default)
6087                         printf(" %6s %7s %7s", numbuf[1], numbuf[2], timebuf);
6088                 else
6089                         printf(" %7s%c %6s %7s %7s",
6090                                numbuf[0], bover ? '*' : ' ', numbuf[1],
6091                                numbuf[2], bover > 1 ? timebuf : "-");
6092
6093
6094                 if (iover)
6095                         diff2str(dqb->dqb_itime, timebuf, now);
6096                 else if (show_default)
6097                         snprintf(timebuf, sizeof(timebuf), "%llu",
6098                                  dqb->dqb_itime);
6099
6100                 snprintf(numbuf[0], sizeof(numbuf),
6101                          (dqb->dqb_valid & QIF_INODES) ? "%ju" : "[%ju]",
6102                          (uintmax_t)dqb->dqb_curinodes);
6103
6104                 if (type == QC_GENERAL)
6105                         sprintf(numbuf[1], (dqb->dqb_valid & QIF_ILIMITS) ?
6106                                 "%ju" : "[%ju]",
6107                                 (uintmax_t)dqb->dqb_isoftlimit);
6108                 else
6109                         sprintf(numbuf[1], "%s", "-");
6110
6111                 sprintf(numbuf[2], (dqb->dqb_valid & QIF_ILIMITS) ?
6112                         "%ju" : "[%ju]", (uintmax_t)dqb->dqb_ihardlimit);
6113
6114                 if (show_default)
6115                         printf(" %6s %7s %7s", numbuf[1], numbuf[2], timebuf);
6116                 else if (type != QC_OSTIDX)
6117                         printf(" %7s%c %6s %7s %7s",
6118                                numbuf[0], iover ? '*' : ' ', numbuf[1],
6119                                numbuf[2], iover > 1 ? timebuf : "-");
6120                 else
6121                         printf(" %7s %7s %7s %7s", "-", "-", "-", "-");
6122                 printf("\n");
6123
6124         } else if (qctl->qc_cmd == LUSTRE_Q_GETINFO ||
6125                    qctl->qc_cmd == Q_GETOINFO) {
6126                 char bgtimebuf[40];
6127                 char igtimebuf[40];
6128
6129                 sec2str(qctl->qc_dqinfo.dqi_bgrace, bgtimebuf, rc);
6130                 sec2str(qctl->qc_dqinfo.dqi_igrace, igtimebuf, rc);
6131                 printf("Block grace time: %s; Inode grace time: %s\n",
6132                        bgtimebuf, igtimebuf);
6133         }
6134 }
6135
6136 static int print_obd_quota(char *mnt, struct if_quotactl *qctl, int is_mdt,
6137                            bool h, __u64 *total)
6138 {
6139         int rc = 0, rc1 = 0, count = 0;
6140         __u32 valid = qctl->qc_valid;
6141
6142         rc = llapi_get_obd_count(mnt, &count, is_mdt);
6143         if (rc) {
6144                 fprintf(stderr, "can not get %s count: %s\n",
6145                         is_mdt ? "mdt": "ost", strerror(-rc));
6146                 return rc;
6147         }
6148
6149         for (qctl->qc_idx = 0; qctl->qc_idx < count; qctl->qc_idx++) {
6150                 qctl->qc_valid = is_mdt ? QC_MDTIDX : QC_OSTIDX;
6151                 rc = llapi_quotactl(mnt, qctl);
6152                 if (rc) {
6153                         /* It is remote client case. */
6154                         if (rc == -EOPNOTSUPP) {
6155                                 rc = 0;
6156                                 goto out;
6157                         }
6158
6159                         if (!rc1)
6160                                 rc1 = rc;
6161                         fprintf(stderr, "quotactl %s%d failed.\n",
6162                                 is_mdt ? "mdt": "ost", qctl->qc_idx);
6163                         continue;
6164                 }
6165
6166                 print_quota(obd_uuid2str(&qctl->obd_uuid), qctl,
6167                             qctl->qc_valid, 0, h, false);
6168                 *total += is_mdt ? qctl->qc_dqblk.dqb_ihardlimit :
6169                                    qctl->qc_dqblk.dqb_bhardlimit;
6170         }
6171 out:
6172         qctl->qc_valid = valid;
6173         return rc ? : rc1;
6174 }
6175
6176 static int get_print_quota(char *mnt, char *name, struct if_quotactl *qctl,
6177                            int verbose, int quiet, bool human_readable,
6178                            bool show_default)
6179 {
6180         int rc1 = 0, rc2 = 0, rc3 = 0;
6181         char *obd_type = (char *)qctl->obd_type;
6182         char *obd_uuid = (char *)qctl->obd_uuid.uuid;
6183         __u64 total_ialloc = 0, total_balloc = 0;
6184         bool use_default_for_blk = false;
6185         bool use_default_for_file = false;
6186         int inacc;
6187
6188         rc1 = llapi_quotactl(mnt, qctl);
6189         if (rc1 < 0) {
6190                 switch (rc1) {
6191                 case -ESRCH:
6192                         fprintf(stderr, "%s quotas are not enabled.\n",
6193                                 qtype_name(qctl->qc_type));
6194                         goto out;
6195                 case -EPERM:
6196                         fprintf(stderr, "Permission denied.\n");
6197                 case -ENODEV:
6198                 case -ENOENT:
6199                         /* We already got error message. */
6200                         goto out;
6201                 default:
6202                         fprintf(stderr, "Unexpected quotactl error: %s\n",
6203                                 strerror(-rc1));
6204                 }
6205         }
6206
6207         if (!show_default && qctl->qc_id == 0) {
6208                 qctl->qc_dqblk.dqb_bhardlimit = 0;
6209                 qctl->qc_dqblk.dqb_bsoftlimit = 0;
6210                 qctl->qc_dqblk.dqb_ihardlimit = 0;
6211                 qctl->qc_dqblk.dqb_isoftlimit = 0;
6212                 qctl->qc_dqblk.dqb_btime = 0;
6213                 qctl->qc_dqblk.dqb_itime = 0;
6214                 qctl->qc_dqblk.dqb_valid |= QIF_LIMITS | QIF_TIMES;
6215         }
6216
6217         if (qctl->qc_dqblk.dqb_valid & QIF_BTIME &&
6218             LQUOTA_FLAG(qctl->qc_dqblk.dqb_btime) & LQUOTA_FLAG_DEFAULT) {
6219                 use_default_for_blk = true;
6220                 qctl->qc_dqblk.dqb_btime &= LQUOTA_GRACE_MASK;
6221         }
6222
6223         if (qctl->qc_dqblk.dqb_valid & QIF_ITIME &&
6224             LQUOTA_FLAG(qctl->qc_dqblk.dqb_itime) & LQUOTA_FLAG_DEFAULT) {
6225                 use_default_for_file = true;
6226                 qctl->qc_dqblk.dqb_itime &= LQUOTA_GRACE_MASK;
6227         }
6228
6229         if ((qctl->qc_cmd == LUSTRE_Q_GETQUOTA ||
6230              qctl->qc_cmd == LUSTRE_Q_GETDEFAULT) && !quiet)
6231                 print_quota_title(name, qctl, human_readable, show_default);
6232
6233         if (rc1 && *obd_type)
6234                 fprintf(stderr, "%s %s ", obd_type, obd_uuid);
6235
6236         if (qctl->qc_valid != QC_GENERAL)
6237                 mnt = "";
6238
6239         inacc = (qctl->qc_cmd == LUSTRE_Q_GETQUOTA) &&
6240                 ((qctl->qc_dqblk.dqb_valid & (QIF_LIMITS|QIF_USAGE)) !=
6241                  (QIF_LIMITS|QIF_USAGE));
6242
6243         print_quota(mnt, qctl, QC_GENERAL, rc1, human_readable, show_default);
6244
6245         if (!show_default && verbose &&
6246             qctl->qc_valid == QC_GENERAL && qctl->qc_cmd != LUSTRE_Q_GETINFO) {
6247                 char strbuf[STRBUF_LEN];
6248
6249                 rc2 = print_obd_quota(mnt, qctl, 1, human_readable,
6250                                       &total_ialloc);
6251                 rc3 = print_obd_quota(mnt, qctl, 0, human_readable,
6252                                       &total_balloc);
6253                 kbytes2str(total_balloc, strbuf, sizeof(strbuf),
6254                            human_readable);
6255                 printf("Total allocated inode limit: %ju, total "
6256                        "allocated block limit: %s\n", (uintmax_t)total_ialloc,
6257                        strbuf);
6258         }
6259
6260         if (use_default_for_blk)
6261                 printf("%cid %u is using default block quota setting\n",
6262                        *qtype_name(qctl->qc_type), qctl->qc_id);
6263
6264         if (use_default_for_file)
6265                 printf("%cid %u is using default file quota setting\n",
6266                        *qtype_name(qctl->qc_type), qctl->qc_id);
6267
6268         if (rc1 || rc2 || rc3 || inacc)
6269                 printf("Some errors happened when getting quota info. "
6270                        "Some devices may be not working or deactivated. "
6271                        "The data in \"[]\" is inaccurate.\n");
6272 out:
6273         return rc1;
6274
6275 }
6276
6277 static int lfs_project(int argc, char **argv)
6278 {
6279         int ret = 0, err = 0, c, i;
6280         struct project_handle_control phc = { 0 };
6281         enum lfs_project_ops_t op;
6282
6283         phc.newline = true;
6284         phc.assign_projid = false;
6285         /* default action */
6286         op = LFS_PROJECT_LIST;
6287
6288         while ((c = getopt(argc, argv, "p:cCsdkr0")) != -1) {
6289                 switch (c) {
6290                 case 'c':
6291                         if (op != LFS_PROJECT_LIST) {
6292                                 fprintf(stderr,
6293                                         "%s: cannot specify '-c' '-C' '-s' together\n",
6294                                         progname);
6295                                 return CMD_HELP;
6296                         }
6297
6298                         op = LFS_PROJECT_CHECK;
6299                         break;
6300                 case 'C':
6301                         if (op != LFS_PROJECT_LIST) {
6302                                 fprintf(stderr,
6303                                         "%s: cannot specify '-c' '-C' '-s' together\n",
6304                                         progname);
6305                                 return CMD_HELP;
6306                         }
6307
6308                         op = LFS_PROJECT_CLEAR;
6309                         break;
6310                 case 's':
6311                         if (op != LFS_PROJECT_LIST) {
6312                                 fprintf(stderr,
6313                                         "%s: cannot specify '-c' '-C' '-s' together\n",
6314                                         progname);
6315                                 return CMD_HELP;
6316                         }
6317
6318                         phc.set_inherit = true;
6319                         op = LFS_PROJECT_SET;
6320                         break;
6321                 case 'd':
6322                         phc.dironly = true;
6323                         break;
6324                 case 'k':
6325                         phc.keep_projid = true;
6326                         break;
6327                 case 'r':
6328                         phc.recursive = true;
6329                         break;
6330                 case 'p':
6331                         phc.projid = strtoul(optarg, NULL, 0);
6332                         phc.assign_projid = true;
6333
6334                         break;
6335                 case '0':
6336                         phc.newline = false;
6337                         break;
6338                 default:
6339                         fprintf(stderr, "%s: invalid option '%c'\n",
6340                                 progname, optopt);
6341                         return CMD_HELP;
6342                 }
6343         }
6344
6345         if (phc.assign_projid && op == LFS_PROJECT_LIST) {
6346                 op = LFS_PROJECT_SET;
6347                 phc.set_projid = true;
6348         } else if (phc.assign_projid && op == LFS_PROJECT_SET) {
6349                 phc.set_projid = true;
6350         }
6351
6352         switch (op) {
6353         case LFS_PROJECT_CHECK:
6354                 if (phc.keep_projid) {
6355                         fprintf(stderr,
6356                                 "%s: '-k' is useless together with '-c'\n",
6357                                 progname);
6358                         return CMD_HELP;
6359                 }
6360                 break;
6361         case LFS_PROJECT_CLEAR:
6362                 if (!phc.newline) {
6363                         fprintf(stderr,
6364                                 "%s: '-0' is useless together with '-C'\n",
6365                                 progname);
6366                         return CMD_HELP;
6367                 }
6368                 if (phc.assign_projid) {
6369                         fprintf(stderr,
6370                                 "%s: '-p' is useless together with '-C'\n",
6371                                 progname);
6372                         return CMD_HELP;
6373                 }
6374                 break;
6375         case LFS_PROJECT_SET:
6376                 if (!phc.newline) {
6377                         fprintf(stderr,
6378                                 "%s: '-0' is useless together with '-s'\n",
6379                                 progname);
6380                         return CMD_HELP;
6381                 }
6382                 if (phc.keep_projid) {
6383                         fprintf(stderr,
6384                                 "%s: '-k' is useless together with '-s'\n",
6385                                 progname);
6386                         return CMD_HELP;
6387                 }
6388                 break;
6389         default:
6390                 if (!phc.newline) {
6391                         fprintf(stderr,
6392                                 "%s: '-0' is useless for list operations\n",
6393                                 progname);
6394                         return CMD_HELP;
6395                 }
6396                 break;
6397         }
6398
6399         argv += optind;
6400         argc -= optind;
6401         if (argc == 0) {
6402                 fprintf(stderr, "%s: missing file or directory target(s)\n",
6403                         progname);
6404                 return CMD_HELP;
6405         }
6406
6407         for (i = 0; i < argc; i++) {
6408                 switch (op) {
6409                 case LFS_PROJECT_CHECK:
6410                         err = lfs_project_check(argv[i], &phc);
6411                         break;
6412                 case LFS_PROJECT_LIST:
6413                         err = lfs_project_list(argv[i], &phc);
6414                         break;
6415                 case LFS_PROJECT_CLEAR:
6416                         err = lfs_project_clear(argv[i], &phc);
6417                         break;
6418                 case LFS_PROJECT_SET:
6419                         err = lfs_project_set(argv[i], &phc);
6420                         break;
6421                 default:
6422                         break;
6423                 }
6424                 if (err && !ret)
6425                         ret = err;
6426         }
6427
6428         return ret;
6429 }
6430
6431 static int lfs_quota(int argc, char **argv)
6432 {
6433         int c;
6434         char *mnt, *name = NULL;
6435         struct if_quotactl qctl = { .qc_cmd = LUSTRE_Q_GETQUOTA,
6436                                     .qc_type = ALLQUOTA };
6437         char *obd_uuid = (char *)qctl.obd_uuid.uuid;
6438         int rc = 0, rc1 = 0, verbose = 0, quiet = 0;
6439         char *endptr;
6440         __u32 valid = QC_GENERAL, idx = 0;
6441         bool human_readable = false;
6442         bool show_default = false;
6443         int qtype;
6444
6445         while ((c = getopt(argc, argv, "gGi:I:o:pPqtuUvh")) != -1) {
6446                 switch (c) {
6447                 case 'U':
6448                         show_default = true;
6449                 case 'u':
6450                         qtype = USRQUOTA;
6451                         goto quota_type;
6452                 case 'G':
6453                         show_default = true;
6454                 case 'g':
6455                         qtype = GRPQUOTA;
6456                         goto quota_type;
6457                 case 'P':
6458                         show_default = true;
6459                 case 'p':
6460                         qtype = PRJQUOTA;
6461 quota_type:
6462                         if (qctl.qc_type != ALLQUOTA) {
6463                                 fprintf(stderr,
6464                                         "%s quota: only one of -u, -g, or -p may be specified\n",
6465                                         progname);
6466                                 return CMD_HELP;
6467                         }
6468                         qctl.qc_type = qtype;
6469                         break;
6470                 case 't':
6471                         qctl.qc_cmd = LUSTRE_Q_GETINFO;
6472                         break;
6473                 case 'o':
6474                         valid = qctl.qc_valid = QC_UUID;
6475                         snprintf(obd_uuid, sizeof(qctl.obd_uuid), "%s", optarg);
6476                         break;
6477                 case 'i':
6478                         valid = qctl.qc_valid = QC_MDTIDX;
6479                         idx = qctl.qc_idx = atoi(optarg);
6480                         if (idx == 0 && *optarg != '0') {
6481                                 fprintf(stderr,
6482                                         "%s quota: invalid MDT index '%s'\n",
6483                                         progname, optarg);
6484                                 return CMD_HELP;
6485                         }
6486                         break;
6487                 case 'I':
6488                         valid = qctl.qc_valid = QC_OSTIDX;
6489                         idx = qctl.qc_idx = atoi(optarg);
6490                         if (idx == 0 && *optarg != '0') {
6491                                 fprintf(stderr,
6492                                         "%s quota: invalid OST index '%s'\n",
6493                                         progname, optarg);
6494                                 return CMD_HELP;
6495                         }
6496                         break;
6497                 case 'v':
6498                         verbose = 1;
6499                         break;
6500                 case 'q':
6501                         quiet = 1;
6502                         break;
6503                 case 'h':
6504                         human_readable = true;
6505                         break;
6506                 default:
6507                         fprintf(stderr, "%s quota: unrecognized option '%s'\n",
6508                                 progname, argv[optind - 1]);
6509                         return CMD_HELP;
6510                 }
6511         }
6512
6513         /* current uid/gid info for "lfs quota /path/to/lustre/mount" */
6514         if (qctl.qc_cmd == LUSTRE_Q_GETQUOTA && qctl.qc_type == ALLQUOTA &&
6515             optind == argc - 1 && !show_default) {
6516
6517                 qctl.qc_cmd = LUSTRE_Q_GETQUOTA;
6518                 qctl.qc_valid = valid;
6519                 qctl.qc_idx = idx;
6520
6521                 for (qtype = USRQUOTA; qtype <= GRPQUOTA; qtype++) {
6522                         qctl.qc_type = qtype;
6523                         if (qtype == USRQUOTA) {
6524                                 qctl.qc_id = geteuid();
6525                                 rc = uid2name(&name, qctl.qc_id);
6526                         } else {
6527                                 qctl.qc_id = getegid();
6528                                 rc = gid2name(&name, qctl.qc_id);
6529                         }
6530                         if (rc)
6531                                 name = "<unknown>";
6532                         mnt = argv[optind];
6533                         rc1 = get_print_quota(mnt, name, &qctl, verbose, quiet,
6534                                               human_readable, show_default);
6535                         if (rc1 && !rc)
6536                                 rc = rc1;
6537                 }
6538                 return rc;
6539         /* lfs quota -u username /path/to/lustre/mount */
6540         } else if (qctl.qc_cmd == LUSTRE_Q_GETQUOTA) {
6541                 /* options should be followed by u/g-name and mntpoint */
6542                 if ((!show_default && optind + 2 != argc) ||
6543                     (show_default && optind + 1 != argc) ||
6544                     qctl.qc_type == ALLQUOTA) {
6545                         fprintf(stderr,
6546                                 "%s quota: name and mount point must be specified\n",
6547                                 progname);
6548                         return CMD_HELP;
6549                 }
6550
6551                 if (!show_default) {
6552                         name = argv[optind++];
6553                         switch (qctl.qc_type) {
6554                         case USRQUOTA:
6555                                 rc = name2uid(&qctl.qc_id, name);
6556                                 break;
6557                         case GRPQUOTA:
6558                                 rc = name2gid(&qctl.qc_id, name);
6559                                 break;
6560                         case PRJQUOTA:
6561                                 rc = name2projid(&qctl.qc_id, name);
6562                                 break;
6563                         default:
6564                                 rc = -ENOTSUP;
6565                                 break;
6566                         }
6567                 } else {
6568                         qctl.qc_valid = QC_GENERAL;
6569                         qctl.qc_cmd = LUSTRE_Q_GETDEFAULT;
6570                         qctl.qc_id = 0;
6571                 }
6572
6573                 if (rc) {
6574                         qctl.qc_id = strtoul(name, &endptr, 10);
6575                         if (*endptr != '\0') {
6576                                 fprintf(stderr, "%s quota: invalid id '%s'\n",
6577                                         progname, name);
6578                                 return CMD_HELP;
6579                         }
6580                 }
6581         } else if (optind + 1 != argc || qctl.qc_type == ALLQUOTA) {
6582                 fprintf(stderr, "%s quota: missing quota info argument(s)\n",
6583                         progname);
6584                 return CMD_HELP;
6585         }
6586
6587         mnt = argv[optind];
6588         rc = get_print_quota(mnt, name, &qctl, verbose, quiet,
6589                              human_readable, show_default);
6590         return rc;
6591 }
6592 #endif /* HAVE_SYS_QUOTA_H! */
6593
6594 static int flushctx_ioctl(char *mp)
6595 {
6596         int fd, rc;
6597
6598         fd = open(mp, O_RDONLY);
6599         if (fd == -1) {
6600                 fprintf(stderr, "flushctx: error open %s: %s\n",
6601                         mp, strerror(errno));
6602                 return -1;
6603         }
6604
6605         rc = ioctl(fd, LL_IOC_FLUSHCTX);
6606         if (rc == -1)
6607                 fprintf(stderr, "flushctx: error ioctl %s: %s\n",
6608                         mp, strerror(errno));
6609
6610         close(fd);
6611         return rc;
6612 }
6613
6614 static int lfs_flushctx(int argc, char **argv)
6615 {
6616         int     kdestroy = 0, c;
6617         char    mntdir[PATH_MAX] = {'\0'};
6618         int     index = 0;
6619         int     rc = 0;
6620
6621         while ((c = getopt(argc, argv, "k")) != -1) {
6622                 switch (c) {
6623                 case 'k':
6624                         kdestroy = 1;
6625                         break;
6626                 default:
6627                         fprintf(stderr, "error: %s: option '-%c' "
6628                                         "unrecognized\n", argv[0], c);
6629                         return CMD_HELP;
6630                 }
6631         }
6632
6633         if (kdestroy) {
6634             if ((rc = system("kdestroy > /dev/null")) != 0) {
6635                 rc = WEXITSTATUS(rc);
6636                 fprintf(stderr, "error destroying tickets: %d, continuing\n", rc);
6637             }
6638         }
6639
6640         if (optind >= argc) {
6641                 /* flush for all mounted lustre fs. */
6642                 while (!llapi_search_mounts(NULL, index++, mntdir, NULL)) {
6643                         /* Check if we have a mount point */
6644                         if (mntdir[0] == '\0')
6645                                 continue;
6646
6647                         if (flushctx_ioctl(mntdir))
6648                                 rc = -1;
6649
6650                         mntdir[0] = '\0'; /* avoid matching in next loop */
6651                 }
6652         } else {
6653                 /* flush fs as specified */
6654                 while (optind < argc) {
6655                         if (flushctx_ioctl(argv[optind++]))
6656                                 rc = -1;
6657                 }
6658         }
6659         return rc;
6660 }
6661
6662 static int lfs_cp(int argc, char **argv)
6663 {
6664         fprintf(stderr, "remote client copy file(s).\n"
6665                 "obsolete, does not support it anymore.\n");
6666         return 0;
6667 }
6668
6669 static int lfs_ls(int argc, char **argv)
6670 {
6671         fprintf(stderr, "remote client lists directory contents.\n"
6672                 "obsolete, does not support it anymore.\n");
6673         return 0;
6674 }
6675
6676 static int lfs_changelog(int argc, char **argv)
6677 {
6678         void *changelog_priv;
6679         struct changelog_rec *rec;
6680         long long startrec = 0, endrec = 0;
6681         char *mdd;
6682         struct option long_opts[] = {
6683                 { .val = 'f', .name = "follow", .has_arg = no_argument },
6684                 { .name = NULL } };
6685         char short_opts[] = "f";
6686         int rc, follow = 0;
6687
6688         while ((rc = getopt_long(argc, argv, short_opts,
6689                 long_opts, NULL)) != -1) {
6690                 switch (rc) {
6691                 case 'f':
6692                         follow++;
6693                         break;
6694                 default:
6695                         fprintf(stderr,
6696                                 "%s changelog: unrecognized option '%s'\n",
6697                                 progname, argv[optind - 1]);
6698                         return CMD_HELP;
6699                 }
6700         }
6701         if (optind >= argc) {
6702                 fprintf(stderr, "%s changelog: mdtname must be specified\n",
6703                         progname);
6704                 return CMD_HELP;
6705         }
6706
6707         mdd = argv[optind++];
6708         if (argc > optind)
6709                 startrec = strtoll(argv[optind++], NULL, 10);
6710         if (argc > optind)
6711                 endrec = strtoll(argv[optind++], NULL, 10);
6712
6713         rc = llapi_changelog_start(&changelog_priv,
6714                                    CHANGELOG_FLAG_BLOCK |
6715                                    CHANGELOG_FLAG_JOBID |
6716                                    CHANGELOG_FLAG_EXTRA_FLAGS |
6717                                    (follow ? CHANGELOG_FLAG_FOLLOW : 0),
6718                                    mdd, startrec);
6719         if (rc < 0) {
6720                 fprintf(stderr, "%s changelog: cannot start changelog: %s\n",
6721                         progname, strerror(errno = -rc));
6722                 return rc;
6723         }
6724
6725         rc = llapi_changelog_set_xflags(changelog_priv,
6726                                         CHANGELOG_EXTRA_FLAG_UIDGID |
6727                                         CHANGELOG_EXTRA_FLAG_NID |
6728                                         CHANGELOG_EXTRA_FLAG_OMODE |
6729                                         CHANGELOG_EXTRA_FLAG_XATTR);
6730         if (rc < 0) {
6731                 fprintf(stderr,
6732                         "%s changelog: cannot set xflags for changelog: %s\n",
6733                         progname, strerror(errno = -rc));
6734                 return rc;
6735         }
6736
6737         while ((rc = llapi_changelog_recv(changelog_priv, &rec)) == 0) {
6738                 time_t secs;
6739                 struct tm ts;
6740
6741                 if (endrec && rec->cr_index > endrec) {
6742                         llapi_changelog_free(&rec);
6743                         break;
6744                 }
6745                 if (rec->cr_index < startrec) {
6746                         llapi_changelog_free(&rec);
6747                         continue;
6748                 }
6749
6750                 secs = rec->cr_time >> 30;
6751                 gmtime_r(&secs, &ts);
6752                 printf("%ju %02d%-5s %02d:%02d:%02d.%09d %04d.%02d.%02d "
6753                        "0x%x t="DFID, (uintmax_t)rec->cr_index, rec->cr_type,
6754                        changelog_type2str(rec->cr_type),
6755                        ts.tm_hour, ts.tm_min, ts.tm_sec,
6756                        (int)(rec->cr_time & ((1 << 30) - 1)),
6757                        ts.tm_year + 1900, ts.tm_mon + 1, ts.tm_mday,
6758                        rec->cr_flags & CLF_FLAGMASK, PFID(&rec->cr_tfid));
6759
6760                 if (rec->cr_flags & CLF_JOBID) {
6761                         struct changelog_ext_jobid *jid =
6762                                 changelog_rec_jobid(rec);
6763
6764                         if (jid->cr_jobid[0] != '\0')
6765                                 printf(" j=%s", jid->cr_jobid);
6766                 }
6767
6768                 if (rec->cr_flags & CLF_EXTRA_FLAGS) {
6769                         struct changelog_ext_extra_flags *ef =
6770                                 changelog_rec_extra_flags(rec);
6771
6772                         printf(" ef=0x%llx", ef->cr_extra_flags);
6773
6774                         if (ef->cr_extra_flags & CLFE_UIDGID) {
6775                                 struct changelog_ext_uidgid *uidgid =
6776                                         changelog_rec_uidgid(rec);
6777
6778                                 printf(" u=%llu:%llu",
6779                                        uidgid->cr_uid, uidgid->cr_gid);
6780                         }
6781                         if (ef->cr_extra_flags & CLFE_NID) {
6782                                 struct changelog_ext_nid *nid =
6783                                         changelog_rec_nid(rec);
6784
6785                                 printf(" nid=%s",
6786                                        libcfs_nid2str(nid->cr_nid));
6787                         }
6788
6789                         if (ef->cr_extra_flags & CLFE_OPEN) {
6790                                 struct changelog_ext_openmode *omd =
6791                                         changelog_rec_openmode(rec);
6792                                 char mode[] = "---";
6793
6794                                 /* exec mode must be exclusive */
6795                                 if (omd->cr_openflags & MDS_FMODE_EXEC) {
6796                                         mode[2] = 'x';
6797                                 } else {
6798                                         if (omd->cr_openflags & MDS_FMODE_READ)
6799                                                 mode[0] = 'r';
6800                                         if (omd->cr_openflags &
6801                                             (MDS_FMODE_WRITE |
6802                                              MDS_OPEN_TRUNC |
6803                                              MDS_OPEN_APPEND))
6804                                                 mode[1] = 'w';
6805                                 }
6806
6807                                 if (strcmp(mode, "---") != 0)
6808                                         printf(" m=%s", mode);
6809
6810                         }
6811
6812                         if (ef->cr_extra_flags & CLFE_XATTR) {
6813                                 struct changelog_ext_xattr *xattr =
6814                                         changelog_rec_xattr(rec);
6815
6816                                 if (xattr->cr_xattr[0] != '\0')
6817                                         printf(" x=%s", xattr->cr_xattr);
6818                         }
6819                 }
6820
6821                 if (rec->cr_namelen)
6822                         printf(" p="DFID" %.*s", PFID(&rec->cr_pfid),
6823                                rec->cr_namelen, changelog_rec_name(rec));
6824
6825                 if (rec->cr_flags & CLF_RENAME) {
6826                         struct changelog_ext_rename *rnm =
6827                                 changelog_rec_rename(rec);
6828
6829                         if (!fid_is_zero(&rnm->cr_sfid))
6830                                 printf(" s="DFID" sp="DFID" %.*s",
6831                                        PFID(&rnm->cr_sfid),
6832                                        PFID(&rnm->cr_spfid),
6833                                        (int)changelog_rec_snamelen(rec),
6834                                        changelog_rec_sname(rec));
6835                 }
6836                 printf("\n");
6837
6838                 llapi_changelog_free(&rec);
6839         }
6840
6841         llapi_changelog_fini(&changelog_priv);
6842
6843         if (rc < 0)
6844                 fprintf(stderr, "%s changelog: cannot access changelog: %s\n",
6845                         progname, strerror(errno = -rc));
6846
6847         return (rc == 1 ? 0 : rc);
6848 }
6849
6850 static int lfs_changelog_clear(int argc, char **argv)
6851 {
6852         long long endrec;
6853         int rc;
6854
6855         if (argc != 4)
6856                 return CMD_HELP;
6857
6858         endrec = strtoll(argv[3], NULL, 10);
6859
6860         rc = llapi_changelog_clear(argv[1], argv[2], endrec);
6861
6862         if (rc == -EINVAL)
6863                 fprintf(stderr, "%s: record out of range: %llu\n",
6864                         argv[0], endrec);
6865         else if (rc == -ENOENT)
6866                 fprintf(stderr, "%s: no changelog user: %s\n",
6867                         argv[0], argv[2]);
6868         else if (rc)
6869                 fprintf(stderr, "%s error: %s\n", argv[0],
6870                         strerror(-rc));
6871
6872         if (rc)
6873                 errno = -rc;
6874
6875         return rc;
6876 }
6877
6878 static int lfs_fid2path(int argc, char **argv)
6879 {
6880         struct option long_opts[] = {
6881                 { .val = 'c',   .name = "cur",  .has_arg = no_argument },
6882                 { .val = 'l',   .name = "link", .has_arg = required_argument },
6883                 { .val = 'r',   .name = "rec",  .has_arg = required_argument },
6884                 { .name = NULL } };
6885         char  short_opts[] = "cl:r:";
6886         char *device, *fid, *path;
6887         long long recno = -1;
6888         int linkno = -1;
6889         int lnktmp;
6890         int printcur = 0;
6891         int rc = 0;
6892         char *endptr = NULL;
6893
6894         while ((rc = getopt_long(argc, argv, short_opts,
6895                 long_opts, NULL)) != -1) {
6896                 switch (rc) {
6897                 case 'c':
6898                         printcur++;
6899                         break;
6900                 case 'l':
6901                         linkno = strtol(optarg, &endptr, 10);
6902                         if (*endptr != '\0') {
6903                                 fprintf(stderr,
6904                                         "%s fid2path: invalid linkno '%s'\n",
6905                                         progname, optarg);
6906                                 return CMD_HELP;
6907                         }
6908                         break;
6909                 case 'r':
6910                         recno = strtoll(optarg, &endptr, 10);
6911                         if (*endptr != '\0') {
6912                                 fprintf(stderr,
6913                                         "%s fid2path: invalid recno '%s'\n",
6914                                         progname, optarg);
6915                                 return CMD_HELP;
6916                         }
6917                         break;
6918                 default:
6919                         fprintf(stderr,
6920                                 "%s fid2path: unrecognized option '%s'\n",
6921                                 progname, argv[optind - 1]);
6922                         return CMD_HELP;
6923                 }
6924         }
6925
6926         if (argc < 3) {
6927                 fprintf(stderr,
6928                         "%s fid2path: <fsname|rootpath> and <fid>... must be specified\n",
6929                         progname);
6930                 return CMD_HELP;
6931         }
6932
6933         device = argv[optind++];
6934         path = calloc(1, PATH_MAX);
6935         if (path == NULL) {
6936                 rc = -errno;
6937                 fprintf(stderr,
6938                         "%s fid2path: cannot allocate memory for path: %s\n",
6939                         progname, strerror(-rc));
6940                 return rc;
6941         }
6942
6943         rc = 0;
6944         while (optind < argc) {
6945                 fid = argv[optind++];
6946
6947                 lnktmp = (linkno >= 0) ? linkno : 0;
6948                 while (1) {
6949                         int oldtmp = lnktmp;
6950                         long long rectmp = recno;
6951                         int rc2;
6952                         rc2 = llapi_fid2path(device, fid, path, PATH_MAX,
6953                                              &rectmp, &lnktmp);
6954                         if (rc2 < 0) {
6955                                 fprintf(stderr,
6956                                         "%s fid2path: cannot find '%s': %s\n",
6957                                         progname, fid, strerror(errno = -rc2));
6958                                 if (rc == 0)
6959                                         rc = rc2;
6960                                 break;
6961                         }
6962
6963                         if (printcur)
6964                                 fprintf(stdout, "%lld ", rectmp);
6965                         if (device[0] == '/') {
6966                                 fprintf(stdout, "%s", device);
6967                                 if (device[strlen(device) - 1] != '/')
6968                                         fprintf(stdout, "/");
6969                         } else if (path[0] == '\0') {
6970                                 fprintf(stdout, "/");
6971                         }
6972                         fprintf(stdout, "%s\n", path);
6973
6974                         if (linkno >= 0)
6975                                 /* specified linkno */
6976                                 break;
6977                         if (oldtmp == lnktmp)
6978                                 /* no more links */
6979                                 break;
6980                 }
6981         }
6982
6983         free(path);
6984         return rc;
6985 }
6986
6987 static int lfs_path2fid(int argc, char **argv)
6988 {
6989         struct option long_opts[] = {
6990                 { .val = 'p', .name = "parents", .has_arg = no_argument },
6991                 { .name = NULL } };
6992         char            **path;
6993         const char        short_opts[] = "p";
6994         const char       *sep = "";
6995         struct lu_fid     fid;
6996         int               rc = 0;
6997         bool              show_parents = false;
6998
6999         while ((rc = getopt_long(argc, argv, short_opts,
7000                                  long_opts, NULL)) != -1) {
7001                 switch (rc) {
7002                 case 'p':
7003                         show_parents = true;
7004                         break;
7005                 default:
7006                         fprintf(stderr,
7007                                 "%s path2fid: unrecognized option '%s'\n",
7008                                 progname, argv[optind - 1]);
7009                         return CMD_HELP;
7010                 }
7011         }
7012
7013         if (optind > argc - 1) {
7014                 fprintf(stderr, "%s path2fid: FILE... must be specified\n",
7015                         progname);
7016                 return CMD_HELP;
7017         }
7018         else if (optind < argc - 1)
7019                 sep = ": ";
7020
7021         rc = 0;
7022         for (path = argv + optind; *path != NULL; path++) {
7023                 int err = 0;
7024                 if (!show_parents) {
7025                         err = llapi_path2fid(*path, &fid);
7026                         if (!err)
7027                                 printf("%s%s"DFID"\n",
7028                                        *sep != '\0' ? *path : "", sep,
7029                                        PFID(&fid));
7030                 } else {
7031                         char            name[NAME_MAX + 1];
7032                         unsigned int    linkno = 0;
7033
7034                         while ((err = llapi_path2parent(*path, linkno, &fid,
7035                                                 name, sizeof(name))) == 0) {
7036                                 if (*sep != '\0' && linkno == 0)
7037                                         printf("%s%s", *path, sep);
7038
7039                                 printf("%s"DFID"/%s", linkno != 0 ? "\t" : "",
7040                                        PFID(&fid), name);
7041                                 linkno++;
7042                         }
7043
7044                         /* err == -ENODATA is end-of-loop */
7045                         if (linkno > 0 && err == -ENODATA) {
7046                                 printf("\n");
7047                                 err = 0;
7048                         }
7049                 }
7050
7051                 if (err) {
7052                         fprintf(stderr,
7053                                 "%s path2fid: cannot get %sfid for '%s': %s\n",
7054                                 progname, show_parents ? "parent " : "", *path,
7055                                 strerror(-err));
7056                         if (rc == 0) {
7057                                 rc = err;
7058                                 errno = -err;
7059                         }
7060                 }
7061         }
7062
7063         return rc;
7064 }
7065
7066 static int lfs_data_version(int argc, char **argv)
7067 {
7068         char *path;
7069         __u64 data_version;
7070         int fd;
7071         int rc;
7072         int c;
7073         int data_version_flags = LL_DV_RD_FLUSH; /* Read by default */
7074
7075         if (argc < 2) {
7076                 fprintf(stderr, "%s data_version: FILE must be specified\n",
7077                         progname);
7078                 return CMD_HELP;
7079         }
7080
7081         while ((c = getopt(argc, argv, "nrw")) != -1) {
7082                 switch (c) {
7083                 case 'n':
7084                         data_version_flags = 0;
7085                         break;
7086                 case 'r':
7087                         data_version_flags |= LL_DV_RD_FLUSH;
7088                         break;
7089                 case 'w':
7090                         data_version_flags |= LL_DV_WR_FLUSH;
7091                         break;
7092                 default:
7093                         fprintf(stderr,
7094                                 "%s data_version: unrecognized option '%s'\n",
7095                                 progname, argv[optind - 1]);
7096                         return CMD_HELP;
7097                 }
7098         }
7099         if (optind == argc) {
7100                 fprintf(stderr, "%s data_version: FILE must be specified\n",
7101                         progname);
7102                 return CMD_HELP;
7103         }
7104
7105         path = argv[optind];
7106         fd = open(path, O_RDONLY);
7107         if (fd < 0) {
7108                 rc = -errno;
7109                 fprintf(stderr, "%s data_version: cannot open file '%s': %s\n",
7110                         progname, path, strerror(-rc));
7111                 return rc;
7112         }
7113
7114         rc = llapi_get_data_version(fd, &data_version, data_version_flags);
7115         if (rc < 0)
7116                 fprintf(stderr,
7117                         "%s data_version: cannot get version for '%s': %s\n",
7118                         progname, path, strerror(-rc));
7119         else
7120                 printf("%ju" "\n", (uintmax_t)data_version);
7121
7122         close(fd);
7123         return rc;
7124 }
7125
7126 static int lfs_hsm_state(int argc, char **argv)
7127 {
7128         int rc;
7129         int i = 1;
7130         char *path;
7131         struct hsm_user_state hus;
7132
7133         if (argc < 2)
7134                 return CMD_HELP;
7135
7136         do {
7137                 path = argv[i];
7138
7139                 rc = llapi_hsm_state_get(path, &hus);
7140                 if (rc) {
7141                         fprintf(stderr, "can't get hsm state for %s: %s\n",
7142                                 path, strerror(errno = -rc));
7143                         return rc;
7144                 }
7145
7146                 /* Display path name and status flags */
7147                 printf("%s: (0x%08x)", path, hus.hus_states);
7148
7149                 if (hus.hus_states & HS_RELEASED)
7150                         printf(" released");
7151                 if (hus.hus_states & HS_EXISTS)
7152                         printf(" exists");
7153                 if (hus.hus_states & HS_DIRTY)
7154                         printf(" dirty");
7155                 if (hus.hus_states & HS_ARCHIVED)
7156                         printf(" archived");
7157                 /* Display user-settable flags */
7158                 if (hus.hus_states & HS_NORELEASE)
7159                         printf(" never_release");
7160                 if (hus.hus_states & HS_NOARCHIVE)
7161                         printf(" never_archive");
7162                 if (hus.hus_states & HS_LOST)
7163                         printf(" lost_from_hsm");
7164
7165                 if (hus.hus_archive_id != 0)
7166                         printf(", archive_id:%d", hus.hus_archive_id);
7167                 printf("\n");
7168
7169         } while (++i < argc);
7170
7171         return 0;
7172 }
7173
7174 #define LFS_HSM_SET   0
7175 #define LFS_HSM_CLEAR 1
7176
7177 /**
7178  * Generic function to set or clear HSM flags.
7179  * Used by hsm_set and hsm_clear.
7180  *
7181  * @mode  if LFS_HSM_SET, set the flags, if LFS_HSM_CLEAR, clear the flags.
7182  */
7183 static int lfs_hsm_change_flags(int argc, char **argv, int mode)
7184 {
7185         struct option long_opts[] = {
7186         { .val = 'A',   .name = "archived",     .has_arg = no_argument },
7187         { .val = 'a',   .name = "noarchive",    .has_arg = no_argument },
7188         { .val = 'd',   .name = "dirty",        .has_arg = no_argument },
7189         { .val = 'e',   .name = "exists",       .has_arg = no_argument },
7190         { .val = 'l',   .name = "lost",         .has_arg = no_argument },
7191         { .val = 'r',   .name = "norelease",    .has_arg = no_argument },
7192         { .val = 'i',   .name = "archive-id",   .has_arg = required_argument },
7193         { .name = NULL } };
7194         char short_opts[] = "lraAdei:";
7195         __u64 mask = 0;
7196         int c, rc;
7197         char *path;
7198         __u32 archive_id = 0;
7199         char *end = NULL;
7200
7201         if (argc < 3)
7202                 return CMD_HELP;
7203
7204         while ((c = getopt_long(argc, argv, short_opts,
7205                                 long_opts, NULL)) != -1) {
7206                 switch (c) {
7207                 case 'l':
7208                         mask |= HS_LOST;
7209                         break;
7210                 case 'a':
7211                         mask |= HS_NOARCHIVE;
7212                         break;
7213                 case 'A':
7214                         mask |= HS_ARCHIVED;
7215                         break;
7216                 case 'r':
7217                         mask |= HS_NORELEASE;
7218                         break;
7219                 case 'd':
7220                         mask |= HS_DIRTY;
7221                         break;
7222                 case 'e':
7223                         mask |= HS_EXISTS;
7224                         break;
7225                 case 'i':
7226                         archive_id = strtol(optarg, &end, 10);
7227                         if (*end != '\0') {
7228                                 fprintf(stderr, "invalid archive_id: '%s'\n",
7229                                         end);
7230                                 return CMD_HELP;
7231                         }
7232                         break;
7233                 case '?':
7234                         return CMD_HELP;
7235                 default:
7236                         fprintf(stderr, "error: %s: option '%s' unrecognized\n",
7237                                 argv[0], argv[optind - 1]);
7238                         return CMD_HELP;
7239                 }
7240         }
7241
7242         /* User should have specified a flag */
7243         if (mask == 0)
7244                 return CMD_HELP;
7245
7246         while (optind < argc) {
7247
7248                 path = argv[optind];
7249
7250                 /* If mode == 0, this means we apply the mask. */
7251                 if (mode == LFS_HSM_SET)
7252                         rc = llapi_hsm_state_set(path, mask, 0, archive_id);
7253                 else
7254                         rc = llapi_hsm_state_set(path, 0, mask, 0);
7255
7256                 if (rc != 0) {
7257                         fprintf(stderr, "Can't change hsm flags for %s: %s\n",
7258                                 path, strerror(errno = -rc));
7259                         return rc;
7260                 }
7261                 optind++;
7262         }
7263
7264         return 0;
7265 }
7266
7267 static int lfs_hsm_action(int argc, char **argv)
7268 {
7269         int                              rc;
7270         int                              i = 1;
7271         char                            *path;
7272         struct hsm_current_action        hca;
7273         struct hsm_extent                he;
7274         enum hsm_user_action             hua;
7275         enum hsm_progress_states         hps;
7276
7277         if (argc < 2)
7278                 return CMD_HELP;
7279
7280         do {
7281                 path = argv[i];
7282
7283                 rc = llapi_hsm_current_action(path, &hca);
7284                 if (rc) {
7285                         fprintf(stderr, "can't get hsm action for %s: %s\n",
7286                                 path, strerror(errno = -rc));
7287                         return rc;
7288                 }
7289                 he = hca.hca_location;
7290                 hua = hca.hca_action;
7291                 hps = hca.hca_state;
7292
7293                 printf("%s: %s", path, hsm_user_action2name(hua));
7294
7295                 /* Skip file without action */
7296                 if (hca.hca_action == HUA_NONE) {
7297                         printf("\n");
7298                         continue;
7299                 }
7300
7301                 printf(" %s ", hsm_progress_state2name(hps));
7302
7303                 if ((hps == HPS_RUNNING) &&
7304                     (hua == HUA_ARCHIVE || hua == HUA_RESTORE))
7305                         printf("(%llu bytes moved)\n",
7306                                (unsigned long long)he.length);
7307                 else if ((he.offset + he.length) == LUSTRE_EOF)
7308                         printf("(from %llu to EOF)\n",
7309                                (unsigned long long)he.offset);
7310                 else
7311                         printf("(from %llu to %llu)\n",
7312                                (unsigned long long)he.offset,
7313                                (unsigned long long)(he.offset + he.length));
7314
7315         } while (++i < argc);
7316
7317         return 0;
7318 }
7319
7320 static int lfs_hsm_set(int argc, char **argv)
7321 {
7322         return lfs_hsm_change_flags(argc, argv, LFS_HSM_SET);
7323 }
7324
7325 static int lfs_hsm_clear(int argc, char **argv)
7326 {
7327         return lfs_hsm_change_flags(argc, argv, LFS_HSM_CLEAR);
7328 }
7329
7330 /**
7331  * Check file state and return its fid, to be used by lfs_hsm_request().
7332  *
7333  * \param[in]     file      Path to file to check
7334  * \param[in,out] fid       Pointer to allocated lu_fid struct.
7335  * \param[in,out] last_dev  Pointer to last device id used.
7336  *
7337  * \return 0 on success.
7338  */
7339 static int lfs_hsm_prepare_file(const char *file, struct lu_fid *fid,
7340                                 dev_t *last_dev)
7341 {
7342         struct stat     st;
7343         int             rc;
7344
7345         rc = lstat(file, &st);
7346         if (rc) {
7347                 fprintf(stderr, "Cannot stat %s: %s\n", file, strerror(errno));
7348                 return -errno;
7349         }
7350         /* Checking for regular file as archiving as posix copytool
7351          * rejects archiving files other than regular files
7352          */
7353         if (!S_ISREG(st.st_mode)) {
7354                 fprintf(stderr, "error: \"%s\" is not a regular file\n", file);
7355                 return CMD_HELP;
7356         }
7357         /* A request should be ... */
7358         if (*last_dev != st.st_dev && *last_dev != 0) {
7359                 fprintf(stderr, "All files should be "
7360                         "on the same filesystem: %s\n", file);
7361                 return -EINVAL;
7362         }
7363         *last_dev = st.st_dev;
7364
7365         rc = llapi_path2fid(file, fid);
7366         if (rc) {
7367                 fprintf(stderr, "Cannot read FID of %s: %s\n",
7368                         file, strerror(-rc));
7369                 return rc;
7370         }
7371         return 0;
7372 }
7373
7374 /* Fill an HSM HUR item with a given file name.
7375  *
7376  * If mntpath is set, then the filename is actually a FID, and no
7377  * lookup on the filesystem will be performed.
7378  *
7379  * \param[in]  hur         the user request to fill
7380  * \param[in]  idx         index of the item inside the HUR to fill
7381  * \param[in]  mntpath     mountpoint of Lustre
7382  * \param[in]  fname       filename (if mtnpath is NULL)
7383  *                         or FID (if mntpath is set)
7384  * \param[in]  last_dev    pointer to last device id used
7385  *
7386  * \retval 0 on success
7387  * \retval CMD_HELP or a negative errno on error
7388  */
7389 static int fill_hur_item(struct hsm_user_request *hur, unsigned int idx,
7390                          const char *mntpath, const char *fname,
7391                          dev_t *last_dev)
7392 {
7393         struct hsm_user_item *hui = &hur->hur_user_item[idx];
7394         int rc;
7395
7396         hui->hui_extent.length = -1;
7397
7398         if (mntpath != NULL) {
7399                 if (*fname == '[')
7400                         fname++;
7401                 rc = sscanf(fname, SFID, RFID(&hui->hui_fid));
7402                 if (rc == 3) {
7403                         rc = 0;
7404                 } else {
7405                         fprintf(stderr, "hsm: '%s' is not a valid FID\n",
7406                                 fname);
7407                         rc = -EINVAL;
7408                 }
7409         } else {
7410                 rc = lfs_hsm_prepare_file(fname, &hui->hui_fid, last_dev);
7411         }
7412
7413         if (rc == 0)
7414                 hur->hur_request.hr_itemcount++;
7415
7416         return rc;
7417 }
7418
7419 static int lfs_hsm_request(int argc, char **argv, int action)
7420 {
7421         struct option long_opts[] = {
7422         { .val = 'a',   .name = "archive",      .has_arg = required_argument },
7423         { .val = 'D',   .name = "data",         .has_arg = required_argument },
7424         { .val = 'l',   .name = "filelist",     .has_arg = required_argument },
7425         { .val = 'm',   .name = "mntpath",      .has_arg = required_argument },
7426         { .name = NULL } };
7427         dev_t                    last_dev = 0;
7428         char                     short_opts[] = "l:D:a:m:";
7429         struct hsm_user_request *hur, *oldhur;
7430         int                      c, i;
7431         size_t                   len;
7432         int                      nbfile;
7433         char                    *line = NULL;
7434         char                    *filelist = NULL;
7435         char                     fullpath[PATH_MAX];
7436         char                    *opaque = NULL;
7437         int                      opaque_len = 0;
7438         int                      archive_id = 0;
7439         FILE                    *fp;
7440         int                      nbfile_alloc = 0;
7441         char                    *some_file = NULL;
7442         char                    *mntpath = NULL;
7443         int                      rc;
7444
7445         if (argc < 2)
7446                 return CMD_HELP;
7447
7448         while ((c = getopt_long(argc, argv, short_opts,
7449                                 long_opts, NULL)) != -1) {
7450                 switch (c) {
7451                 case 'l':
7452                         filelist = optarg;
7453                         break;
7454                 case 'D':
7455                         opaque = optarg;
7456                         break;
7457                 case 'a':
7458                         if (action != HUA_ARCHIVE &&
7459                             action != HUA_REMOVE) {
7460                                 fprintf(stderr,
7461                                         "error: -a is supported only "
7462                                         "when archiving or removing\n");
7463                                 return CMD_HELP;
7464                         }
7465                         archive_id = atoi(optarg);
7466                         break;
7467                 case 'm':
7468                         if (some_file == NULL) {
7469                                 mntpath = optarg;
7470                                 some_file = strdup(optarg);
7471                         }
7472                         break;
7473                 case '?':
7474                         return CMD_HELP;
7475                 default:
7476                         fprintf(stderr, "error: %s: option '%s' unrecognized\n",
7477                                 argv[0], argv[optind - 1]);
7478                         return CMD_HELP;
7479                 }
7480         }
7481
7482         /* All remaining args are files, so we have at least nbfile */
7483         nbfile = argc - optind;
7484
7485         if ((nbfile == 0) && (filelist == NULL))
7486                 return CMD_HELP;
7487
7488         if (opaque != NULL)
7489                 opaque_len = strlen(opaque);
7490
7491         /* Alloc the request structure with enough place to store all files
7492          * from command line. */
7493         hur = llapi_hsm_user_request_alloc(nbfile, opaque_len);
7494         if (hur == NULL) {
7495                 fprintf(stderr, "Cannot create the request: %s\n",
7496                         strerror(errno));
7497                 return errno;
7498         }
7499         nbfile_alloc = nbfile;
7500
7501         hur->hur_request.hr_action = action;
7502         hur->hur_request.hr_archive_id = archive_id;
7503         hur->hur_request.hr_flags = 0;
7504
7505         /* All remaining args are files, add them */
7506         if (nbfile != 0 && some_file == NULL)
7507                 some_file = strdup(argv[optind]);
7508
7509         for (i = 0; i < nbfile; i++) {
7510                 rc = fill_hur_item(hur, i, mntpath, argv[optind + i],
7511                                    &last_dev);
7512                 if (rc)
7513                         goto out_free;
7514         }
7515
7516         /* from here stop using nb_file, use hur->hur_request.hr_itemcount */
7517
7518         /* If a filelist was specified, read the filelist from it. */
7519         if (filelist != NULL) {
7520                 fp = fopen(filelist, "r");
7521                 if (fp == NULL) {
7522                         fprintf(stderr, "Cannot read the file list %s: %s\n",
7523                                 filelist, strerror(errno));
7524                         rc = -errno;
7525                         goto out_free;
7526                 }
7527
7528                 while ((rc = getline(&line, &len, fp)) != -1) {
7529                         /* If allocated buffer was too small, get something
7530                          * larger */
7531                         if (nbfile_alloc <= hur->hur_request.hr_itemcount) {
7532                                 ssize_t size;
7533
7534                                 nbfile_alloc = nbfile_alloc * 2 + 1;
7535                                 oldhur = hur;
7536                                 hur = llapi_hsm_user_request_alloc(nbfile_alloc,
7537                                                                    opaque_len);
7538                                 if (hur == NULL) {
7539                                         fprintf(stderr, "hsm: cannot allocate "
7540                                                 "the request: %s\n",
7541                                                 strerror(errno));
7542                                         hur = oldhur;
7543                                         rc = -errno;
7544                                         fclose(fp);
7545                                         goto out_free;
7546                                 }
7547                                 size = hur_len(oldhur);
7548                                 if (size < 0) {
7549                                         fprintf(stderr, "hsm: cannot allocate "
7550                                                 "%u files + %u bytes data\n",
7551                                             oldhur->hur_request.hr_itemcount,
7552                                             oldhur->hur_request.hr_data_len);
7553                                         free(hur);
7554                                         hur = oldhur;
7555                                         rc = -E2BIG;
7556                                         fclose(fp);
7557                                         goto out_free;
7558                                 }
7559                                 memcpy(hur, oldhur, size);
7560                                 free(oldhur);
7561                         }
7562
7563                         /* Chop CR */
7564                         if (line[strlen(line) - 1] == '\n')
7565                                 line[strlen(line) - 1] = '\0';
7566
7567                         rc = fill_hur_item(hur, hur->hur_request.hr_itemcount,
7568                                            mntpath, line, &last_dev);
7569                         if (rc) {
7570                                 fclose(fp);
7571                                 goto out_free;
7572                         }
7573
7574                         if (some_file == NULL) {
7575                                 some_file = line;
7576                                 line = NULL;
7577                         }
7578                 }
7579
7580                 rc = fclose(fp);
7581                 free(line);
7582         }
7583
7584         /* If a --data was used, add it to the request */
7585         hur->hur_request.hr_data_len = opaque_len;
7586         if (opaque != NULL)
7587                 memcpy(hur_data(hur), opaque, opaque_len);
7588
7589         /* Send the HSM request */
7590         if (realpath(some_file, fullpath) == NULL) {
7591                 fprintf(stderr, "Could not find path '%s': %s\n",
7592                         some_file, strerror(errno));
7593         }
7594         rc = llapi_hsm_request(fullpath, hur);
7595         if (rc) {
7596                 fprintf(stderr, "Cannot send HSM request (use of %s): %s\n",
7597                         some_file, strerror(-rc));
7598                 goto out_free;
7599         }
7600
7601 out_free:
7602         free(some_file);
7603         free(hur);
7604         return rc;
7605 }
7606
7607 static int lfs_hsm_archive(int argc, char **argv)
7608 {
7609         return lfs_hsm_request(argc, argv, HUA_ARCHIVE);
7610 }
7611
7612 static int lfs_hsm_restore(int argc, char **argv)
7613 {
7614         return lfs_hsm_request(argc, argv, HUA_RESTORE);
7615 }
7616
7617 static int lfs_hsm_release(int argc, char **argv)
7618 {
7619         return lfs_hsm_request(argc, argv, HUA_RELEASE);
7620 }
7621
7622 static int lfs_hsm_remove(int argc, char **argv)
7623 {
7624         return lfs_hsm_request(argc, argv, HUA_REMOVE);
7625 }
7626
7627 static int lfs_hsm_cancel(int argc, char **argv)
7628 {
7629         return lfs_hsm_request(argc, argv, HUA_CANCEL);
7630 }
7631
7632 static int lfs_swap_layouts(int argc, char **argv)
7633 {
7634         if (argc != 3)
7635                 return CMD_HELP;
7636
7637         return llapi_swap_layouts(argv[1], argv[2], 0, 0,
7638                                   SWAP_LAYOUTS_KEEP_MTIME |
7639                                   SWAP_LAYOUTS_KEEP_ATIME);
7640 }
7641
7642 static const char *const ladvise_names[] = LU_LADVISE_NAMES;
7643
7644 static const char *const lock_mode_names[] = LOCK_MODE_NAMES;
7645
7646 int lfs_get_mode(const char *string)
7647 {
7648         enum lock_mode_user mode;
7649
7650         for (mode = 0; mode < ARRAY_SIZE(lock_mode_names); mode++) {
7651                 if (lock_mode_names[mode] == NULL)
7652                         continue;
7653                 if (strcmp(string, lock_mode_names[mode]) == 0)
7654                         return mode;
7655         }
7656
7657         return -EINVAL;
7658 }
7659
7660 static enum lu_ladvise_type lfs_get_ladvice(const char *string)
7661 {
7662         enum lu_ladvise_type advice;
7663
7664         for (advice = 0;
7665              advice < ARRAY_SIZE(ladvise_names); advice++) {
7666                 if (ladvise_names[advice] == NULL)
7667                         continue;
7668                 if (strcmp(string, ladvise_names[advice]) == 0)
7669                         return advice;
7670         }
7671
7672         return LU_LADVISE_INVALID;
7673 }
7674
7675 static int lfs_ladvise(int argc, char **argv)
7676 {
7677         struct option long_opts[] = {
7678         { .val = 'a',   .name = "advice",       .has_arg = required_argument },
7679         { .val = 'b',   .name = "background",   .has_arg = no_argument },
7680         { .val = 'e',   .name = "end",          .has_arg = required_argument },
7681         { .val = 'l',   .name = "length",       .has_arg = required_argument },
7682         { .val = 'm',   .name = "mode",         .has_arg = required_argument },
7683         { .val = 's',   .name = "start",        .has_arg = required_argument },
7684         { .val = 'u',   .name = "unset",        .has_arg = no_argument },
7685         { .name = NULL } };
7686         char                     short_opts[] = "a:be:l:m:s:u";
7687         int                      c;
7688         int                      rc = 0;
7689         const char              *path;
7690         int                      fd;
7691         struct llapi_lu_ladvise  advice;
7692         enum lu_ladvise_type     advice_type = LU_LADVISE_INVALID;
7693         unsigned long long       start = 0;
7694         unsigned long long       end = LUSTRE_EOF;
7695         unsigned long long       length = 0;
7696         unsigned long long       size_units;
7697         unsigned long long       flags = 0;
7698         int                      mode = 0;
7699
7700         optind = 0;
7701         while ((c = getopt_long(argc, argv, short_opts,
7702                                 long_opts, NULL)) != -1) {
7703                 switch (c) {
7704                 case 'a':
7705                         advice_type = lfs_get_ladvice(optarg);
7706                         if (advice_type == LU_LADVISE_INVALID) {
7707                                 fprintf(stderr, "%s: invalid advice type "
7708                                         "'%s'\n", argv[0], optarg);
7709                                 fprintf(stderr, "Valid types:");
7710
7711                                 for (advice_type = 0;
7712                                      advice_type < ARRAY_SIZE(ladvise_names);
7713                                      advice_type++) {
7714                                         if (ladvise_names[advice_type] == NULL)
7715                                                 continue;
7716                                         fprintf(stderr, " %s",
7717                                                 ladvise_names[advice_type]);
7718                                 }
7719                                 fprintf(stderr, "\n");
7720
7721                                 return CMD_HELP;
7722                         }
7723                         break;
7724                 case 'b':
7725                         flags |= LF_ASYNC;
7726                         break;
7727                 case 'u':
7728                         flags |= LF_UNSET;
7729                         break;
7730                 case 'e':
7731                         size_units = 1;
7732                         rc = llapi_parse_size(optarg, &end,
7733                                               &size_units, 0);
7734                         if (rc) {
7735                                 fprintf(stderr, "%s: bad end offset '%s'\n",
7736                                         argv[0], optarg);
7737                                 return CMD_HELP;
7738                         }
7739                         break;
7740                 case 's':
7741                         size_units = 1;
7742                         rc = llapi_parse_size(optarg, &start,
7743                                               &size_units, 0);
7744                         if (rc) {
7745                                 fprintf(stderr, "%s: bad start offset "
7746                                         "'%s'\n", argv[0], optarg);
7747                                 return CMD_HELP;
7748                         }
7749                         break;
7750                 case 'l':
7751                         size_units = 1;
7752                         rc = llapi_parse_size(optarg, &length,
7753                                               &size_units, 0);
7754                         if (rc) {
7755                                 fprintf(stderr, "%s: bad length '%s'\n",
7756                                         argv[0], optarg);
7757                                 return CMD_HELP;
7758                         }
7759                         break;
7760                 case 'm':
7761                         mode = lfs_get_mode(optarg);
7762                         if (mode < 0) {
7763                                 fprintf(stderr, "%s: bad mode '%s', valid "
7764                                                  "modes are READ or WRITE\n",
7765                                         argv[0], optarg);
7766                                 return CMD_HELP;
7767                         }
7768                         break;
7769                 case '?':
7770                         return CMD_HELP;
7771                 default:
7772                         fprintf(stderr, "%s: option '%s' unrecognized\n",
7773                                 argv[0], argv[optind - 1]);
7774                         return CMD_HELP;
7775                 }
7776         }
7777
7778         if (advice_type == LU_LADVISE_INVALID) {
7779                 fprintf(stderr, "%s: please give an advice type\n", argv[0]);
7780                 fprintf(stderr, "Valid types:");
7781                 for (advice_type = 0; advice_type < ARRAY_SIZE(ladvise_names);
7782                      advice_type++) {
7783                         if (ladvise_names[advice_type] == NULL)
7784                                 continue;
7785                         fprintf(stderr, " %s", ladvise_names[advice_type]);
7786                 }
7787                 fprintf(stderr, "\n");
7788                 return CMD_HELP;
7789         }
7790
7791         if (advice_type == LU_LADVISE_LOCKNOEXPAND) {
7792                 fprintf(stderr, "%s: Lock no expand advice is a per file "
7793                                  "descriptor advice, so when called from lfs, "
7794                                  "it does nothing.\n", argv[0]);
7795                 return CMD_HELP;
7796         }
7797
7798         if (argc <= optind) {
7799                 fprintf(stderr, "%s: please give one or more file names\n",
7800                         argv[0]);
7801                 return CMD_HELP;
7802         }
7803
7804         if (end != LUSTRE_EOF && length != 0 && end != start + length) {
7805                 fprintf(stderr, "%s: conflicting arguments of -l and -e\n",
7806                         argv[0]);
7807                 return CMD_HELP;
7808         }
7809
7810         if (end == LUSTRE_EOF && length != 0)
7811                 end = start + length;
7812
7813         if (end <= start) {
7814                 fprintf(stderr, "%s: range [%llu, %llu] is invalid\n",
7815                         argv[0], start, end);
7816                 return CMD_HELP;
7817         }
7818
7819         if (advice_type != LU_LADVISE_LOCKAHEAD && mode != 0) {
7820                 fprintf(stderr, "%s: mode is only valid with lockahead\n",
7821                         argv[0]);
7822                 return CMD_HELP;
7823         }
7824
7825         if (advice_type == LU_LADVISE_LOCKAHEAD && mode == 0) {
7826                 fprintf(stderr, "%s: mode is required with lockahead\n",
7827                         argv[0]);
7828                 return CMD_HELP;
7829         }
7830
7831         while (optind < argc) {
7832                 int rc2;
7833
7834                 path = argv[optind++];
7835
7836                 fd = open(path, O_RDONLY);
7837                 if (fd < 0) {
7838                         fprintf(stderr, "%s: cannot open file '%s': %s\n",
7839                                 argv[0], path, strerror(errno));
7840                         rc2 = -errno;
7841                         goto next;
7842                 }
7843
7844                 advice.lla_start = start;
7845                 advice.lla_end = end;
7846                 advice.lla_advice = advice_type;
7847                 advice.lla_value1 = 0;
7848                 advice.lla_value2 = 0;
7849                 advice.lla_value3 = 0;
7850                 advice.lla_value4 = 0;
7851                 if (advice_type == LU_LADVISE_LOCKAHEAD) {
7852                         advice.lla_lockahead_mode = mode;
7853                         advice.lla_peradvice_flags = flags;
7854                 }
7855
7856                 rc2 = llapi_ladvise(fd, flags, 1, &advice);
7857                 close(fd);
7858                 if (rc2 < 0) {
7859                         fprintf(stderr, "%s: cannot give advice '%s' to file "
7860                                 "'%s': %s\n", argv[0],
7861                                 ladvise_names[advice_type],
7862                                 path, strerror(errno));
7863
7864                         goto next;
7865                 }
7866
7867 next:
7868                 if (rc == 0 && rc2 < 0)
7869                         rc = rc2;
7870         }
7871         return rc;
7872 }
7873
7874 /** The input string contains a comma delimited list of component ids and
7875  * ranges, for example "1,2-4,7".
7876  */
7877 static int parse_mirror_ids(__u16 *ids, int size, char *arg)
7878 {
7879         bool end_of_loop = false;
7880         char *ptr = NULL;
7881         int nr = 0;
7882         int rc;
7883
7884         if (arg == NULL)
7885                 return -EINVAL;
7886
7887         while (!end_of_loop) {
7888                 int start_index;
7889                 int end_index;
7890                 int i;
7891                 char *endptr = NULL;
7892
7893                 rc = -EINVAL;
7894                 ptr = strchrnul(arg, ',');
7895                 end_of_loop = *ptr == '\0';
7896                 *ptr = '\0';
7897
7898                 start_index = strtol(arg, &endptr, 0);
7899                 if (endptr == arg) /* no data at all */
7900                         break;
7901                 if (*endptr != '-' && *endptr != '\0') /* has invalid data */
7902                         break;
7903                 if (start_index < 0)
7904                         break;
7905
7906                 end_index = start_index;
7907                 if (*endptr == '-') {
7908                         end_index = strtol(endptr + 1, &endptr, 0);
7909                         if (*endptr != '\0')
7910                                 break;
7911                         if (end_index < start_index)
7912                                 break;
7913                 }
7914
7915                 for (i = start_index; i <= end_index && size > 0; i++) {
7916                         int j;
7917
7918                         /* remove duplicate */
7919                         for (j = 0; j < nr; j++) {
7920                                 if (ids[j] == i)
7921                                         break;
7922                         }
7923                         if (j == nr) { /* no duplicate */
7924                                 ids[nr++] = i;
7925                                 --size;
7926                         }
7927                 }
7928
7929                 if (size == 0 && i < end_index)
7930                         break;
7931
7932                 *ptr = ',';
7933                 arg = ++ptr;
7934                 rc = 0;
7935         }
7936         if (!end_of_loop && ptr != NULL)
7937                 *ptr = ',';
7938
7939         return rc < 0 ? rc : nr;
7940 }
7941
7942 /**
7943  * struct verify_mirror_id - Mirror id to be verified.
7944  * @mirror_id:   A specified mirror id.
7945  * @is_valid_id: @mirror_id is valid or not in the mirrored file.
7946  */
7947 struct verify_mirror_id {
7948         __u16 mirror_id;
7949         bool is_valid_id;
7950 };
7951
7952 /**
7953  * compare_mirror_ids() - Compare mirror ids.
7954  * @layout: Mirror component list.
7955  * @cbdata: Callback data in verify_mirror_id structure.
7956  *
7957  * This is a callback function called by llapi_layout_comp_iterate()
7958  * to compare the specified mirror id with the one in the current
7959  * component of @layout. If they are the same, then the specified
7960  * mirror id is valid.
7961  *
7962  * Return: a negative error code on failure or
7963  *         LLAPI_LAYOUT_ITER_CONT: Proceed iteration
7964  *         LLAPI_LAYOUT_ITER_STOP: Stop iteration
7965  */
7966 static inline
7967 int compare_mirror_ids(struct llapi_layout *layout, void *cbdata)
7968 {
7969         struct verify_mirror_id *mirror_id_cbdata =
7970                                  (struct verify_mirror_id *)cbdata;
7971         uint32_t mirror_id;
7972         int rc = 0;
7973
7974         rc = llapi_layout_mirror_id_get(layout, &mirror_id);
7975         if (rc < 0) {
7976                 rc = -errno;
7977                 fprintf(stderr,
7978                         "%s: llapi_layout_mirror_id_get failed: %s.\n",
7979                         progname, strerror(errno));
7980                 return rc;
7981         }
7982
7983         if (mirror_id_cbdata->mirror_id == mirror_id) {
7984                 mirror_id_cbdata->is_valid_id = true;
7985                 return LLAPI_LAYOUT_ITER_STOP;
7986         }
7987
7988         return LLAPI_LAYOUT_ITER_CONT;
7989 }
7990
7991 /**
7992  * verify_mirror_ids() - Verify specified mirror ids.
7993  * @fname:      Mirrored file name.
7994  * @mirror_ids: Specified mirror ids to be verified.
7995  * @ids_nr:     Number of specified mirror ids.
7996  *
7997  * This function verifies that specified @mirror_ids are valid
7998  * in the mirrored file @fname.
7999  *
8000  * Return: 0 on success or a negative error code on failure.
8001  */
8002 static inline
8003 int verify_mirror_ids(const char *fname, __u16 *mirror_ids, int ids_nr)
8004 {
8005         struct llapi_layout *layout = NULL;
8006         struct verify_mirror_id mirror_id_cbdata = { 0 };
8007         struct stat stbuf;
8008         uint32_t flr_state;
8009         int i;
8010         int fd;
8011         int rc = 0;
8012         int rc2 = 0;
8013
8014         if (ids_nr <= 0)
8015                 return -EINVAL;
8016
8017         if (stat(fname, &stbuf) < 0) {
8018                 fprintf(stderr, "%s: cannot stat file '%s': %s.\n",
8019                         progname, fname, strerror(errno));
8020                 rc = -errno;
8021                 goto error;
8022         }
8023
8024         if (!S_ISREG(stbuf.st_mode)) {
8025                 fprintf(stderr, "%s: '%s' is not a regular file.\n",
8026                         progname, fname);
8027                 rc = -EINVAL;
8028                 goto error;
8029         }
8030
8031         fd = open(fname, O_DIRECT | O_RDONLY);
8032         if (fd < 0) {
8033                 fprintf(stderr, "%s: cannot open '%s': %s.\n",
8034                         progname, fname, strerror(errno));
8035                 rc = -errno;
8036                 goto error;
8037         }
8038
8039         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
8040         if (rc < 0) {
8041                 fprintf(stderr, "%s: '%s' llapi_lease_acquire failed: %s.\n",
8042                         progname, fname, strerror(errno));
8043                 goto close_fd;
8044         }
8045
8046         layout = llapi_layout_get_by_fd(fd, 0);
8047         if (layout == NULL) {
8048                 fprintf(stderr, "%s: '%s' llapi_layout_get_by_fd failed: %s.\n",
8049                         progname, fname, strerror(errno));
8050                 rc = -errno;
8051                 llapi_lease_release(fd);
8052                 goto close_fd;
8053         }
8054
8055         rc = llapi_layout_flags_get(layout, &flr_state);
8056         if (rc < 0) {
8057                 fprintf(stderr, "%s: '%s' llapi_layout_flags_get failed: %s.\n",
8058                         progname, fname, strerror(errno));
8059                 rc = -errno;
8060                 goto free_layout;
8061         }
8062
8063         flr_state &= LCM_FL_FLR_MASK;
8064         switch (flr_state) {
8065         case LCM_FL_NONE:
8066                 rc = -EINVAL;
8067                 fprintf(stderr, "%s: '%s' file state error: %s.\n",
8068                         progname, fname, llapi_layout_flags_string(flr_state));
8069                 goto free_layout;
8070         default:
8071                 break;
8072         }
8073
8074         rc2 = 0;
8075         for (i = 0; i < ids_nr; i++) {
8076                 mirror_id_cbdata.mirror_id = mirror_ids[i];
8077                 mirror_id_cbdata.is_valid_id = false;
8078
8079                 rc = llapi_layout_comp_iterate(layout, compare_mirror_ids,
8080                                                &mirror_id_cbdata);
8081                 if (rc < 0) {
8082                         rc = -errno;
8083                         fprintf(stderr,
8084                                 "%s: '%s' failed to verify mirror id: %u.\n",
8085                                 progname, fname, mirror_ids[i]);
8086                         goto free_layout;
8087                 }
8088
8089                 if (!mirror_id_cbdata.is_valid_id) {
8090                         rc2 = -EINVAL;
8091                         fprintf(stderr,
8092                                 "%s: '%s' invalid specified mirror id: %u.\n",
8093                                 progname, fname, mirror_ids[i]);
8094                 }
8095         }
8096         rc = rc2;
8097
8098 free_layout:
8099         llapi_layout_free(layout);
8100         llapi_lease_release(fd);
8101 close_fd:
8102         close(fd);
8103 error:
8104         return rc;
8105 }
8106
8107 static inline
8108 int lfs_mirror_resync_file(const char *fname, struct ll_ioc_lease *ioc,
8109                            __u16 *mirror_ids, int ids_nr)
8110 {
8111         struct llapi_resync_comp comp_array[1024] = { { 0 } };
8112         struct llapi_layout *layout;
8113         struct stat stbuf;
8114         uint32_t flr_state;
8115         uint64_t start;
8116         uint64_t end;
8117         int comp_size = 0;
8118         int idx;
8119         int fd;
8120         int rc;
8121
8122         if (stat(fname, &stbuf) < 0) {
8123                 fprintf(stderr, "%s: cannot stat file '%s': %s.\n",
8124                         progname, fname, strerror(errno));
8125                 rc = -errno;
8126                 goto error;
8127         }
8128         if (!S_ISREG(stbuf.st_mode)) {
8129                 fprintf(stderr, "%s: '%s' is not a regular file.\n",
8130                         progname, fname);
8131                 rc = -EINVAL;
8132                 goto error;
8133         }
8134
8135         fd = open(fname, O_DIRECT | O_RDWR);
8136         if (fd < 0) {
8137                 fprintf(stderr, "%s: cannot open '%s': %s.\n",
8138                         progname, fname, strerror(errno));
8139                 rc = -errno;
8140                 goto error;
8141         }
8142
8143         layout = llapi_layout_get_by_fd(fd, 0);
8144         if (layout == NULL) {
8145                 fprintf(stderr, "%s: '%s' llapi_layout_get_by_fd failed: %s.\n",
8146                         progname, fname, strerror(errno));
8147                 rc = -errno;
8148                 goto close_fd;
8149         }
8150
8151         rc = llapi_layout_flags_get(layout, &flr_state);
8152         if (rc) {
8153                 fprintf(stderr, "%s: '%s' llapi_layout_flags_get failed: %s.\n",
8154                         progname, fname, strerror(errno));
8155                 rc = -errno;
8156                 goto free_layout;
8157         }
8158
8159         flr_state &= LCM_FL_FLR_MASK;
8160         if (flr_state == LCM_FL_NONE) {
8161                 rc = -EINVAL;
8162                 fprintf(stderr, "%s: '%s' is not a FLR file.\n",
8163                         progname, fname);
8164                 goto free_layout;
8165         }
8166
8167         /* get stale component info */
8168         comp_size = llapi_mirror_find_stale(layout, comp_array,
8169                                             ARRAY_SIZE(comp_array),
8170                                             mirror_ids, ids_nr);
8171         if (comp_size <= 0) {
8172                 rc = comp_size;
8173                 goto free_layout;
8174         }
8175
8176         ioc->lil_mode = LL_LEASE_WRLCK;
8177         ioc->lil_flags = LL_LEASE_RESYNC;
8178         rc = llapi_lease_set(fd, ioc);
8179         if (rc < 0) {
8180                 if (rc == -EALREADY)
8181                         rc = 0;
8182                 else
8183                         fprintf(stderr,
8184                             "%s: '%s' llapi_lease_get_ext resync failed: %s.\n",
8185                                 progname, fname, strerror(errno));
8186                 goto free_layout;
8187         }
8188
8189         /* get the read range [start, end) */
8190         start = comp_array[0].lrc_start;
8191         end = comp_array[0].lrc_end;
8192         for (idx = 1; idx < comp_size; idx++) {
8193                 if (comp_array[idx].lrc_start < start)
8194                         start = comp_array[idx].lrc_start;
8195                 if (end < comp_array[idx].lrc_end)
8196                         end = comp_array[idx].lrc_end;
8197         }
8198
8199         rc = llapi_lease_check(fd);
8200         if (rc != LL_LEASE_WRLCK) {
8201                 fprintf(stderr, "%s: '%s' lost lease lock.\n",
8202                         progname, fname);
8203                 goto free_layout;
8204         }
8205
8206         rc = llapi_mirror_resync_many(fd, layout, comp_array, comp_size,
8207                                       start, end);
8208         if (rc < 0)
8209                 fprintf(stderr, "%s: '%s' llapi_mirror_resync_many: %d.\n",
8210                         progname, fname, rc);
8211
8212         /* prepare ioc for lease put */
8213         ioc->lil_mode = LL_LEASE_UNLCK;
8214         ioc->lil_flags = LL_LEASE_RESYNC_DONE;
8215         ioc->lil_count = 0;
8216         for (idx = 0; idx < comp_size; idx++) {
8217                 if (comp_array[idx].lrc_synced) {
8218                         ioc->lil_ids[ioc->lil_count] = comp_array[idx].lrc_id;
8219                         ioc->lil_count++;
8220                 }
8221         }
8222
8223         rc = llapi_lease_set(fd, ioc);
8224         if (rc <= 0) {
8225                 if (rc == 0) /* lost lease lock */
8226                         rc = -EBUSY;
8227                 fprintf(stderr, "%s: resync file '%s' failed: %s.\n",
8228                         progname, fname, strerror(errno));
8229                 goto free_layout;
8230         }
8231         /**
8232          * llapi_lease_set returns lease mode when it request to unlock
8233          * the lease lock
8234          */
8235         rc = 0;
8236
8237 free_layout:
8238         llapi_layout_free(layout);
8239 close_fd:
8240         close(fd);
8241 error:
8242         return rc;
8243 }
8244
8245 static inline int lfs_mirror_resync(int argc, char **argv)
8246 {
8247         struct ll_ioc_lease *ioc = NULL;
8248         __u16 mirror_ids[128] = { 0 };
8249         int ids_nr = 0;
8250         int c;
8251         int rc = 0;
8252
8253         struct option long_opts[] = {
8254         { .val = 'o',   .name = "only",         .has_arg = required_argument },
8255         { .name = NULL } };
8256
8257         while ((c = getopt_long(argc, argv, "o:", long_opts, NULL)) >= 0) {
8258                 switch (c) {
8259                 case 'o':
8260                         rc = parse_mirror_ids(mirror_ids,
8261                                         sizeof(mirror_ids) / sizeof(__u16),
8262                                         optarg);
8263                         if (rc < 0) {
8264                                 fprintf(stderr,
8265                                         "%s: bad mirror ids '%s'.\n",
8266                                         argv[0], optarg);
8267                                 goto error;
8268                         }
8269                         ids_nr = rc;
8270                         break;
8271                 default:
8272                         fprintf(stderr, "%s: options '%s' unrecognized.\n",
8273                                 argv[0], argv[optind - 1]);
8274                         rc = -EINVAL;
8275                         goto error;
8276                 }
8277         }
8278
8279         if (argc == optind) {
8280                 fprintf(stderr, "%s: no file name given.\n", argv[0]);
8281                 rc = CMD_HELP;
8282                 goto error;
8283         }
8284
8285         if (ids_nr > 0 && argc > optind + 1) {
8286                 fprintf(stderr,
8287                     "%s: option '--only' cannot be used upon multiple files.\n",
8288                         argv[0]);
8289                 rc = CMD_HELP;
8290                 goto error;
8291
8292         }
8293
8294         if (ids_nr > 0) {
8295                 rc = verify_mirror_ids(argv[optind], mirror_ids, ids_nr);
8296                 if (rc < 0)
8297                         goto error;
8298         }
8299
8300         /* set the lease on the file */
8301         ioc = calloc(sizeof(*ioc) + sizeof(__u32) * 4096, 1);
8302         if (ioc == NULL) {
8303                 fprintf(stderr, "%s: cannot alloc id array for ioc: %s.\n",
8304                         argv[0], strerror(errno));
8305                 rc = -errno;
8306                 goto error;
8307         }
8308
8309         for (; optind < argc; optind++) {
8310                 rc = lfs_mirror_resync_file(argv[optind], ioc,
8311                                             mirror_ids, ids_nr);
8312                 /* ignore previous file's error, continue with next file */
8313
8314                 /* reset ioc */
8315                 memset(ioc, 0, sizeof(*ioc) + sizeof(__u32) * 4096);
8316         }
8317
8318         free(ioc);
8319 error:
8320         return rc;
8321 }
8322
8323 static inline int verify_mirror_id_by_fd(int fd, __u16 mirror_id)
8324 {
8325         struct llapi_layout *layout;
8326         int rc;
8327
8328         layout = llapi_layout_get_by_fd(fd, 0);
8329         if (layout == NULL) {
8330                 fprintf(stderr, "could not get layout.\n");
8331                 return  -EINVAL;
8332         }
8333
8334         rc = llapi_layout_comp_iterate(layout, find_mirror_id, &mirror_id);
8335         if (rc < 0) {
8336                 fprintf(stderr, "failed to iterate layout\n");
8337                 llapi_layout_free(layout);
8338
8339                 return rc;
8340         } else if (rc == LLAPI_LAYOUT_ITER_CONT) {
8341                 fprintf(stderr, "does not find mirror with ID %u\n", mirror_id);
8342                 llapi_layout_free(layout);
8343
8344                 return -EINVAL;
8345         }
8346         llapi_layout_free(layout);
8347
8348         return 0;
8349 }
8350
8351 /**
8352  * Check whether two files are the same file
8353  * \retval      0  same file
8354  * \retval      1  not the same file
8355  * \retval      <0 error code
8356  */
8357 static inline int check_same_file(const char *f1, const char *f2)
8358 {
8359         struct stat stbuf1;
8360         struct stat stbuf2;
8361
8362         if (stat(f1, &stbuf1) < 0) {
8363                 fprintf(stderr, "%s: cannot stat file '%s': %s\n",
8364                         progname, f1, strerror(errno));
8365                 return -errno;
8366         }
8367
8368         if (stat(f2, &stbuf2) < 0) {
8369                 fprintf(stderr, "%s: cannot stat file '%s': %s\n",
8370                         progname, f2, strerror(errno));
8371                 return -errno;
8372         }
8373
8374         if (stbuf1.st_rdev == stbuf2.st_rdev &&
8375             stbuf1.st_ino == stbuf2.st_ino)
8376                 return 0;
8377
8378         return 1;
8379 }
8380
8381 static inline int lfs_mirror_read(int argc, char **argv)
8382 {
8383         int rc = CMD_HELP;
8384         __u16 mirror_id = 0;
8385         const char *outfile = NULL;
8386         char *fname;
8387         int fd = 0;
8388         int outfd;
8389         int c;
8390         void *buf;
8391         const size_t buflen = 4 << 20;
8392         off_t pos;
8393         struct option long_opts[] = {
8394         { .val = 'N',   .name = "mirror-id",    .has_arg = required_argument },
8395         { .val = 'o',   .name = "outfile",      .has_arg = required_argument },
8396         { .name = NULL } };
8397
8398         while ((c = getopt_long(argc, argv, "N:o:", long_opts, NULL)) >= 0) {
8399                 char *end;
8400
8401                 switch (c) {
8402                 case 'N':
8403                         mirror_id = strtoul(optarg, &end, 0);
8404                         if (*end != '\0' || mirror_id == 0) {
8405                                 fprintf(stderr,
8406                                         "%s %s: invalid mirror ID '%s'\n",
8407                                         progname, argv[0], optarg);
8408                                 return rc;
8409                         }
8410                         break;
8411                 case 'o':
8412                         outfile = optarg;
8413                         break;
8414                 default:
8415                         fprintf(stderr, "%s: option '%s' unrecognized.\n",
8416                                 progname, argv[optind - 1]);
8417                         return -EINVAL;
8418                 }
8419         }
8420
8421         if (argc == optind) {
8422                 fprintf(stderr, "%s %s: no mirrored file provided\n",
8423                         progname, argv[0]);
8424                 return rc;
8425         } else if (argc > optind + 1) {
8426                 fprintf(stderr, "%s %s: too many files\n", progname, argv[0]);
8427                 return rc;
8428         }
8429
8430         if (mirror_id == 0) {
8431                 fprintf(stderr, "%s %s: no valid mirror ID is provided\n",
8432                         progname, argv[0]);
8433                 return rc;
8434         }
8435
8436         /* open mirror file */
8437         fname = argv[optind];
8438
8439         if (outfile) {
8440                 rc = check_same_file(fname, outfile);
8441                 if (rc == 0) {
8442                         fprintf(stderr,
8443                         "%s %s: output file cannot be the mirrored file\n",
8444                                 progname, argv[0]);
8445                         return -EINVAL;
8446                 }
8447                 if (rc < 0)
8448                         return rc;
8449         }
8450
8451         fd = open(fname, O_DIRECT | O_RDONLY);
8452         if (fd < 0) {
8453                 fprintf(stderr, "%s %s: cannot open '%s': %s\n",
8454                         progname, argv[0], fname, strerror(errno));
8455                 return rc;
8456         }
8457
8458         /* verify mirror id */
8459         rc = verify_mirror_id_by_fd(fd, mirror_id);
8460         if (rc) {
8461                 fprintf(stderr,
8462                         "%s %s: cannot find mirror with ID %u in '%s'\n",
8463                         progname, argv[0], mirror_id, fname);
8464                 goto close_fd;
8465         }
8466
8467         /* open output file */
8468         if (outfile) {
8469                 outfd = open(outfile, O_EXCL | O_WRONLY | O_CREAT, 0644);
8470                 if (outfd < 0) {
8471                         fprintf(stderr, "%s %s: cannot create file '%s': %s\n",
8472                                 progname, argv[0], outfile, strerror(errno));
8473                         rc = -errno;
8474                         goto close_fd;
8475                 }
8476         } else {
8477                 outfd = STDOUT_FILENO;
8478         }
8479
8480         /* allocate buffer */
8481         rc = posix_memalign(&buf, sysconf(_SC_PAGESIZE), buflen);
8482         if (rc) {
8483                 fprintf(stderr, "%s %s: posix_memalign returns %d\n",
8484                                 progname, argv[0], rc);
8485                 goto close_outfd;
8486         }
8487
8488         pos = 0;
8489         while (1) {
8490                 ssize_t bytes_read;
8491                 ssize_t written = 0;
8492
8493                 bytes_read = llapi_mirror_read(fd, mirror_id, buf, buflen, pos);
8494                 if (bytes_read < 0) {
8495                         rc = bytes_read;
8496                         fprintf(stderr,
8497                                 "%s %s: fail to read data from mirror %u: %s\n",
8498                                 progname, argv[0], mirror_id, strerror(-rc));
8499                         goto free_buf;
8500                 }
8501
8502                 /* EOF reached */
8503                 if (bytes_read == 0)
8504                         break;
8505
8506                 while (written < bytes_read) {
8507                         ssize_t written2;
8508
8509                         written2 = write(outfd, buf + written,
8510                                          bytes_read - written);
8511                         if (written2 < 0) {
8512                                 fprintf(stderr,
8513                                         "%s %s: fail to write %s: %s\n",
8514                                         progname, argv[0], outfile ? : "STDOUT",
8515                                         strerror(errno));
8516                                 rc = -errno;
8517                                 goto free_buf;
8518                         }
8519                         written += written2;
8520                 }
8521
8522                 if (written != bytes_read) {
8523                         fprintf(stderr,
8524                 "%s %s: written %ld bytes does not match with %ld read.\n",
8525                                 progname, argv[0], written, bytes_read);
8526                         rc = -EIO;
8527                         goto free_buf;
8528                 }
8529
8530                 pos += bytes_read;
8531         }
8532
8533         fsync(outfd);
8534         rc = 0;
8535
8536 free_buf:
8537         free(buf);
8538 close_outfd:
8539         if (outfile)
8540                 close(outfd);
8541 close_fd:
8542         close(fd);
8543
8544         return rc;
8545 }
8546
8547 static inline int lfs_mirror_write(int argc, char **argv)
8548 {
8549         int rc = CMD_HELP;
8550         __u16 mirror_id = 0;
8551         const char *inputfile = NULL;
8552         char *fname;
8553         int fd = 0;
8554         int inputfd;
8555         int c;
8556         void *buf;
8557         const size_t buflen = 4 << 20;
8558         off_t pos;
8559         size_t page_size = sysconf(_SC_PAGESIZE);
8560         struct ll_ioc_lease_id ioc;
8561
8562         struct option long_opts[] = {
8563         { .val = 'N',   .name = "mirror-id",    .has_arg = required_argument },
8564         { .val = 'i',   .name = "inputfile",    .has_arg = required_argument },
8565         { .name = NULL } };
8566
8567         while ((c = getopt_long(argc, argv, "N:i:", long_opts, NULL)) >= 0) {
8568                 char *end;
8569
8570                 switch (c) {
8571                 case 'N':
8572                         mirror_id = strtoul(optarg, &end, 0);
8573                         if (*end != '\0' || mirror_id == 0) {
8574                                 fprintf(stderr,
8575                                         "%s %s: invalid mirror ID '%s'\n",
8576                                         progname, argv[0], optarg);
8577                                 return rc;
8578                         }
8579                         break;
8580                 case 'i':
8581                         inputfile = optarg;
8582                         break;
8583                 default:
8584                         fprintf(stderr, "%s: option '%s' unrecognized\n",
8585                                 progname, argv[optind - 1]);
8586                         return -EINVAL;
8587                 }
8588         }
8589
8590         if (argc == optind) {
8591                 fprintf(stderr, "%s %s: no mirrored file provided\n",
8592                         progname, argv[0]);
8593                 return rc;
8594         } else if (argc > optind + 1) {
8595                 fprintf(stderr, "%s %s: too many files\n", progname, argv[0]);
8596                 return rc;
8597         }
8598
8599         if (mirror_id == 0) {
8600                 fprintf(stderr, "%s %s: no valid mirror ID is provided\n",
8601                         progname, argv[0]);
8602                 return rc;
8603         }
8604
8605         /* open mirror file */
8606         fname = argv[optind];
8607
8608         if (inputfile) {
8609                 rc = check_same_file(fname, inputfile);
8610                 if (rc == 0) {
8611                         fprintf(stderr,
8612                         "%s %s: input file cannot be the mirrored file\n",
8613                                 progname, argv[0]);
8614                         return -EINVAL;
8615                 }
8616                 if (rc < 0)
8617                         return rc;
8618         }
8619
8620         fd = open(fname, O_DIRECT | O_WRONLY);
8621         if (fd < 0) {
8622                 fprintf(stderr, "%s %s: cannot open '%s': %s\n",
8623                         progname, argv[0], fname, strerror(errno));
8624                 return rc;
8625         }
8626
8627         /* verify mirror id */
8628         rc = verify_mirror_id_by_fd(fd, mirror_id);
8629         if (rc) {
8630                 fprintf(stderr,
8631                         "%s %s: cannot find mirror with ID %u in '%s'\n",
8632                         progname, argv[0], mirror_id, fname);
8633                 goto close_fd;
8634         }
8635
8636         /* open input file */
8637         if (inputfile) {
8638                 inputfd = open(inputfile, O_RDONLY, 0644);
8639                 if (inputfd < 0) {
8640                         fprintf(stderr, "%s %s: cannot open file '%s': %s\n",
8641                                 progname, argv[0], inputfile, strerror(errno));
8642                         rc = -errno;
8643                         goto close_fd;
8644                 }
8645         } else {
8646                 inputfd = STDIN_FILENO;
8647         }
8648
8649         /* allocate buffer */
8650         rc = posix_memalign(&buf, page_size, buflen);
8651         if (rc) {
8652                 fprintf(stderr, "%s %s: posix_memalign returns %d\n",
8653                         progname, argv[0], rc);
8654                 goto close_inputfd;
8655         }
8656
8657         /* prepare target mirror components instantiation */
8658         ioc.lil_mode = LL_LEASE_WRLCK;
8659         ioc.lil_flags = LL_LEASE_RESYNC;
8660         ioc.lil_mirror_id = mirror_id;
8661         rc = llapi_lease_set(fd, (struct ll_ioc_lease *)&ioc);
8662         if (rc < 0) {
8663                 fprintf(stderr,
8664                         "%s %s: '%s' llapi_lease_get_ext failed: %s\n",
8665                         progname, argv[0], fname, strerror(errno));
8666                 goto free_buf;
8667         }
8668
8669         pos = 0;
8670         while (1) {
8671                 ssize_t bytes_read;
8672                 ssize_t written;
8673                 size_t to_write;
8674
8675                 rc = llapi_lease_check(fd);
8676                 if (rc != LL_LEASE_WRLCK) {
8677                         fprintf(stderr, "%s %s: '%s' lost lease lock\n",
8678                                 progname, argv[0], fname);
8679                         goto free_buf;
8680                 }
8681
8682                 bytes_read = read(inputfd, buf, buflen);
8683                 if (bytes_read < 0) {
8684                         rc = bytes_read;
8685                         fprintf(stderr,
8686                                 "%s %s: fail to read data from '%s': %s\n",
8687                                 progname, argv[0], inputfile ? : "STDIN",
8688                                 strerror(errno));
8689                         rc = -errno;
8690                         goto free_buf;
8691                 }
8692
8693                 /* EOF reached */
8694                 if (bytes_read == 0)
8695                         break;
8696
8697                 /* round up to page align to make direct IO happy. */
8698                 to_write = (bytes_read + page_size - 1) & ~(page_size - 1);
8699
8700                 written = llapi_mirror_write(fd, mirror_id, buf, to_write,
8701                                              pos);
8702                 if (written < 0) {
8703                         rc = written;
8704                         fprintf(stderr,
8705                               "%s %s: fail to write to mirror %u: %s\n",
8706                                 progname, argv[0], mirror_id,
8707                                 strerror(-rc));
8708                         goto free_buf;
8709                 }
8710
8711                 pos += bytes_read;
8712         }
8713
8714         if (pos & (page_size - 1)) {
8715                 rc = llapi_mirror_truncate(fd, mirror_id, pos);
8716                 if (rc < 0)
8717                         goto free_buf;
8718         }
8719
8720         ioc.lil_mode = LL_LEASE_UNLCK;
8721         ioc.lil_flags = LL_LEASE_RESYNC_DONE;
8722         ioc.lil_count = 0;
8723         rc = llapi_lease_set(fd, (struct ll_ioc_lease *)&ioc);
8724         if (rc <= 0) {
8725                 if (rc == 0)
8726                         rc = -EBUSY;
8727                 fprintf(stderr,
8728                         "%s %s: release lease lock of '%s' failed: %s\n",
8729                         progname, argv[0], fname, strerror(errno));
8730                 goto free_buf;
8731         }
8732
8733         rc = 0;
8734
8735 free_buf:
8736         free(buf);
8737 close_inputfd:
8738         if (inputfile)
8739                 close(inputfd);
8740 close_fd:
8741         close(fd);
8742
8743         return rc;
8744 }
8745
8746 /**
8747  * struct verify_chunk - Mirror chunk to be verified.
8748  * @chunk:        [start, end) of the chunk.
8749  * @mirror_count: Number of mirror ids in @mirror_id array.
8750  * @mirror_id:    Array of valid mirror ids that cover the chunk.
8751  */
8752 struct verify_chunk {
8753         struct lu_extent chunk;
8754         unsigned int mirror_count;
8755         __u16 mirror_id[LUSTRE_MIRROR_COUNT_MAX];
8756 };
8757
8758 /**
8759  * print_chunks() - Print chunk information.
8760  * @fname:       Mirrored file name.
8761  * @chunks:      Array of chunks.
8762  * @chunk_count: Number of chunks in @chunks array.
8763  *
8764  * This function prints [start, end) of each chunk in @chunks
8765  * for mirrored file @fname, and also prints the valid mirror ids
8766  * that cover the chunk.
8767  *
8768  * Return: void.
8769  */
8770 static inline
8771 void print_chunks(const char *fname, struct verify_chunk *chunks,
8772                   int chunk_count)
8773 {
8774         int i;
8775         int j;
8776
8777         fprintf(stdout, "Chunks to be verified in %s:\n", fname);
8778         for (i = 0; i < chunk_count; i++) {
8779                 fprintf(stdout, DEXT, PEXT(&chunks[i].chunk));
8780
8781                 if (chunks[i].mirror_count == 0)
8782                         fprintf(stdout, "\t[");
8783                 else {
8784                         fprintf(stdout, "\t[%u", chunks[i].mirror_id[0]);
8785                         for (j = 1; j < chunks[i].mirror_count; j++)
8786                                 fprintf(stdout, ", %u", chunks[i].mirror_id[j]);
8787                 }
8788                 fprintf(stdout, "]\t%u\n", chunks[i].mirror_count);
8789         }
8790         fprintf(stdout, "\n");
8791 }
8792
8793 /**
8794  * print_checksums() - Print CRC-32 checksum values.
8795  * @chunk: A chunk and its corresponding valid mirror ids.
8796  * @crc:   CRC-32 checksum values on the chunk for each valid mirror.
8797  *
8798  * This function prints CRC-32 checksum values on @chunk for
8799  * each valid mirror that covers it.
8800  *
8801  * Return: void.
8802  */
8803 static inline
8804 void print_checksums(struct verify_chunk *chunk, unsigned long *crc)
8805 {
8806         int i;
8807
8808         fprintf(stdout,
8809                 "CRC-32 checksum value for chunk "DEXT":\n",
8810                 PEXT(&chunk->chunk));
8811         for (i = 0; i < chunk->mirror_count; i++)
8812                 fprintf(stdout, "Mirror %u:\t%#lx\n",
8813                         chunk->mirror_id[i], crc[i]);
8814         fprintf(stdout, "\n");
8815 }
8816
8817 /**
8818  * filter_mirror_id() - Filter specified mirror ids.
8819  * @chunks:      Array of chunks.
8820  * @chunk_count: Number of chunks in @chunks array.
8821  * @mirror_ids:  Specified mirror ids to be verified.
8822  * @ids_nr:      Number of specified mirror ids.
8823  *
8824  * This function scans valid mirror ids that cover each chunk in @chunks
8825  * and filters specified mirror ids.
8826  *
8827  * Return: void.
8828  */
8829 static inline
8830 void filter_mirror_id(struct verify_chunk *chunks, int chunk_count,
8831                       __u16 *mirror_ids, int ids_nr)
8832 {
8833         int i;
8834         int j;
8835         int k;
8836         __u16 valid_id[LUSTRE_MIRROR_COUNT_MAX] = { 0 };
8837         unsigned int valid_count = 0;
8838
8839         for (i = 0; i < chunk_count; i++) {
8840                 if (chunks[i].mirror_count == 0)
8841                         continue;
8842
8843                 valid_count = 0;
8844                 for (j = 0; j < ids_nr; j++) {
8845                         for (k = 0; k < chunks[i].mirror_count; k++) {
8846                                 if (chunks[i].mirror_id[k] == mirror_ids[j]) {
8847                                         valid_id[valid_count] = mirror_ids[j];
8848                                         valid_count++;
8849                                         break;
8850                                 }
8851                         }
8852                 }
8853
8854                 memcpy(chunks[i].mirror_id, valid_id,
8855                        sizeof(__u16) * valid_count);
8856                 chunks[i].mirror_count = valid_count;
8857         }
8858 }
8859
8860 /**
8861  * lfs_mirror_prepare_chunk() - Find mirror chunks to be verified.
8862  * @layout:      Mirror component list.
8863  * @chunks:      Array of chunks.
8864  * @chunks_size: Array size of @chunks.
8865  *
8866  * This function scans the components in @layout from offset 0 to LUSTRE_EOF
8867  * to find out chunk segments and store them in @chunks array.
8868  *
8869  * The @mirror_id array in each element of @chunks will store the valid
8870  * mirror ids that cover the chunk. If a mirror component covering the
8871  * chunk has LCME_FL_STALE or LCME_FL_OFFLINE flag, then the mirror id
8872  * will not be stored into the @mirror_id array, and the chunk for that
8873  * mirror will not be verified.
8874  *
8875  * The @mirror_count in each element of @chunks will store the number of
8876  * mirror ids in @mirror_id array. If @mirror_count is 0, it indicates the
8877  * chunk is invalid in all of the mirrors. And if @mirror_count is 1, it
8878  * indicates the chunk is valid in only one mirror. In both cases, the
8879  * chunk will not be verified.
8880  *
8881  * Here is an example:
8882  *
8883  *  0      1M     2M     3M     4M           EOF
8884  *  +------+-------------+--------------------+
8885  *  |      |             |      S             |       mirror1
8886  *  +------+------+------+------+-------------+
8887  *  |             |   S  |   S  |             |       mirror2
8888  *  +-------------+------+------+-------------+
8889  *
8890  * prepared @chunks array will contain 5 elements:
8891  * (([0, 1M), [1, 2], 2),
8892  *  ([1M, 2M), [1, 2], 2),
8893  *  ([2M, 3M), [1], 1),
8894  *  ([3M, 4M], [], 0),
8895  *  ([4M, EOF), [2], 1))
8896  *
8897  * Return: the actual array size of @chunks on success
8898  *         or a negative error code on failure.
8899  */
8900 static inline
8901 int lfs_mirror_prepare_chunk(struct llapi_layout *layout,
8902                              struct verify_chunk *chunks,
8903                              size_t chunks_size)
8904 {
8905         uint64_t start;
8906         uint64_t end;
8907         uint32_t mirror_id;
8908         uint32_t flags;
8909         int idx = 0;
8910         int i = 0;
8911         int rc = 0;
8912
8913         memset(chunks, 0, sizeof(*chunks) * chunks_size);
8914
8915         while (1) {
8916                 rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_FIRST);
8917                 if (rc < 0) {
8918                         fprintf(stderr,
8919                                 "%s: move to the first layout component: %s.\n",
8920                                 progname, strerror(errno));
8921                         goto error;
8922                 }
8923
8924                 i = 0;
8925                 rc = 0;
8926                 chunks[idx].chunk.e_end = LUSTRE_EOF;
8927                 while (rc == 0) {
8928                         rc = llapi_layout_comp_extent_get(layout, &start, &end);
8929                         if (rc < 0) {
8930                                 fprintf(stderr,
8931                                         "%s: llapi_layout_comp_extent_get failed: %s.\n",
8932                                         progname, strerror(errno));
8933                                 goto error;
8934                         }
8935
8936                         if (start > chunks[idx].chunk.e_start ||
8937                             end <= chunks[idx].chunk.e_start)
8938                                 goto next;
8939
8940                         if (end < chunks[idx].chunk.e_end)
8941                                 chunks[idx].chunk.e_end = end;
8942
8943                         rc = llapi_layout_comp_flags_get(layout, &flags);
8944                         if (rc < 0) {
8945                                 fprintf(stderr,
8946                                         "%s: llapi_layout_comp_flags_get failed: %s.\n",
8947                                         progname, strerror(errno));
8948                                 goto error;
8949                         }
8950
8951                         if (flags & LCME_FL_STALE || flags & LCME_FL_OFFLINE)
8952                                 goto next;
8953
8954                         rc = llapi_layout_mirror_id_get(layout, &mirror_id);
8955                         if (rc < 0) {
8956                                 fprintf(stderr,
8957                                         "%s: llapi_layout_mirror_id_get failed: %s.\n",
8958                                         progname, strerror(errno));
8959                                 goto error;
8960                         }
8961
8962                         chunks[idx].mirror_id[i] = mirror_id;
8963                         i++;
8964                         if (i >= ARRAY_SIZE(chunks[idx].mirror_id)) {
8965                                 fprintf(stderr,
8966                                         "%s: mirror_id array is too small.\n",
8967                                         progname);
8968                                 rc = -EINVAL;
8969                                 goto error;
8970                         }
8971
8972                 next:
8973                         rc = llapi_layout_comp_use(layout,
8974                                                    LLAPI_LAYOUT_COMP_USE_NEXT);
8975                         if (rc < 0) {
8976                                 fprintf(stderr,
8977                                         "%s: move to the next layout component: %s.\n",
8978                                         progname, strerror(errno));
8979                                 goto error;
8980                         }
8981                 } /* loop through all components */
8982
8983                 chunks[idx].mirror_count = i;
8984
8985                 if (chunks[idx].chunk.e_end == LUSTRE_EOF)
8986                         break;
8987
8988                 idx++;
8989                 if (idx >= chunks_size) {
8990                         fprintf(stderr, "%s: chunks array is too small.\n",
8991                                 progname);
8992                         rc = -EINVAL;
8993                         goto error;
8994                 }
8995
8996                 chunks[idx].chunk.e_start = chunks[idx - 1].chunk.e_end;
8997         }
8998
8999 error:
9000         return rc < 0 ? rc : idx + 1;
9001 }
9002
9003 /**
9004  * lfs_mirror_verify_chunk() - Verify a chunk.
9005  * @fd:        File descriptor of the mirrored file.
9006  * @file_size: Size of the mirrored file.
9007  * @chunk:     A chunk and its corresponding valid mirror ids.
9008  * @verbose:   Verbose mode.
9009  *
9010  * This function verifies a @chunk contains exactly the same data
9011  * ammong the mirrors that cover it.
9012  *
9013  * If @verbose is specified, then the function will print where the
9014  * differences are if the data do not match. Otherwise, it will
9015  * just return an error in that case.
9016  *
9017  * Return: 0 on success or a negative error code on failure.
9018  */
9019 static inline
9020 int lfs_mirror_verify_chunk(int fd, size_t file_size,
9021                             struct verify_chunk *chunk, int verbose)
9022 {
9023         const size_t buflen = 4 * 1024 * 1024; /* 4M */
9024         void *buf;
9025         size_t page_size = sysconf(_SC_PAGESIZE);
9026         ssize_t bytes_read;
9027         ssize_t bytes_done;
9028         size_t count;
9029         off_t pos;
9030         unsigned long crc;
9031         unsigned long crc_array[LUSTRE_MIRROR_COUNT_MAX] = { 0 };
9032         int i;
9033         int rc = 0;
9034
9035         if (file_size == 0)
9036                 return 0;
9037
9038         rc = posix_memalign(&buf, page_size, buflen);
9039         if (rc) /* error code is returned directly */
9040                 return -rc;
9041
9042         if (verbose > 1) {
9043                 fprintf(stdout, "Verifying chunk "DEXT" on mirror:",
9044                         PEXT(&chunk->chunk));
9045                 for (i = 0; i < chunk->mirror_count; i++)
9046                         fprintf(stdout, " %u", chunk->mirror_id[i]);
9047                 fprintf(stdout, "\n");
9048         }
9049
9050         bytes_done = 0;
9051         count = MIN(chunk->chunk.e_end, file_size) - chunk->chunk.e_start;
9052         pos = chunk->chunk.e_start;
9053         while (bytes_done < count) {
9054                 /* compute initial CRC-32 checksum */
9055                 crc = crc32(0L, Z_NULL, 0);
9056                 memset(crc_array, 0, sizeof(crc_array));
9057
9058                 bytes_read = 0;
9059                 for (i = 0; i < chunk->mirror_count; i++) {
9060                         bytes_read = llapi_mirror_read(fd, chunk->mirror_id[i],
9061                                                        buf, buflen, pos);
9062                         if (bytes_read < 0) {
9063                                 rc = bytes_read;
9064                                 fprintf(stderr,
9065                                         "%s: failed to read data from mirror %u: %s.\n",
9066                                         progname, chunk->mirror_id[i],
9067                                         strerror(-rc));
9068                                 goto error;
9069                         }
9070
9071                         /* compute new CRC-32 checksum */
9072                         crc_array[i] = crc32(crc, buf, bytes_read);
9073                 }
9074
9075                 if (verbose)
9076                         print_checksums(chunk, crc_array);
9077
9078                 /* compare CRC-32 checksum values */
9079                 for (i = 1; i < chunk->mirror_count; i++) {
9080                         if (crc_array[i] != crc_array[0]) {
9081                                 rc = -EINVAL;
9082                                 if (!verbose)
9083                                         goto error;
9084
9085                                 fprintf(stderr,
9086                                         "%s: chunk "DEXT" has different checksum value on mirror %u and mirror %u.\n",
9087                                         progname, PEXT(&chunk->chunk),
9088                                         chunk->mirror_id[0],
9089                                         chunk->mirror_id[i]);
9090                         }
9091                 }
9092
9093                 pos += bytes_read;
9094                 bytes_done += bytes_read;
9095         }
9096
9097         if (verbose > 1 && rc == 0) {
9098                 fprintf(stdout, "Verifying chunk "DEXT" on mirror:",
9099                         PEXT(&chunk->chunk));
9100                 for (i = 0; i < chunk->mirror_count; i++)
9101                         fprintf(stdout, " %u", chunk->mirror_id[i]);
9102                 fprintf(stdout, " PASS\n\n");
9103         }
9104
9105 error:
9106         free(buf);
9107         return rc;
9108 }
9109
9110 /**
9111  * lfs_mirror_verify_file() - Verify a mirrored file.
9112  * @fname:      Mirrored file name.
9113  * @mirror_ids: Specified mirror ids to be verified.
9114  * @ids_nr:     Number of specified mirror ids.
9115  * @verbose:    Verbose mode.
9116  *
9117  * This function verifies that each SYNC mirror of a mirrored file
9118  * specified by @fname contains exactly the same data.
9119  *
9120  * If @mirror_ids is specified, then the function will verify the
9121  * mirrors specified by @mirror_ids contain exactly the same data.
9122  *
9123  * If @verbose is specified, then the function will print where the
9124  * differences are if the data do not match. Otherwise, it will
9125  * just return an error in that case.
9126  *
9127  * Return: 0 on success or a negative error code on failure.
9128  */
9129 static inline
9130 int lfs_mirror_verify_file(const char *fname, __u16 *mirror_ids, int ids_nr,
9131                            int verbose)
9132 {
9133         struct verify_chunk chunks_array[1024] = { };
9134         struct llapi_layout *layout = NULL;
9135         struct stat stbuf;
9136         uint32_t flr_state;
9137         int fd;
9138         int chunk_count = 0;
9139         int idx = 0;
9140         int rc = 0;
9141         int rc1 = 0;
9142         int rc2 = 0;
9143
9144         if (stat(fname, &stbuf) < 0) {
9145                 fprintf(stderr, "%s: cannot stat file '%s': %s.\n",
9146                         progname, fname, strerror(errno));
9147                 rc = -errno;
9148                 goto error;
9149         }
9150
9151         if (!S_ISREG(stbuf.st_mode)) {
9152                 fprintf(stderr, "%s: '%s' is not a regular file.\n",
9153                         progname, fname);
9154                 rc = -EINVAL;
9155                 goto error;
9156         }
9157
9158         if (stbuf.st_size == 0) {
9159                 if (verbose)
9160                         fprintf(stdout, "%s: '%s' file size is 0.\n",
9161                                 progname, fname);
9162                 rc = 0;
9163                 goto error;
9164         }
9165
9166         fd = open(fname, O_DIRECT | O_RDONLY);
9167         if (fd < 0) {
9168                 fprintf(stderr, "%s: cannot open '%s': %s.\n",
9169                         progname, fname, strerror(errno));
9170                 rc = -errno;
9171                 goto error;
9172         }
9173
9174         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
9175         if (rc < 0) {
9176                 fprintf(stderr, "%s: '%s' llapi_lease_acquire failed: %s.\n",
9177                         progname, fname, strerror(errno));
9178                 goto close_fd;
9179         }
9180
9181         layout = llapi_layout_get_by_fd(fd, 0);
9182         if (layout == NULL) {
9183                 fprintf(stderr, "%s: '%s' llapi_layout_get_by_fd failed: %s.\n",
9184                         progname, fname, strerror(errno));
9185                 rc = -errno;
9186                 llapi_lease_release(fd);
9187                 goto close_fd;
9188         }
9189
9190         rc = llapi_layout_flags_get(layout, &flr_state);
9191         if (rc < 0) {
9192                 fprintf(stderr, "%s: '%s' llapi_layout_flags_get failed: %s.\n",
9193                         progname, fname, strerror(errno));
9194                 rc = -errno;
9195                 goto free_layout;
9196         }
9197
9198         flr_state &= LCM_FL_FLR_MASK;
9199         switch (flr_state) {
9200         case LCM_FL_NONE:
9201                 rc = -EINVAL;
9202                 fprintf(stderr, "%s: '%s' file state error: %s.\n",
9203                         progname, fname, llapi_layout_flags_string(flr_state));
9204                 goto free_layout;
9205         default:
9206                 break;
9207         }
9208
9209         /* find out mirror chunks to be verified */
9210         chunk_count = lfs_mirror_prepare_chunk(layout, chunks_array,
9211                                                ARRAY_SIZE(chunks_array));
9212         if (chunk_count < 0) {
9213                 rc = chunk_count;
9214                 goto free_layout;
9215         }
9216
9217         if (ids_nr > 0)
9218                 /* filter specified mirror ids */
9219                 filter_mirror_id(chunks_array, chunk_count, mirror_ids, ids_nr);
9220
9221         if (verbose > 2)
9222                 print_chunks(fname, chunks_array, chunk_count);
9223
9224         for (idx = 0; idx < chunk_count; idx++) {
9225                 if (chunks_array[idx].chunk.e_start >= stbuf.st_size) {
9226                         if (verbose)
9227                                 fprintf(stdout,
9228                                         "%s: '%s' chunk "DEXT" exceeds file size %#llx: skipped\n",
9229                                         progname, fname,
9230                                         PEXT(&chunks_array[idx].chunk),
9231                                         (unsigned long long)stbuf.st_size);
9232                         break;
9233                 }
9234
9235                 if (chunks_array[idx].mirror_count == 0) {
9236                         fprintf(stderr,
9237                                 "%s: '%s' chunk "DEXT" is invalid in all of the mirrors: ",
9238                                 progname, fname,
9239                                 PEXT(&chunks_array[idx].chunk));
9240                         if (verbose) {
9241                                 fprintf(stderr, "skipped\n");
9242                                 continue;
9243                         }
9244                         rc = -EINVAL;
9245                         fprintf(stderr, "failed\n");
9246                         goto free_layout;
9247                 }
9248
9249                 if (chunks_array[idx].mirror_count == 1) {
9250                         if (verbose)
9251                                 fprintf(stdout,
9252                                         "%s: '%s' chunk "DEXT" is only valid in mirror %u: skipped\n",
9253                                         progname, fname,
9254                                         PEXT(&chunks_array[idx].chunk),
9255                                         chunks_array[idx].mirror_id[0]);
9256                         continue;
9257                 }
9258
9259                 rc = llapi_lease_check(fd);
9260                 if (rc != LL_LEASE_RDLCK) {
9261                         fprintf(stderr, "%s: '%s' lost lease lock.\n",
9262                                 progname, fname);
9263                         goto free_layout;
9264                 }
9265
9266                 /* verify one chunk */
9267                 rc1 = lfs_mirror_verify_chunk(fd, stbuf.st_size,
9268                                               &chunks_array[idx], verbose);
9269                 if (rc1 < 0) {
9270                         rc2 = rc1;
9271                         if (!verbose) {
9272                                 rc = rc1;
9273                                 goto free_layout;
9274                         }
9275                 }
9276         }
9277
9278         if (rc2 < 0)
9279                 rc = rc2;
9280
9281 free_layout:
9282         llapi_layout_free(layout);
9283         llapi_lease_release(fd);
9284 close_fd:
9285         close(fd);
9286 error:
9287         return rc;
9288 }
9289
9290 /**
9291  * lfs_mirror_verify() - Parse and execute lfs mirror verify command.
9292  * @argc: The count of lfs mirror verify command line arguments.
9293  * @argv: Array of strings for lfs mirror verify command line arguments.
9294  *
9295  * This function parses lfs mirror verify command and verifies the
9296  * specified mirrored file(s).
9297  *
9298  * Return: 0 on success or a negative error code on failure.
9299  */
9300 static inline int lfs_mirror_verify(int argc, char **argv)
9301 {
9302         __u16 mirror_ids[LUSTRE_MIRROR_COUNT_MAX] = { 0 };
9303         int ids_nr = 0;
9304         int c;
9305         int verbose = 0;
9306         int rc = 0;
9307         int rc1 = 0;
9308         char cmd[PATH_MAX];
9309
9310         struct option long_opts[] = {
9311         { .val = 'o',   .name = "only",         .has_arg = required_argument },
9312         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
9313         { .name = NULL } };
9314
9315         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
9316         progname = cmd;
9317         while ((c = getopt_long(argc, argv, "o:v", long_opts, NULL)) >= 0) {
9318                 switch (c) {
9319                 case 'o':
9320                         rc = parse_mirror_ids(mirror_ids,
9321                                               ARRAY_SIZE(mirror_ids),
9322                                               optarg);
9323                         if (rc < 0) {
9324                                 fprintf(stderr,
9325                                         "%s: bad mirror ids '%s'.\n",
9326                                         progname, optarg);
9327                                 goto error;
9328                         }
9329                         ids_nr = rc;
9330                         if (ids_nr < 2) {
9331                                 fprintf(stderr,
9332                                         "%s: at least 2 mirror ids needed with '--only' option.\n",
9333                                         progname);
9334                                 rc = CMD_HELP;
9335                                 goto error;
9336                         }
9337                         break;
9338                 case 'v':
9339                         verbose++;
9340                         break;
9341                 default:
9342                         fprintf(stderr, "%s: option '%s' unrecognized.\n",
9343                                 progname, argv[optind - 1]);
9344                         rc = -EINVAL;
9345                         goto error;
9346                 }
9347         }
9348
9349         if (argc == optind) {
9350                 fprintf(stderr, "%s: no file name given.\n", progname);
9351                 rc = CMD_HELP;
9352                 goto error;
9353         }
9354
9355         if (ids_nr > 0 && argc > optind + 1) {
9356                 fprintf(stderr,
9357                         "%s: '--only' cannot be used upon multiple files.\n",
9358                         progname);
9359                 rc = CMD_HELP;
9360                 goto error;
9361
9362         }
9363
9364         if (ids_nr > 0) {
9365                 rc = verify_mirror_ids(argv[optind], mirror_ids, ids_nr);
9366                 if (rc < 0)
9367                         goto error;
9368         }
9369
9370         rc = 0;
9371         for (; optind < argc; optind++) {
9372                 rc1 = lfs_mirror_verify_file(argv[optind], mirror_ids, ids_nr,
9373                                              verbose);
9374                 if (rc1 < 0)
9375                         rc = rc1;
9376         }
9377 error:
9378         return rc;
9379 }
9380
9381 /**
9382  * lfs_mirror() - Parse and execute lfs mirror commands.
9383  * @argc: The count of lfs mirror command line arguments.
9384  * @argv: Array of strings for lfs mirror command line arguments.
9385  *
9386  * This function parses lfs mirror commands and performs the
9387  * corresponding functions specified in mirror_cmdlist[].
9388  *
9389  * Return: 0 on success or an error code on failure.
9390  */
9391 static int lfs_mirror(int argc, char **argv)
9392 {
9393         char cmd[PATH_MAX];
9394         int rc = 0;
9395
9396         setlinebuf(stdout);
9397
9398         Parser_init("lfs-mirror > ", mirror_cmdlist);
9399
9400         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
9401         progname = cmd;
9402         program_invocation_short_name = cmd;
9403         if (argc > 1)
9404                 rc = Parser_execarg(argc - 1, argv + 1, mirror_cmdlist);
9405         else
9406                 rc = Parser_commands();
9407
9408         return rc < 0 ? -rc : rc;
9409 }
9410
9411 static void lustre_som_swab(struct lustre_som_attrs *attrs)
9412 {
9413 #if __BYTE_ORDER == __BIG_ENDIAN
9414         __swab16s(&attrs->lsa_valid);
9415         __swab64s(&attrs->lsa_size);
9416         __swab64s(&attrs->lsa_blocks);
9417 #endif
9418 }
9419
9420 enum lfs_som_type {
9421         LFS_SOM_SIZE = 0x1,
9422         LFS_SOM_BLOCKS = 0x2,
9423         LFS_SOM_FLAGS = 0x4,
9424         LFS_SOM_ATTR_ALL = LFS_SOM_SIZE | LFS_SOM_BLOCKS |
9425                            LFS_SOM_FLAGS,
9426 };
9427
9428 static int lfs_getsom(int argc, char **argv)
9429 {
9430         const char *path;
9431         struct lustre_som_attrs *attrs;
9432         char buf[sizeof(*attrs) + 64];
9433         enum lfs_som_type type = LFS_SOM_ATTR_ALL;
9434         int rc = 0, c;
9435
9436         while ((c = getopt(argc, argv, "sbf")) != -1) {
9437                 switch (c) {
9438                 case 's':
9439                         type = LFS_SOM_SIZE;
9440                         break;
9441                 case 'b':
9442                         type = LFS_SOM_BLOCKS;
9443                         break;
9444                 case 'f':
9445                         type = LFS_SOM_FLAGS;
9446                         break;
9447                 default:
9448                         fprintf(stderr, "%s: invalid option '%c'\n",
9449                                 progname, optopt);
9450                         return CMD_HELP;
9451                 }
9452         }
9453
9454         argc -= optind;
9455         argv += optind;
9456
9457         if (argc != 1) {
9458                 fprintf(stderr, "%s: %s\n",
9459                         progname, argc == 0 ? "miss file target" :
9460                         "input more than 2 files");
9461                 return CMD_HELP;
9462         }
9463
9464         path = argv[0];
9465         attrs = (void *)buf;
9466         rc = lgetxattr(path, "trusted.som", attrs, sizeof(buf));
9467         if (rc < 0) {
9468                 rc = -errno;
9469                 fprintf(stderr, "%s failed to get som xattr: %s (%d)\n",
9470                         argv[0], strerror(errno), errno);
9471                 return rc;
9472         }
9473
9474         lustre_som_swab(attrs);
9475
9476         switch (type) {
9477         case LFS_SOM_ATTR_ALL:
9478                 printf("file: %s size: %llu blocks: %llu flags: %x\n",
9479                        path, attrs->lsa_size, attrs->lsa_blocks,
9480                        attrs->lsa_valid);
9481                 break;
9482         case LFS_SOM_SIZE:
9483                 printf("%llu\n", attrs->lsa_size);
9484                 break;
9485         case LFS_SOM_BLOCKS:
9486                 printf("%llu\n", attrs->lsa_blocks);
9487                 break;
9488         case LFS_SOM_FLAGS:
9489                 printf("%x\n", attrs->lsa_valid);
9490                 break;
9491         default:
9492                 fprintf(stderr, "%s: unknown option\n", progname);
9493                 return CMD_HELP;
9494         }
9495
9496         return 0;
9497 }
9498
9499 /**
9500  * lfs_mirror_list_commands() - List lfs mirror commands.
9501  * @argc: The count of command line arguments.
9502  * @argv: Array of strings for command line arguments.
9503  *
9504  * This function lists lfs mirror commands defined in mirror_cmdlist[].
9505  *
9506  * Return: 0 on success.
9507  */
9508 static int lfs_mirror_list_commands(int argc, char **argv)
9509 {
9510         char buffer[81] = "";
9511
9512         Parser_list_commands(mirror_cmdlist, buffer, sizeof(buffer),
9513                              NULL, 0, 4);
9514
9515         return 0;
9516 }
9517
9518 static int lfs_list_commands(int argc, char **argv)
9519 {
9520         char buffer[81] = ""; /* 80 printable chars + terminating NUL */
9521
9522         Parser_list_commands(cmdlist, buffer, sizeof(buffer), NULL, 0, 4);
9523
9524         return 0;
9525 }
9526
9527 int main(int argc, char **argv)
9528 {
9529         int rc;
9530
9531         /* Ensure that liblustreapi constructor has run */
9532         if (!llapi_liblustreapi_initialized())
9533                 fprintf(stderr, "liblustreapi was not properly initialized\n");
9534
9535         setlinebuf(stdout);
9536         opterr = 0;
9537
9538         Parser_init("lfs > ", cmdlist);
9539
9540         progname = program_invocation_short_name; /* Used in error messages */
9541         if (argc > 1) {
9542                 llapi_set_command_name(argv[1]);
9543                 rc = Parser_execarg(argc - 1, argv + 1, cmdlist);
9544                 llapi_clear_command_name();
9545         } else {
9546                 rc = Parser_commands();
9547         }
9548
9549         return rc < 0 ? -rc : rc;
9550 }
9551
9552 #ifdef _LUSTRE_IDL_H_
9553 /* Everything we need here should be included by lustreapi.h. */
9554 # error "lfs should not depend on lustre_idl.h"
9555 #endif /* _LUSTRE_IDL_H_ */