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