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