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