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