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