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