Whamcloud - gitweb
LU-12694 quota: display correct group quota information
[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 pathbad = -1;
3985         int neg_opt = 0;
3986         time_t *xtime;
3987         int *xsign;
3988         int isoption;
3989         char *endptr;
3990
3991         time(&t);
3992
3993         /* when getopt_long_only() hits '!' it returns 1, puts "!" in optarg */
3994         while ((c = getopt_long_only(argc, argv,
3995                         "-0A:b:c:C:D:E:g:G:H:i:L:m:M:n:N:O:Ppqrs:S:t:T:u:U:vz:",
3996                         long_opts, NULL)) >= 0) {
3997                 xtime = NULL;
3998                 xsign = NULL;
3999                 if (neg_opt)
4000                         --neg_opt;
4001                 /* '!' is part of option */
4002                 /* when getopt_long_only() finds a string which is not
4003                  * an option nor a known option argument it returns 1
4004                  * in that case if we already have found pathstart and pathend
4005                  * (i.e. we have the list of pathnames),
4006                  * the only supported value is "!"
4007                  */
4008                 isoption = (c != 1) || (strcmp(optarg, "!") == 0);
4009                 if (!isoption && pathend != -1) {
4010                         fprintf(stderr, "err: %s: filename|dirname must either "
4011                                         "precede options or follow options\n",
4012                                         argv[0]);
4013                         ret = CMD_HELP;
4014                         goto err;
4015                 }
4016                 if (!isoption && pathstart == -1)
4017                         pathstart = optind - 1;
4018                 if (isoption && pathstart != -1 && pathend == -1)
4019                         pathend = optind - 2;
4020                 switch (c) {
4021                 case 0:
4022                         /* Long options. */
4023                         break;
4024                 case 1:
4025                         /* unknown; opt is "!" or path component,
4026                          * checking done above.
4027                          */
4028                         if (strcmp(optarg, "!") == 0)
4029                                 neg_opt = 2;
4030                         break;
4031                 case 'A':
4032                         xtime = &param.fp_atime;
4033                         xsign = &param.fp_asign;
4034                         param.fp_exclude_atime = !!neg_opt;
4035                         /* no break, this falls through to 'C' for ctime */
4036                 case 'C':
4037                         if (c == 'C') {
4038                                 xtime = &param.fp_ctime;
4039                                 xsign = &param.fp_csign;
4040                                 param.fp_exclude_ctime = !!neg_opt;
4041                         }
4042                         /* no break, this falls through to 'M' for mtime */
4043                 case 'M':
4044                         if (c == 'M') {
4045                                 xtime = &param.fp_mtime;
4046                                 xsign = &param.fp_msign;
4047                                 param.fp_exclude_mtime = !!neg_opt;
4048                         }
4049                         rc = set_time(&param, &t, xtime, optarg);
4050                         if (rc == LONG_MAX) {
4051                                 ret = -1;
4052                                 goto err;
4053                         }
4054                         if (rc)
4055                                 *xsign = rc;
4056                         break;
4057                 case 'b':
4058                         if (optarg[0] == '+') {
4059                                 param.fp_blocks_sign = -1;
4060                                 optarg++;
4061                         } else if (optarg[0] == '-') {
4062                                 param.fp_blocks_sign =  1;
4063                                 optarg++;
4064                         }
4065
4066                         param.fp_blocks_units = 1024;
4067                         ret = llapi_parse_size(optarg, &param.fp_blocks,
4068                                                &param.fp_blocks_units, 0);
4069                         if (ret) {
4070                                 fprintf(stderr, "error: bad blocks '%s'\n",
4071                                         optarg);
4072                                 goto err;
4073                         }
4074                         param.fp_check_blocks = 1;
4075                         param.fp_exclude_blocks = !!neg_opt;
4076                         break;
4077                 case LFS_COMP_COUNT_OPT:
4078                         if (optarg[0] == '+') {
4079                                 param.fp_comp_count_sign = -1;
4080                                 optarg++;
4081                         } else if (optarg[0] == '-') {
4082                                 param.fp_comp_count_sign =  1;
4083                                 optarg++;
4084                         }
4085
4086                         param.fp_comp_count = strtoul(optarg, &endptr, 0);
4087                         if (*endptr != '\0') {
4088                                 fprintf(stderr, "error: bad component count "
4089                                         "'%s'\n", optarg);
4090                                 goto err;
4091                         }
4092                         param.fp_check_comp_count = 1;
4093                         param.fp_exclude_comp_count = !!neg_opt;
4094                         break;
4095                 case LFS_COMP_FLAGS_OPT:
4096                         rc = comp_str2flags(optarg, &param.fp_comp_flags,
4097                                             &param.fp_comp_neg_flags);
4098                         if (rc) {
4099                                 fprintf(stderr, "error: bad component flags "
4100                                         "'%s'\n", optarg);
4101                                 goto err;
4102                         }
4103                         param.fp_check_comp_flags = 1;
4104                         if (neg_opt) {
4105                                 __u32 flags = param.fp_comp_neg_flags;
4106                                 param.fp_comp_neg_flags = param.fp_comp_flags;
4107                                 param.fp_comp_flags = flags;
4108                         }
4109                         break;
4110                 case LFS_COMP_START_OPT:
4111                         if (optarg[0] == '+') {
4112                                 param.fp_comp_start_sign = -1;
4113                                 optarg++;
4114                         } else if (optarg[0] == '-') {
4115                                 param.fp_comp_start_sign =  1;
4116                                 optarg++;
4117                         }
4118
4119                         rc = llapi_parse_size(optarg, &param.fp_comp_start,
4120                                               &param.fp_comp_start_units, 0);
4121                         if (rc) {
4122                                 fprintf(stderr, "error: bad component start "
4123                                         "'%s'\n", optarg);
4124                                 goto err;
4125                         }
4126                         param.fp_check_comp_start = 1;
4127                         param.fp_exclude_comp_start = !!neg_opt;
4128                         break;
4129                 case LFS_MIRROR_STATE_OPT:
4130                         rc = mirror_str2state(optarg, &param.fp_mirror_state,
4131                                               &param.fp_mirror_neg_state);
4132                         if (rc) {
4133                                 fprintf(stderr,
4134                                         "error: bad mirrored file state '%s'\n",
4135                                         optarg);
4136                                 goto err;
4137                         }
4138                         param.fp_check_mirror_state = 1;
4139                         if (neg_opt) {
4140                                 __u16 state = param.fp_mirror_neg_state;
4141                                 param.fp_mirror_neg_state =
4142                                         param.fp_mirror_state;
4143                                 param.fp_mirror_state = state;
4144                         }
4145                         break;
4146                 case 'c':
4147                         if (optarg[0] == '+') {
4148                                 param.fp_stripe_count_sign = -1;
4149                                 optarg++;
4150                         } else if (optarg[0] == '-') {
4151                                 param.fp_stripe_count_sign =  1;
4152                                 optarg++;
4153                         }
4154
4155                         param.fp_stripe_count = strtoul(optarg, &endptr, 0);
4156                         if (*endptr != '\0') {
4157                                 fprintf(stderr,"error: bad stripe_count '%s'\n",
4158                                         optarg);
4159                                 ret = -1;
4160                                 goto err;
4161                         }
4162                         param.fp_check_stripe_count = 1;
4163                         param.fp_exclude_stripe_count = !!neg_opt;
4164                         break;
4165                 case 'D':
4166                         param.fp_max_depth = strtol(optarg, 0, 0);
4167                         break;
4168                 case 'E':
4169                         if (optarg[0] == '+') {
4170                                 param.fp_comp_end_sign = -1;
4171                                 optarg++;
4172                         } else if (optarg[0] == '-') {
4173                                 param.fp_comp_end_sign =  1;
4174                                 optarg++;
4175                         }
4176
4177                         if (arg_is_eof(optarg)) {
4178                                 param.fp_comp_end = LUSTRE_EOF;
4179                                 param.fp_comp_end_units = 1;
4180                                 rc = 0;
4181                         } else {
4182                                 rc = llapi_parse_size(optarg,
4183                                                 &param.fp_comp_end,
4184                                                 &param.fp_comp_end_units, 0);
4185                         }
4186                         if (rc) {
4187                                 fprintf(stderr, "error: bad component end "
4188                                         "'%s'\n", optarg);
4189                                 goto err;
4190                         }
4191                         param.fp_check_comp_end = 1;
4192                         param.fp_exclude_comp_end = !!neg_opt;
4193                         break;
4194                 case LFS_LAYOUT_FOREIGN_OPT: {
4195                         /* all types by default */
4196                         uint32_t type = LU_FOREIGN_TYPE_UNKNOWN;
4197
4198                         if (optarg != NULL) {
4199                                 /* check pure numeric */
4200                                 type = strtoul(optarg, &endptr, 0);
4201                                 if (*endptr) {
4202                                         /* check name */
4203                                         type = check_foreign_type_name(optarg);
4204                                         if (type == LU_FOREIGN_TYPE_UNKNOWN) {
4205                                                 fprintf(stderr,
4206                                                         "%s %s: unknown foreign type '%s'\n",
4207                                                         progname, argv[0],
4208                                                         optarg);
4209                                                 return CMD_HELP;
4210                                         }
4211                                 }
4212                         }
4213                         param.fp_foreign_type = type;
4214                         param.fp_check_foreign = 1;
4215                         param.fp_exclude_foreign = !!neg_opt;
4216                         break;
4217                 }
4218                 case 'g':
4219                 case 'G':
4220                         rc = name2gid(&param.fp_gid, optarg);
4221                         if (rc) {
4222                                 param.fp_gid = strtoul(optarg, &endptr, 10);
4223                                 if (*endptr != '\0') {
4224                                         fprintf(stderr, "Group/GID: %s cannot "
4225                                                 "be found.\n", optarg);
4226                                         ret = -1;
4227                                         goto err;
4228                                 }
4229                         }
4230                         param.fp_exclude_gid = !!neg_opt;
4231                         param.fp_check_gid = 1;
4232                         break;
4233                 case 'H':
4234                         param.fp_hash_type = check_hashtype(optarg);
4235                         if (param.fp_hash_type == 0) {
4236                                 fprintf(stderr, "error: bad hash_type '%s'\n",
4237                                         optarg);
4238                                 ret = -1;
4239                                 goto err;
4240                         }
4241                         param.fp_check_hash_type = 1;
4242                         param.fp_exclude_hash_type = !!neg_opt;
4243                         break;
4244                 case 'L':
4245                         ret = name2layout(&param.fp_layout, optarg);
4246                         if (ret)
4247                                 goto err;
4248                         param.fp_exclude_layout = !!neg_opt;
4249                         param.fp_check_layout = 1;
4250                         break;
4251                 case 'u':
4252                 case 'U':
4253                         rc = name2uid(&param.fp_uid, optarg);
4254                         if (rc) {
4255                                 param.fp_uid = strtoul(optarg, &endptr, 10);
4256                                 if (*endptr != '\0') {
4257                                         fprintf(stderr, "User/UID: %s cannot "
4258                                                 "be found.\n", optarg);
4259                                         ret = -1;
4260                                         goto err;
4261                                 }
4262                         }
4263                         param.fp_exclude_uid = !!neg_opt;
4264                         param.fp_check_uid = 1;
4265                         break;
4266                 case 'n':
4267                         param.fp_pattern = (char *)optarg;
4268                         param.fp_exclude_pattern = !!neg_opt;
4269                         break;
4270                 case 'N':
4271                         if (optarg[0] == '+') {
4272                                 param.fp_mirror_count_sign = -1;
4273                                 optarg++;
4274                         } else if (optarg[0] == '-') {
4275                                 param.fp_mirror_count_sign =  1;
4276                                 optarg++;
4277                         }
4278
4279                         param.fp_mirror_count = strtoul(optarg, &endptr, 0);
4280                         if (*endptr != '\0') {
4281                                 fprintf(stderr,
4282                                         "error: bad mirror count '%s'\n",
4283                                         optarg);
4284                                 goto err;
4285                         }
4286                         param.fp_check_mirror_count = 1;
4287                         param.fp_exclude_mirror_count = !!neg_opt;
4288                         break;
4289                 case 'm':
4290                 case 'i':
4291                 case 'O': {
4292                         char *buf, *token, *next, *p;
4293                         int len = 1;
4294                         void *tmp;
4295
4296                         buf = strdup(optarg);
4297                         if (buf == NULL) {
4298                                 ret = -ENOMEM;
4299                                 goto err;
4300                         }
4301
4302                         param.fp_exclude_obd = !!neg_opt;
4303
4304                         token = buf;
4305                         while (token && *token) {
4306                                 token = strchr(token, ',');
4307                                 if (token) {
4308                                         len++;
4309                                         token++;
4310                                 }
4311                         }
4312                         if (c == 'm') {
4313                                 param.fp_exclude_mdt = !!neg_opt;
4314                                 param.fp_num_alloc_mdts += len;
4315                                 tmp = realloc(param.fp_mdt_uuid,
4316                                               param.fp_num_alloc_mdts *
4317                                               sizeof(*param.fp_mdt_uuid));
4318                                 if (tmp == NULL) {
4319                                         ret = -ENOMEM;
4320                                         goto err_free;
4321                                 }
4322
4323                                 param.fp_mdt_uuid = tmp;
4324                         } else {
4325                                 param.fp_exclude_obd = !!neg_opt;
4326                                 param.fp_num_alloc_obds += len;
4327                                 tmp = realloc(param.fp_obd_uuid,
4328                                               param.fp_num_alloc_obds *
4329                                               sizeof(*param.fp_obd_uuid));
4330                                 if (tmp == NULL) {
4331                                         ret = -ENOMEM;
4332                                         goto err_free;
4333                                 }
4334
4335                                 param.fp_obd_uuid = tmp;
4336                         }
4337                         for (token = buf; token && *token; token = next) {
4338                                 struct obd_uuid *puuid;
4339                                 if (c == 'm') {
4340                                         puuid =
4341                                         &param.fp_mdt_uuid[param.fp_num_mdts++];
4342                                 } else {
4343                                         puuid =
4344                                         &param.fp_obd_uuid[param.fp_num_obds++];
4345                                 }
4346                                 p = strchr(token, ',');
4347                                 next = 0;
4348                                 if (p) {
4349                                         *p = 0;
4350                                         next = p+1;
4351                                 }
4352
4353                                 if (strlen(token) > sizeof(puuid->uuid) - 1) {
4354                                         ret = -E2BIG;
4355                                         goto err_free;
4356                                 }
4357
4358                                 strncpy(puuid->uuid, token,
4359                                         sizeof(puuid->uuid));
4360                         }
4361 err_free:
4362                         if (buf)
4363                                 free(buf);
4364                         break;
4365                 }
4366 #if LUSTRE_VERSION_CODE >= OBD_OCD_VERSION(2, 18, 53, 0)
4367                 case 'p':
4368 #endif
4369                 case LFS_POOL_OPT:
4370                         if (strlen(optarg) > LOV_MAXPOOLNAME) {
4371                                 fprintf(stderr,
4372                                         "Pool name %s is too long (max %d)\n",
4373                                         optarg, LOV_MAXPOOLNAME);
4374                                 ret = -1;
4375                                 goto err;
4376                         }
4377                         /*
4378                          * We do check for empty pool because empty pool
4379                          * is used to find V1 LOV attributes
4380                          */
4381                         strncpy(param.fp_poolname, optarg, LOV_MAXPOOLNAME);
4382                         param.fp_poolname[LOV_MAXPOOLNAME] = '\0';
4383                         param.fp_exclude_pool = !!neg_opt;
4384                         param.fp_check_pool = 1;
4385                         break;
4386 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 14, 53, 0)
4387                 case 'p': /* want this for --pool, to match getstripe/find */
4388                         fprintf(stderr,
4389                                 "warning: -p deprecated, use --print0 or -0\n");
4390 #endif
4391                 case '0':
4392                         param.fp_zero_end = 1;
4393                         break;
4394                 case 'P': /* we always print, this option is a no-op */
4395                         break;
4396                 case LFS_PROJID_OPT:
4397                         rc = name2projid(&param.fp_projid, optarg);
4398                         if (rc) {
4399                                 param.fp_projid = strtoul(optarg, &endptr, 10);
4400                                 if (*endptr != '\0') {
4401                                         fprintf(stderr,
4402                                                 "Invalid project ID: %s",
4403                                                 optarg);
4404                                         ret = -1;
4405                                         goto err;
4406                                 }
4407                         }
4408                         param.fp_exclude_projid = !!neg_opt;
4409                         param.fp_check_projid = 1;
4410                         break;
4411                 case 's':
4412                         if (optarg[0] == '+') {
4413                                 param.fp_size_sign = -1;
4414                                 optarg++;
4415                         } else if (optarg[0] == '-') {
4416                                 param.fp_size_sign =  1;
4417                                 optarg++;
4418                         }
4419
4420                         ret = llapi_parse_size(optarg, &param.fp_size,
4421                                                &param.fp_size_units, 0);
4422                         if (ret) {
4423                                 fprintf(stderr, "error: bad file size '%s'\n",
4424                                         optarg);
4425                                 goto err;
4426                         }
4427                         param.fp_check_size = 1;
4428                         param.fp_exclude_size = !!neg_opt;
4429                         break;
4430                 case 'S':
4431                         if (optarg[0] == '+') {
4432                                 param.fp_stripe_size_sign = -1;
4433                                 optarg++;
4434                         } else if (optarg[0] == '-') {
4435                                 param.fp_stripe_size_sign =  1;
4436                                 optarg++;
4437                         }
4438
4439                         ret = llapi_parse_size(optarg, &param.fp_stripe_size,
4440                                                &param.fp_stripe_size_units, 0);
4441                         if (ret) {
4442                                 fprintf(stderr, "error: bad stripe_size '%s'\n",
4443                                         optarg);
4444                                 goto err;
4445                         }
4446                         param.fp_check_stripe_size = 1;
4447                         param.fp_exclude_stripe_size = !!neg_opt;
4448                         break;
4449                 case 't':
4450                         param.fp_exclude_type = !!neg_opt;
4451                         switch (optarg[0]) {
4452                         case 'b':
4453                                 param.fp_type = S_IFBLK;
4454                                 break;
4455                         case 'c':
4456                                 param.fp_type = S_IFCHR;
4457                                 break;
4458                         case 'd':
4459                                 param.fp_type = S_IFDIR;
4460                                 break;
4461                         case 'f':
4462                                 param.fp_type = S_IFREG;
4463                                 break;
4464                         case 'l':
4465                                 param.fp_type = S_IFLNK;
4466                                 break;
4467                         case 'p':
4468                                 param.fp_type = S_IFIFO;
4469                                 break;
4470                         case 's':
4471                                 param.fp_type = S_IFSOCK;
4472                                 break;
4473                         default:
4474                                 fprintf(stderr, "error: %s: bad type '%s'\n",
4475                                         argv[0], optarg);
4476                                 ret = CMD_HELP;
4477                                 goto err;
4478                         };
4479                         break;
4480                 case 'T':
4481                         if (optarg[0] == '+') {
4482                                 param.fp_mdt_count_sign = -1;
4483                                 optarg++;
4484                         } else if (optarg[0] == '-') {
4485                                 param.fp_mdt_count_sign =  1;
4486                                 optarg++;
4487                         }
4488
4489                         param.fp_mdt_count = strtoul(optarg, &endptr, 0);
4490                         if (*endptr != '\0') {
4491                                 fprintf(stderr, "error: bad mdt_count '%s'\n",
4492                                         optarg);
4493                                 ret = -1;
4494                                 goto err;
4495                         }
4496                         param.fp_check_mdt_count = 1;
4497                         param.fp_exclude_mdt_count = !!neg_opt;
4498                         break;
4499                 case 'z':
4500                         if (optarg[0] == '+') {
4501                                 param.fp_ext_size_sign = -1;
4502                                 optarg++;
4503                         } else if (optarg[0] == '-') {
4504                                 param.fp_ext_size_sign =  1;
4505                                 optarg++;
4506                         }
4507
4508                         ret = llapi_parse_size(optarg, &param.fp_ext_size,
4509                                                &param.fp_ext_size_units, 0);
4510                         if (ret) {
4511                                 fprintf(stderr, "error: bad ext-size '%s'\n",
4512                                         optarg);
4513                                 goto err;
4514                         }
4515                         param.fp_ext_size /= SEL_UNIT_SIZE;
4516                         param.fp_ext_size_units /= SEL_UNIT_SIZE;
4517                         param.fp_check_ext_size = 1;
4518                         param.fp_exclude_ext_size = !!neg_opt;
4519                         break;
4520
4521                 default:
4522                         ret = CMD_HELP;
4523                         goto err;
4524                 };
4525         }
4526
4527         if (pathstart == -1) {
4528                 fprintf(stderr, "error: %s: no filename|pathname\n",
4529                         argv[0]);
4530                 ret = CMD_HELP;
4531                 goto err;
4532         } else if (pathend == -1) {
4533                 /* no options */
4534                 pathend = argc;
4535         }
4536
4537         do {
4538                 rc = llapi_find(argv[pathstart], &param);
4539                 if (rc && !ret) {
4540                         ret = rc;
4541                         pathbad = pathstart;
4542                 }
4543         } while (++pathstart < pathend);
4544
4545         if (ret)
4546                 fprintf(stderr, "%s: failed for '%s': %s\n",
4547                         progname, argv[pathbad], strerror(-rc));
4548
4549 err:
4550         if (param.fp_obd_uuid && param.fp_num_alloc_obds)
4551                 free(param.fp_obd_uuid);
4552
4553         if (param.fp_mdt_uuid && param.fp_num_alloc_mdts)
4554                 free(param.fp_mdt_uuid);
4555
4556         return ret;
4557 }
4558
4559 static int lfs_getstripe_internal(int argc, char **argv,
4560                                   struct find_param *param)
4561 {
4562         struct option long_opts[] = {
4563 /* find { .val = 'A',   .name = "atime",        .has_arg = required_argument }*/
4564 /* find { .val = 'b',   .name = "blocks",       .has_arg = required_argument }*/
4565         { .val = LFS_COMP_COUNT_OPT,
4566                         .name = "comp-count",   .has_arg = no_argument },
4567         { .val = LFS_COMP_COUNT_OPT,
4568                 .name = "component-count",      .has_arg = no_argument },
4569         { .val = LFS_COMP_FLAGS_OPT,
4570                         .name = "comp-flags",   .has_arg = optional_argument },
4571         { .val = LFS_COMP_FLAGS_OPT,
4572                 .name = "component-flags",      .has_arg = optional_argument },
4573         { .val = LFS_COMP_START_OPT,
4574                         .name = "comp-start",   .has_arg = optional_argument },
4575         { .val = LFS_COMP_START_OPT,
4576                 .name = "component-start",      .has_arg = optional_argument },
4577         { .val = LFS_MIRROR_INDEX_OPT,
4578                 .name = "mirror-index",         .has_arg = required_argument },
4579         { .val = LFS_MIRROR_ID_OPT,
4580                 .name = "mirror-id",            .has_arg = required_argument },
4581         { .val = 'c',   .name = "stripe-count", .has_arg = no_argument },
4582         { .val = 'c',   .name = "stripe_count", .has_arg = no_argument },
4583 /* find { .val = 'C',   .name = "ctime",        .has_arg = required_argument }*/
4584         { .val = 'd',   .name = "directory",    .has_arg = no_argument },
4585         { .val = 'D',   .name = "default",      .has_arg = no_argument },
4586         { .val = 'E',   .name = "comp-end",     .has_arg = optional_argument },
4587         { .val = 'E',   .name = "component-end", .has_arg = optional_argument },
4588         { .val = 'F',   .name = "fid",          .has_arg = no_argument },
4589         { .val = 'g',   .name = "generation",   .has_arg = no_argument },
4590 /* find { .val = 'G',   .name = "group",        .has_arg = required_argument }*/
4591 /* dirstripe { .val = 'H', .name = "mdt-hash",  .has_arg = required_argument }*/
4592         { .val = 'i',   .name = "stripe-index", .has_arg = no_argument },
4593         { .val = 'i',   .name = "stripe_index", .has_arg = no_argument },
4594         { .val = 'I',   .name = "comp-id",      .has_arg = optional_argument },
4595         { .val = 'I',   .name = "component-id", .has_arg = optional_argument },
4596         { .val = 'L',   .name = "layout",       .has_arg = no_argument },
4597         { .val = 'm',   .name = "mdt",          .has_arg = no_argument },
4598         { .val = 'm',   .name = "mdt-index",    .has_arg = no_argument },
4599         { .val = 'm',   .name = "mdt_index",    .has_arg = no_argument },
4600 /* find { .val = 'M',   .name = "mtime",        .has_arg = required_argument }*/
4601 /* find { .val = 'n',   .name = "name",         .has_arg = required_argument }*/
4602         { .val = 'N',   .name = "mirror-count", .has_arg = no_argument },
4603         { .val = 'O',   .name = "obd",          .has_arg = required_argument },
4604         { .val = 'O',   .name = "ost",          .has_arg = required_argument },
4605         { .val = 'p',   .name = "pool",         .has_arg = no_argument },
4606 /* find { .val = 'P',   .name = "print",        .has_arg = no_argument }, */
4607         { .val = 'q',   .name = "quiet",        .has_arg = no_argument },
4608         { .val = 'r',   .name = "recursive",    .has_arg = no_argument },
4609         { .val = 'R',   .name = "raw",          .has_arg = no_argument },
4610         { .val = 'S',   .name = "stripe-size",  .has_arg = no_argument },
4611         { .val = 'S',   .name = "stripe_size",  .has_arg = no_argument },
4612 /* find { .val = 't',   .name = "type",         .has_arg = required_argument }*/
4613 /* dirstripe { .val = 'T', .name = "mdt-count", .has_arg = required_argument }*/
4614 /* find { .val = 'u',   .name = "uid",          .has_arg = required_argument }*/
4615 /* find { .val = 'U',   .name = "user",         .has_arg = required_argument }*/
4616         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
4617         { .val = 'y',   .name = "yaml",         .has_arg = no_argument },
4618         { .val = 'z',   .name = "extension-size", .has_arg = no_argument },
4619         { .val = 'z',   .name = "ext-size",     .has_arg = no_argument },
4620         { .name = NULL } };
4621         int c, rc;
4622         int neg_opt = 0;
4623         int pathstart = -1, pathend = -1;
4624         int isoption;
4625         char *end, *tmp;
4626
4627         while ((c = getopt_long(argc, argv,
4628                         "-cdDE::FghiI::LmMNoO:pqrRsSvyz",
4629                         long_opts, NULL)) != -1) {
4630                 if (neg_opt)
4631                         --neg_opt;
4632
4633                 /* '!' is part of option */
4634                 isoption = (c != 1) || (strcmp(optarg, "!") == 0);
4635                 if (!isoption && pathend != -1) {
4636                         fprintf(stderr,
4637                                 "error: %s: filename|dirname must either precede options or follow options\n",
4638                                 argv[0]);
4639                         return CMD_HELP;
4640                 }
4641                 if (!isoption && pathstart == -1)
4642                         pathstart = optind - 1;
4643                 if (isoption && pathstart != -1 && pathend == -1)
4644                         pathend = optind - 2;
4645
4646                 switch (c) {
4647                 case 1:
4648                         /* unknown: opt is "!" */
4649                         if (strcmp(optarg, "!") == 0)
4650                                 neg_opt = 2;
4651                         break;
4652                 case 'c':
4653                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
4654                                 param->fp_verbose |= VERBOSE_COUNT;
4655                                 param->fp_max_depth = 0;
4656                         }
4657                         break;
4658                 case LFS_COMP_COUNT_OPT:
4659                         param->fp_verbose |= VERBOSE_COMP_COUNT;
4660                         param->fp_max_depth = 0;
4661                         break;
4662                 case LFS_COMP_FLAGS_OPT:
4663                         if (optarg != NULL) {
4664                                 rc = comp_str2flags(optarg,
4665                                                     &param->fp_comp_flags,
4666                                                     &param->fp_comp_neg_flags);
4667                                 if (rc != 0) {
4668                                         fprintf(stderr, "error: %s bad "
4669                                                 "component flags '%s'.\n",
4670                                                 argv[0], optarg);
4671                                         return CMD_HELP;
4672                                 }
4673                                 param->fp_check_comp_flags = 1;
4674                         } else {
4675                                 param->fp_verbose |= VERBOSE_COMP_FLAGS;
4676                                 param->fp_max_depth = 0;
4677                         }
4678                         break;
4679                 case LFS_COMP_START_OPT:
4680                         if (optarg != NULL) {
4681                                 tmp = optarg;
4682                                 if (tmp[0] == '+') {
4683                                         param->fp_comp_start_sign = -1;
4684                                         tmp++;
4685                                 } else if (tmp[0] == '-') {
4686                                         param->fp_comp_start_sign = 1;
4687                                         tmp++;
4688                                 }
4689                                 rc = llapi_parse_size(tmp,
4690                                                 &param->fp_comp_start,
4691                                                 &param->fp_comp_start_units, 0);
4692                                 if (rc != 0) {
4693                                         fprintf(stderr, "error: %s bad "
4694                                                 "component start '%s'.\n",
4695                                                 argv[0], tmp);
4696                                         return CMD_HELP;
4697                                 } else {
4698                                         param->fp_check_comp_start = 1;
4699                                 }
4700                         } else {
4701                                 param->fp_verbose |= VERBOSE_COMP_START;
4702                                 param->fp_max_depth = 0;
4703                         }
4704                         break;
4705                 case LFS_MIRROR_INDEX_OPT:
4706                         if (optarg[0] == '+') {
4707                                 param->fp_mirror_index_sign = -1;
4708                                 optarg++;
4709                         } else if (optarg[0] == '-') {
4710                                 param->fp_mirror_index_sign = 1;
4711                                 optarg++;
4712                         }
4713
4714                         param->fp_mirror_index = strtoul(optarg, &end, 0);
4715                         if (*end != '\0' || (param->fp_mirror_index == 0 &&
4716                             param->fp_mirror_index_sign == 0 && neg_opt == 0)) {
4717                                 fprintf(stderr,
4718                                         "%s %s: invalid mirror index '%s'\n",
4719                                         progname, argv[0], optarg);
4720                                 return CMD_HELP;
4721                         }
4722                         if (param->fp_mirror_id != 0) {
4723                                 fprintf(stderr,
4724                                         "%s %s: can't specify both mirror index and mirror ID\n",
4725                                         progname, argv[0]);
4726                                 return CMD_HELP;
4727                         }
4728                         param->fp_check_mirror_index = 1;
4729                         param->fp_exclude_mirror_index = !!neg_opt;
4730                         break;
4731                 case LFS_MIRROR_ID_OPT:
4732                         if (optarg[0] == '+') {
4733                                 param->fp_mirror_id_sign = -1;
4734                                 optarg++;
4735                         } else if (optarg[0] == '-') {
4736                                 param->fp_mirror_id_sign = 1;
4737                                 optarg++;
4738                         }
4739
4740                         param->fp_mirror_id = strtoul(optarg, &end, 0);
4741                         if (*end != '\0' || (param->fp_mirror_id == 0 &&
4742                             param->fp_mirror_id_sign == 0 && neg_opt == 0)) {
4743                                 fprintf(stderr,
4744                                         "%s %s: invalid mirror ID '%s'\n",
4745                                         progname, argv[0], optarg);
4746                                 return CMD_HELP;
4747                         }
4748                         if (param->fp_mirror_index != 0) {
4749                                 fprintf(stderr,
4750                                         "%s %s: can't specify both mirror index and mirror ID\n",
4751                                         progname, argv[0]);
4752                                 return CMD_HELP;
4753                         }
4754                         param->fp_check_mirror_id = 1;
4755                         param->fp_exclude_mirror_id = !!neg_opt;
4756                         break;
4757                 case 'd':
4758                         param->fp_max_depth = 0;
4759                         break;
4760                 case 'D':
4761                         param->fp_get_default_lmv = 1;
4762                         break;
4763                 case 'E':
4764                         if (optarg != NULL) {
4765                                 tmp = optarg;
4766                                 if (tmp[0] == '+') {
4767                                         param->fp_comp_end_sign = -1;
4768                                         tmp++;
4769                                 } else if (tmp[0] == '-') {
4770                                         param->fp_comp_end_sign = 1;
4771                                         tmp++;
4772                                 }
4773
4774                                 if (arg_is_eof(tmp)) {
4775                                         param->fp_comp_end = LUSTRE_EOF;
4776                                         param->fp_comp_end_units = 1;
4777                                         rc = 0;
4778                                 } else {
4779                                         rc = llapi_parse_size(tmp,
4780                                                 &param->fp_comp_end,
4781                                                 &param->fp_comp_end_units, 0);
4782                                 }
4783                                 if (rc != 0) {
4784                                         fprintf(stderr, "error: %s bad "
4785                                                 "component end '%s'.\n",
4786                                                 argv[0], tmp);
4787                                         return CMD_HELP;
4788                                 }
4789                                 param->fp_check_comp_end = 1;
4790                         } else {
4791                                 param->fp_verbose |= VERBOSE_COMP_END;
4792                                 param->fp_max_depth = 0;
4793                         }
4794                         break;
4795                 case 'F':
4796                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
4797                                 param->fp_verbose |= VERBOSE_DFID;
4798                                 param->fp_max_depth = 0;
4799                         }
4800                         break;
4801                 case 'g':
4802                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
4803                                 param->fp_verbose |= VERBOSE_GENERATION;
4804                                 param->fp_max_depth = 0;
4805                         }
4806                         break;
4807                 case 'i':
4808                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
4809                                 param->fp_verbose |= VERBOSE_STRIPE_OFFSET;
4810                                 param->fp_max_depth = 0;
4811                         }
4812                         break;
4813                 case 'I':
4814                         if (optarg != NULL) {
4815                                 param->fp_comp_id = strtoul(optarg, &end, 0);
4816                                 if (*end != '\0' || param->fp_comp_id == 0 ||
4817                                     param->fp_comp_id > LCME_ID_MAX) {
4818                                         fprintf(stderr, "error: %s bad "
4819                                                 "component id '%s'\n",
4820                                                 argv[0], optarg);
4821                                         return CMD_HELP;
4822                                 } else {
4823                                         param->fp_check_comp_id = 1;
4824                                 }
4825                         } else {
4826                                 param->fp_max_depth = 0;
4827                                 param->fp_verbose |= VERBOSE_COMP_ID;
4828                         }
4829                         break;
4830                 case 'L':
4831                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
4832                                 param->fp_verbose |= VERBOSE_PATTERN;
4833                                 param->fp_max_depth = 0;
4834                         }
4835                         break;
4836 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
4837                 case 'M':
4838                         fprintf(stderr, "warning: '-M' deprecated"
4839                                 ", use '--mdt-index' or '-m' instead\n");
4840 #endif
4841                 case 'm':
4842                         if (!(param->fp_verbose & VERBOSE_DETAIL))
4843                                 param->fp_max_depth = 0;
4844                         param->fp_verbose |= VERBOSE_MDTINDEX;
4845                         break;
4846                 case 'N':
4847                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
4848                                 param->fp_verbose |= VERBOSE_MIRROR_COUNT;
4849                                 param->fp_max_depth = 0;
4850                         }
4851                         break;
4852                 case 'O':
4853                         if (param->fp_obd_uuid) {
4854                                 fprintf(stderr,
4855                                         "error: %s: only one obduuid allowed",
4856                                         argv[0]);
4857                                 return CMD_HELP;
4858                         }
4859                         param->fp_obd_uuid = (struct obd_uuid *)optarg;
4860                         break;
4861                 case 'p':
4862                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
4863                                 param->fp_verbose |= VERBOSE_POOL;
4864                                 param->fp_max_depth = 0;
4865                         }
4866                         break;
4867                 case 'q':
4868                         param->fp_quiet++;
4869                         break;
4870                 case 'r':
4871                         param->fp_recursive = 1;
4872                         break;
4873                 case 'R':
4874                         param->fp_raw = 1;
4875                         break;
4876                 case 'S':
4877                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
4878                                 param->fp_verbose |= VERBOSE_STRIPE_SIZE;
4879                                 param->fp_max_depth = 0;
4880                         }
4881                         break;
4882                 case 'v':
4883                         param->fp_verbose = VERBOSE_DEFAULT | VERBOSE_DETAIL;
4884                         break;
4885                 case 'y':
4886                         param->fp_yaml = 1;
4887                         break;
4888                 case 'z':
4889                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
4890                                 param->fp_verbose |= VERBOSE_EXT_SIZE;
4891                                 param->fp_max_depth = 0;
4892                         }
4893                         break;
4894                 default:
4895                         return CMD_HELP;
4896                 }
4897         }
4898
4899         if (pathstart == -1) {
4900                 fprintf(stderr, "error: %s: no filename|pathname\n",
4901                                 argv[0]);
4902                 return CMD_HELP;
4903         } else if (pathend == -1) {
4904                 /* no options */
4905                 pathend = argc;
4906         }
4907
4908         if (pathend > argc)
4909                 return CMD_HELP;
4910
4911         if (param->fp_recursive)
4912                 param->fp_max_depth = -1;
4913         else if (param->fp_verbose & VERBOSE_DETAIL)
4914                 param->fp_max_depth = 1;
4915
4916         if (!param->fp_verbose)
4917                 param->fp_verbose = VERBOSE_DEFAULT;
4918         if (param->fp_quiet)
4919                 param->fp_verbose = VERBOSE_OBJID;
4920
4921         do {
4922                 rc = llapi_getstripe(argv[pathstart], param);
4923         } while (++pathstart < pathend && !rc);
4924
4925         if (rc)
4926                 fprintf(stderr, "error: %s failed for %s.\n",
4927                         argv[0], argv[optind - 1]);
4928         return rc;
4929 }
4930
4931 static int lfs_tgts(int argc, char **argv)
4932 {
4933         char mntdir[PATH_MAX] = {'\0'}, path[PATH_MAX] = {'\0'};
4934         struct find_param param;
4935         int index = 0, rc=0;
4936
4937         if (argc > 2)
4938                 return CMD_HELP;
4939
4940         if (argc == 2 && !realpath(argv[1], path)) {
4941                 rc = -errno;
4942                 fprintf(stderr, "error: invalid path '%s': %s\n",
4943                         argv[1], strerror(-rc));
4944                 return rc;
4945         }
4946
4947         while (!llapi_search_mounts(path, index++, mntdir, NULL)) {
4948                 /* Check if we have a mount point */
4949                 if (mntdir[0] == '\0')
4950                         continue;
4951
4952                 memset(&param, 0, sizeof(param));
4953                 if (!strcmp(argv[0], "mdts"))
4954                         param.fp_get_lmv = 1;
4955
4956                 rc = llapi_ostlist(mntdir, &param);
4957                 if (rc) {
4958                         fprintf(stderr, "error: %s: failed on %s\n",
4959                                 argv[0], mntdir);
4960                 }
4961                 if (path[0] != '\0')
4962                         break;
4963                 memset(mntdir, 0, PATH_MAX);
4964         }
4965
4966         return rc;
4967 }
4968
4969 static int lfs_getstripe(int argc, char **argv)
4970 {
4971         struct find_param param = { 0 };
4972
4973         param.fp_max_depth = 1;
4974         return lfs_getstripe_internal(argc, argv, &param);
4975 }
4976
4977 /* functions */
4978 static int lfs_getdirstripe(int argc, char **argv)
4979 {
4980         struct find_param param = { 0 };
4981         struct option long_opts[] = {
4982         { .val = 'c',   .name = "mdt-count",    .has_arg = no_argument },
4983         { .val = 'D',   .name = "default",      .has_arg = no_argument },
4984         { .val = 'H',   .name = "mdt-hash",     .has_arg = no_argument },
4985         { .val = 'i',   .name = "mdt-index",    .has_arg = no_argument },
4986         { .val = 'm',   .name = "mdt-index",    .has_arg = no_argument },
4987         { .val = 'O',   .name = "obd",          .has_arg = required_argument },
4988         { .val = 'r',   .name = "recursive",    .has_arg = no_argument },
4989         { .val = 'T',   .name = "mdt-count",    .has_arg = no_argument },
4990         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
4991         { .val = 'y',   .name = "yaml",         .has_arg = no_argument },
4992         { .name = NULL } };
4993         int c, rc;
4994
4995         param.fp_get_lmv = 1;
4996
4997         while ((c = getopt_long(argc, argv,
4998                                 "cDHimO:rtTvy", long_opts, NULL)) != -1)
4999         {
5000                 switch (c) {
5001                 case 'c':
5002                 case 'T':
5003                         param.fp_verbose |= VERBOSE_COUNT;
5004                         break;
5005                 case 'D':
5006                         param.fp_get_default_lmv = 1;
5007                         break;
5008                 case 'i':
5009                 case 'm':
5010                         param.fp_verbose |= VERBOSE_STRIPE_OFFSET;
5011                         break;
5012 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
5013                 case 't':
5014                         fprintf(stderr, "warning: '-t' deprecated, "
5015                                 "use '--mdt-hash' or '-H' instead\n");
5016 #endif
5017                 case 'H':
5018                         param.fp_verbose |= VERBOSE_HASH_TYPE;
5019                         break;
5020                 case 'O':
5021                         if (param.fp_obd_uuid) {
5022                                 fprintf(stderr,
5023                                         "error: %s: only one obduuid allowed",
5024                                         argv[0]);
5025                                 return CMD_HELP;
5026                         }
5027                         param.fp_obd_uuid = (struct obd_uuid *)optarg;
5028                         break;
5029                 case 'r':
5030                         param.fp_recursive = 1;
5031                         break;
5032                 case 'v':
5033                         param.fp_verbose |= VERBOSE_DETAIL;
5034                         break;
5035                 case 'y':
5036                         param.fp_yaml = 1;
5037                         break;
5038                 default:
5039                         fprintf(stderr, "%s %s: unrecognized option '%s'\n",
5040                                 progname, argv[0], argv[optind - 1]);
5041                         return CMD_HELP;
5042                 }
5043         }
5044
5045         if (optind >= argc)
5046                 return CMD_HELP;
5047
5048         if (param.fp_recursive)
5049                 param.fp_max_depth = -1;
5050
5051         if (!param.fp_verbose)
5052                 param.fp_verbose = VERBOSE_DEFAULT;
5053
5054         do {
5055                 rc = llapi_getstripe(argv[optind], &param);
5056         } while (++optind < argc && !rc);
5057
5058         if (rc)
5059                 fprintf(stderr, "error: %s failed for %s.\n",
5060                         argv[0], argv[optind - 1]);
5061         return rc;
5062 }
5063
5064 enum mntdf_flags {
5065         MNTDF_INODES    = 0x0001,
5066         MNTDF_COOKED    = 0x0002,
5067         MNTDF_LAZY      = 0x0004,
5068         MNTDF_VERBOSE   = 0x0008,
5069         MNTDF_SHOW      = 0x0010,
5070 };
5071
5072 #define COOK(value)                                             \
5073 ({                                                              \
5074         int radix = 0;                                          \
5075         while (value > 1024) {                                  \
5076                 value /= 1024;                                  \
5077                 radix++;                                        \
5078         }                                                       \
5079         radix;                                                  \
5080 })
5081 #define UUF     "%-20s"
5082 #define CSF     "%11s"
5083 #define CDF     "%11llu"
5084 #define HDF     "%8.1f%c"
5085 #define RSF     "%4s"
5086 #define RDF     "%3d%%"
5087
5088 static inline int obd_statfs_ratio(const struct obd_statfs *st, bool inodes)
5089 {
5090         double avail, used, ratio = 0;
5091
5092         if (inodes) {
5093                 avail = st->os_ffree;
5094                 used = st->os_files - st->os_ffree;
5095         } else {
5096                 avail = st->os_bavail;
5097                 used = st->os_blocks - st->os_bfree;
5098         }
5099         if (avail + used > 0)
5100                 ratio = used / (used + avail) * 100;
5101
5102         /* Round up to match df(1) usage percentage */
5103         return (ratio - (int)ratio) > 0 ? (int)(ratio + 1) : (int)ratio;
5104 }
5105
5106 /* This is to identify various problem states for "lfs df" if .osn_err = true,
5107  * so only show flags reflecting those states by default. Informational states
5108  * are only shown with "-v" and use lower-case names to distinguish them.
5109  * UNUSED[12] were for "EROFS = 30" until 1.6 but are now available for use.
5110  */
5111 static struct obd_statfs_state_names {
5112         enum obd_statfs_state   osn_state;
5113         const char              osn_name;
5114         bool                    osn_err;
5115 } oss_names[] = {
5116         { .osn_state = OS_STATE_DEGRADED,    .osn_name = 'D', .osn_err = true },
5117         { .osn_state = OS_STATE_READONLY,    .osn_name = 'R', .osn_err = true },
5118         { .osn_state = OS_STATE_NOPRECREATE, .osn_name = 'N', .osn_err = true },
5119         { .osn_state = OS_STATE_UNUSED1,     .osn_name = '?', .osn_err = true },
5120         { .osn_state = OS_STATE_UNUSED2,     .osn_name = '?', .osn_err = true },
5121         { .osn_state = OS_STATE_ENOSPC,      .osn_name = 'S', .osn_err = true },
5122         { .osn_state = OS_STATE_ENOINO,      .osn_name = 'I', .osn_err = true },
5123         { .osn_state = OS_STATE_SUM,         .osn_name = 'a', /* aggregate */ },
5124         { .osn_state = OS_STATE_NONROT,      .osn_name = 'f', /* flash */     },
5125 };
5126
5127 static int showdf(char *mntdir, struct obd_statfs *stat,
5128                   char *uuid, enum mntdf_flags flags,
5129                   char *type, int index, int rc)
5130 {
5131         long long avail, used, total;
5132         int ratio = 0;
5133         char *suffix = "KMGTPEZY";
5134         /* Note if we have >2^64 bytes/fs these buffers will need to be grown */
5135         char tbuf[3 * sizeof(__u64)];
5136         char ubuf[3 * sizeof(__u64)];
5137         char abuf[3 * sizeof(__u64)];
5138         char rbuf[3 * sizeof(__u64)];
5139
5140         if (!uuid || !stat)
5141                 return -EINVAL;
5142
5143         switch (rc) {
5144         case 0:
5145                 if (flags & MNTDF_INODES) {
5146                         avail = stat->os_ffree;
5147                         used = stat->os_files - stat->os_ffree;
5148                         total = stat->os_files;
5149                 } else {
5150                         int shift = flags & MNTDF_COOKED ? 0 : 10;
5151
5152                         avail = (stat->os_bavail * stat->os_bsize) >> shift;
5153                         used  = ((stat->os_blocks - stat->os_bfree) *
5154                                  stat->os_bsize) >> shift;
5155                         total = (stat->os_blocks * stat->os_bsize) >> shift;
5156                 }
5157
5158                 ratio = obd_statfs_ratio(stat, flags & MNTDF_INODES);
5159
5160                 if (flags & MNTDF_COOKED) {
5161                         int i;
5162                         double cook_val;
5163
5164                         cook_val = (double)total;
5165                         i = COOK(cook_val);
5166                         if (i > 0)
5167                                 snprintf(tbuf, sizeof(tbuf), HDF, cook_val,
5168                                          suffix[i - 1]);
5169                         else
5170                                 snprintf(tbuf, sizeof(tbuf), CDF, total);
5171
5172                         cook_val = (double)used;
5173                         i = COOK(cook_val);
5174                         if (i > 0)
5175                                 snprintf(ubuf, sizeof(ubuf), HDF, cook_val,
5176                                          suffix[i - 1]);
5177                         else
5178                                 snprintf(ubuf, sizeof(ubuf), CDF, used);
5179
5180                         cook_val = (double)avail;
5181                         i = COOK(cook_val);
5182                         if (i > 0)
5183                                 snprintf(abuf, sizeof(abuf), HDF, cook_val,
5184                                          suffix[i - 1]);
5185                         else
5186                                 snprintf(abuf, sizeof(abuf), CDF, avail);
5187                 } else {
5188                         snprintf(tbuf, sizeof(tbuf), CDF, total);
5189                         snprintf(ubuf, sizeof(tbuf), CDF, used);
5190                         snprintf(abuf, sizeof(tbuf), CDF, avail);
5191                 }
5192
5193                 sprintf(rbuf, RDF, ratio);
5194                 printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s",
5195                        uuid, tbuf, ubuf, abuf, rbuf, mntdir);
5196                 if (type)
5197                         printf("[%s:%d]", type, index);
5198
5199                 if (stat->os_state) {
5200                         uint32_t i;
5201
5202                         printf(" ");
5203                         for (i = 0; i < ARRAY_SIZE(oss_names); i++) {
5204                                 if (oss_names[i].osn_state & stat->os_state &&
5205                                     (oss_names[i].osn_err ||
5206                                      flags & MNTDF_VERBOSE))
5207                                         printf("%c", oss_names[i].osn_name);
5208                         }
5209                 }
5210
5211                 printf("\n");
5212                 break;
5213         case -ENODATA:
5214                 printf(UUF": inactive device\n", uuid);
5215                 break;
5216         default:
5217                 printf(UUF": %s\n", uuid, strerror(-rc));
5218                 break;
5219         }
5220
5221         return 0;
5222 }
5223
5224 struct ll_stat_type {
5225         int   st_op;
5226         char *st_name;
5227 };
5228
5229 #define LL_STATFS_MAX   LOV_MAX_STRIPE_COUNT
5230
5231 struct ll_statfs_data {
5232         int                     sd_index;
5233         struct obd_statfs       sd_st;
5234 };
5235
5236 struct ll_statfs_buf {
5237         int                     sb_count;
5238         struct ll_statfs_data   sb_buf[LL_STATFS_MAX];
5239 };
5240
5241 static int mntdf(char *mntdir, char *fsname, char *pool, enum mntdf_flags flags,
5242                  int ops, struct ll_statfs_buf *lsb)
5243 {
5244         struct obd_statfs stat_buf, sum = { .os_bsize = 1 };
5245         struct obd_uuid uuid_buf;
5246         char *poolname = NULL;
5247         struct ll_stat_type types[] = {
5248                 { .st_op = LL_STATFS_LMV,       .st_name = "MDT" },
5249                 { .st_op = LL_STATFS_LOV,       .st_name = "OST" },
5250                 { .st_name = NULL } };
5251         struct ll_stat_type *tp;
5252         __u64 ost_files = 0;
5253         __u64 ost_ffree = 0;
5254         __u32 index;
5255         __u32 type;
5256         int fd;
5257         int rc = 0;
5258         int rc2;
5259
5260         if (pool) {
5261                 poolname = strchr(pool, '.');
5262                 if (poolname != NULL) {
5263                         if (strncmp(fsname, pool, strlen(fsname))) {
5264                                 fprintf(stderr, "filesystem name incorrect\n");
5265                                 return -ENODEV;
5266                         }
5267                         poolname++;
5268                 } else
5269                         poolname = pool;
5270         }
5271
5272         fd = open(mntdir, O_RDONLY);
5273         if (fd < 0) {
5274                 rc = -errno;
5275                 fprintf(stderr, "%s: cannot open '%s': %s\n", progname, mntdir,
5276                         strerror(errno));
5277                 return rc;
5278         }
5279
5280         if (flags & MNTDF_SHOW) {
5281                 if (flags & MNTDF_INODES)
5282                         printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s\n",
5283                                "UUID", "Inodes", "IUsed", "IFree",
5284                                "IUse%", "Mounted on");
5285                 else
5286                         printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s\n",
5287                                "UUID",
5288                                flags & MNTDF_COOKED ? "bytes" : "1K-blocks",
5289                                "Used", "Available", "Use%", "Mounted on");
5290         }
5291
5292         for (tp = types; tp->st_name != NULL; tp++) {
5293                 bool have_ost = false;
5294
5295                 if (!(tp->st_op & ops))
5296                         continue;
5297
5298                 for (index = 0; ; index++) {
5299                         memset(&stat_buf, 0, sizeof(struct obd_statfs));
5300                         memset(&uuid_buf, 0, sizeof(struct obd_uuid));
5301                         type = flags & MNTDF_LAZY ?
5302                                 tp->st_op | LL_STATFS_NODELAY : tp->st_op;
5303                         rc2 = llapi_obd_fstatfs(fd, type, index,
5304                                                &stat_buf, &uuid_buf);
5305                         if (rc2 == -ENODEV)
5306                                 break;
5307                         if (rc2 == -EAGAIN)
5308                                 continue;
5309                         if (rc2 == -ENODATA) { /* Inactive device, OK. */
5310                                 if (!(flags & MNTDF_VERBOSE))
5311                                         continue;
5312                         } else if (rc2 < 0 && rc == 0) {
5313                                 rc = rc2;
5314                         }
5315
5316                         /* If we have OSTs then don't report MDT block counts.
5317                          * For MDT-only filesystems the expectation is that all
5318                          * layouts have a DoM component.  For filesystems with
5319                          * OSTs, files are not necessarily going to store data
5320                          * on MDTs, and MDT space is limited to a fraction of
5321                          * OST space, so don't include it in the summary.
5322                          */
5323                         if (tp->st_op == LL_STATFS_LOV && !have_ost) {
5324                                 have_ost = true;
5325                                 sum.os_blocks = 0;
5326                                 sum.os_bfree = 0;
5327                                 sum.os_bavail = 0;
5328                         }
5329
5330                         if (poolname && tp->st_op == LL_STATFS_LOV &&
5331                             llapi_search_ost(fsname, poolname,
5332                                              obd_uuid2str(&uuid_buf)) != 1)
5333                                 continue;
5334
5335                         /* the llapi_obd_statfs() call may have returned with
5336                          * an error, but if it filled in uuid_buf we will at
5337                          * lease use that to print out a message for that OBD.
5338                          * If we didn't get anything in the uuid_buf, then fill
5339                          * it in so that we can print an error message. */
5340                         if (uuid_buf.uuid[0] == '\0')
5341                                 snprintf(uuid_buf.uuid, sizeof(uuid_buf.uuid),
5342                                          "%s%04x", tp->st_name, index);
5343                         if (!rc && lsb) {
5344                                 lsb->sb_buf[lsb->sb_count].sd_index = index;
5345                                 lsb->sb_buf[lsb->sb_count].sd_st = stat_buf;
5346                                 lsb->sb_count++;
5347                         }
5348                         if (flags & MNTDF_SHOW)
5349                                 showdf(mntdir, &stat_buf,
5350                                        obd_uuid2str(&uuid_buf), flags,
5351                                        tp->st_name, index, rc2);
5352
5353                         if (rc2)
5354                                 continue;
5355
5356                         if (tp->st_op == LL_STATFS_LMV) {
5357                                 sum.os_ffree += stat_buf.os_ffree;
5358                                 sum.os_files += stat_buf.os_files;
5359                         } else /* if (tp->st_op == LL_STATFS_LOV) */ {
5360                                 ost_files += stat_buf.os_files;
5361                                 ost_ffree += stat_buf.os_ffree;
5362                         }
5363                         sum.os_blocks += stat_buf.os_blocks *
5364                                          stat_buf.os_bsize;
5365                         sum.os_bfree  += stat_buf.os_bfree *
5366                                          stat_buf.os_bsize;
5367                         sum.os_bavail += stat_buf.os_bavail *
5368                                          stat_buf.os_bsize;
5369                 }
5370         }
5371
5372         close(fd);
5373
5374         /* If we have _some_ OSTs, but don't have as many free objects on the
5375          * OST as inodes on the MDTs, reduce the reported number of inodes
5376          * to compensate, so that the "inodes in use" number is correct.
5377          * This should be kept in sync with ll_statfs_internal().
5378          */
5379         if (ost_files && ost_ffree < sum.os_ffree) {
5380                 sum.os_files = (sum.os_files - sum.os_ffree) + ost_ffree;
5381                 sum.os_ffree = ost_ffree;
5382         }
5383         if (flags & MNTDF_SHOW) {
5384                 printf("\n");
5385                 showdf(mntdir, &sum, "filesystem_summary:", flags, NULL, 0, 0);
5386                 printf("\n");
5387         }
5388
5389         return rc;
5390 }
5391
5392 static int ll_statfs_data_comp(const void *sd1, const void *sd2)
5393 {
5394         const struct obd_statfs *st1 = &((const struct ll_statfs_data *)sd1)->
5395                                                 sd_st;
5396         const struct obd_statfs *st2 = &((const struct ll_statfs_data *)sd2)->
5397                                                 sd_st;
5398         int r1 = obd_statfs_ratio(st1, false);
5399         int r2 = obd_statfs_ratio(st2, false);
5400         int64_t result = r1 - r2;
5401
5402         /* if both space usage are above 90, compare free inodes */
5403         if (r1 > 90 && r2 > 90)
5404                 result = st2->os_ffree - st1->os_ffree;
5405
5406         if (result < 0)
5407                 return -1;
5408         else if (result == 0)
5409                 return 0;
5410         else
5411                 return 1;
5412 }
5413
5414 /* functions */
5415 static int lfs_setdirstripe(int argc, char **argv)
5416 {
5417         char *dname;
5418         struct lfs_setstripe_args lsa = { 0 };
5419         struct llapi_stripe_param *param = NULL;
5420         __u32 mdts[LMV_MAX_STRIPE_COUNT] = { 0 };
5421         char *end;
5422         int c;
5423         char *mode_opt = NULL;
5424         bool default_stripe = false;
5425         bool delete = false;
5426         bool auto_distributed = false;
5427         bool foreign_mode = false;
5428         mode_t mode = S_IRWXU | S_IRWXG | S_IRWXO;
5429         mode_t previous_mode = 0;
5430         struct ll_statfs_buf *lsb = NULL;
5431         char mntdir[PATH_MAX] = "";
5432         char *xattr = NULL;
5433         __u32 type = LU_FOREIGN_TYPE_DAOS, flags = 0;
5434         struct option long_opts[] = {
5435         { .val = 'c',   .name = "count",        .has_arg = required_argument },
5436         { .val = 'c',   .name = "mdt-count",    .has_arg = required_argument },
5437         { .val = 'd',   .name = "delete",       .has_arg = no_argument },
5438         { .val = 'D',   .name = "default",      .has_arg = no_argument },
5439         { .val = 'D',   .name = "default_stripe", .has_arg = no_argument },
5440         { .val = LFS_LAYOUT_FLAGS_OPT,
5441                         .name = "flags",        .has_arg = required_argument },
5442         { .val = LFS_LAYOUT_FOREIGN_OPT,
5443                         .name = "foreign",      .has_arg = optional_argument},
5444         { .val = 'H',   .name = "mdt-hash",     .has_arg = required_argument },
5445 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 17, 53, 0)
5446         { .val = 'i',   .name = "mdt-index",    .has_arg = required_argument },
5447         { .val = 'i',   .name = "mdt",          .has_arg = required_argument },
5448 #else
5449         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument },
5450         { .val = 'm',   .name = "mdt",          .has_arg = required_argument },
5451 #endif
5452 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
5453         { .val = 'i',   .name = "index",        .has_arg = required_argument },
5454 #endif
5455         { .val = 'o',   .name = "mode",         .has_arg = required_argument },
5456 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
5457         { .val = 't',   .name = "hash-type",    .has_arg = required_argument },
5458 #endif
5459         { .val = 'T',   .name = "mdt-count",    .has_arg = required_argument },
5460 /* setstripe { .val = 'y', .name = "yaml",      .has_arg = no_argument }, */
5461         { .val = 'x',   .name = "xattr",        .has_arg = required_argument },
5462         { .name = NULL } };
5463         int result = 0;
5464
5465         setstripe_args_init(&lsa);
5466
5467         while ((c = getopt_long(argc, argv, "c:dDi:H:m:o:t:T:x:",
5468                                 long_opts, NULL)) >= 0) {
5469                 switch (c) {
5470                 case 0:
5471                         /* Long options. */
5472                         break;
5473                 case 'c':
5474                 case 'T':
5475                         lsa.lsa_stripe_count = strtoul(optarg, &end, 0);
5476                         if (*end != '\0') {
5477                                 fprintf(stderr,
5478                                         "%s %s: invalid stripe count '%s'\n",
5479                                         progname, argv[0], optarg);
5480                                 return CMD_HELP;
5481                         }
5482                         break;
5483                 case 'd':
5484                         delete = true;
5485                         default_stripe = true;
5486                         break;
5487                 case 'D':
5488                         default_stripe = true;
5489                         break;
5490                 case LFS_LAYOUT_FOREIGN_OPT:
5491                         if (optarg != NULL) {
5492                                 /* check pure numeric */
5493                                 type = strtoul(optarg, &end, 0);
5494                                 if (*end) {
5495                                         /* check name */
5496                                         type = check_foreign_type_name(optarg);
5497                                         if (type == LU_FOREIGN_TYPE_UNKNOWN) {
5498                                                 fprintf(stderr,
5499                                                         "%s %s: unknown foreign type '%s'\n",
5500                                                         progname, argv[0],
5501                                                         optarg);
5502                                                 return CMD_HELP;
5503                                         }
5504                                 }
5505                         }
5506                         foreign_mode = true;
5507                         break;
5508                 case LFS_LAYOUT_FLAGS_OPT:
5509                         flags = strtoul(optarg, &end, 16);
5510                         if (*end != '\0') {
5511                                 fprintf(stderr,
5512                                         "%s %s: bad flags '%s'\n",
5513                                         progname, argv[0], optarg);
5514                                 return CMD_HELP;
5515                         }
5516                         break;
5517 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
5518                 case 't':
5519                         fprintf(stderr, "warning: '--hash-type' and '-t' "
5520                               "deprecated, use '--mdt-hash' or '-H' instead\n");
5521 #endif
5522                 case 'H':
5523                         lsa.lsa_pattern = check_hashtype(optarg);
5524                         if (lsa.lsa_pattern == 0) {
5525                                 fprintf(stderr,
5526                                         "%s %s: bad stripe hash type '%s'\n",
5527                                         progname, argv[0], optarg);
5528                                 return CMD_HELP;
5529                         }
5530                         break;
5531                 case 'i':
5532 #if LUSTRE_VERSION_CODE >= OBD_OCD_VERSION(2, 17, 53, 0)
5533                 case 'm':
5534 #endif
5535 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
5536                         if (strcmp(argv[optind - 1], "--index") == 0)
5537                                 fprintf(stderr,
5538                                         "%s %s: warning: '--index' deprecated, use '--mdt-index' instead\n",
5539                                         progname, argv[0]);
5540 #endif
5541                         lsa.lsa_nr_tgts = parse_targets(mdts,
5542                                                 sizeof(mdts) / sizeof(__u32),
5543                                                 lsa.lsa_nr_tgts, optarg, NULL);
5544                         if (lsa.lsa_nr_tgts < 0) {
5545                                 fprintf(stderr,
5546                                         "%s %s: invalid MDT target(s) '%s'\n",
5547                                         progname, argv[0], optarg);
5548                                 return CMD_HELP;
5549                         }
5550
5551                         lsa.lsa_tgts = mdts;
5552                         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
5553                                 lsa.lsa_stripe_off = mdts[0];
5554                         break;
5555 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 15, 53, 0)
5556                 case 'm':
5557                         fprintf(stderr, "warning: '-m' is deprecated, "
5558                                 "use '--mode' or '-o' instead\n");
5559 #endif
5560                 case 'o':
5561                         mode_opt = optarg;
5562                         break;
5563                 case 'x':
5564                         xattr = optarg;
5565                         break;
5566                 default:
5567                         fprintf(stderr, "%s %s: unrecognized option '%s'\n",
5568                                 progname, argv[0], argv[optind - 1]);
5569                         return CMD_HELP;
5570                 }
5571         }
5572
5573         if (optind == argc) {
5574                 fprintf(stderr, "%s %s: DIR must be specified\n",
5575                         progname, argv[0]);
5576                 return CMD_HELP;
5577         }
5578
5579         if (xattr && !foreign_mode) {
5580                 /* only print a warning as this is armless and will be
5581                  * ignored
5582                  */
5583                 fprintf(stderr,
5584                         "%s %s: xattr has been specified for non-foreign layout\n",
5585                         progname, argv[0]);
5586         } else if (foreign_mode && !xattr) {
5587                 fprintf(stderr,
5588                         "%s %s: xattr must be provided in foreign mode\n",
5589                         progname, argv[0]);
5590                 return CMD_HELP;
5591         }
5592
5593         if (foreign_mode && (delete || default_stripe || lsa.lsa_nr_tgts ||
5594             lsa.lsa_tgts || setstripe_args_specified(&lsa))) {
5595                 fprintf(stderr,
5596                         "%s %s: only --xattr/--flags/--mode options are valid with --foreign\n",
5597                         progname, argv[0]);
5598                 return CMD_HELP;
5599         }
5600
5601         if (!delete && lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT &&
5602             lsa.lsa_stripe_count == LLAPI_LAYOUT_DEFAULT && !foreign_mode) {
5603                 fprintf(stderr,
5604                         "%s %s: stripe offset and count must be specified\n",
5605                         progname, argv[0]);
5606                 return CMD_HELP;
5607         }
5608
5609         if (delete &&
5610             (lsa.lsa_stripe_off != LLAPI_LAYOUT_DEFAULT ||
5611              lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT)) {
5612                 fprintf(stderr,
5613                         "%s %s: cannot specify -d with -c or -i options\n",
5614                         progname, argv[0]);
5615                 return CMD_HELP;
5616         }
5617
5618         if (mode_opt != NULL) {
5619                 mode = strtoul(mode_opt, &end, 8);
5620                 if (*end != '\0') {
5621                         fprintf(stderr,
5622                                 "%s %s: bad MODE '%s'\n",
5623                                 progname, argv[0], mode_opt);
5624                         return CMD_HELP;
5625                 }
5626                 previous_mode = umask(0);
5627         }
5628
5629         /* foreign LMV/dir case */
5630         if (foreign_mode) {
5631                 if (argc > optind + 1) {
5632                         fprintf(stderr,
5633                                 "%s %s: cannot specify multiple foreign dirs\n",
5634                                 progname, argv[0]);
5635                         return CMD_HELP;
5636                 }
5637
5638                 dname = argv[optind];
5639                 result = llapi_dir_create_foreign(dname, mode, type, flags,
5640                                                   xattr);
5641                 if (result != 0)
5642                         fprintf(stderr,
5643                                 "%s mkdir: can't create foreign dir '%s': %s\n",
5644                                 progname, dname, strerror(-result));
5645                 return result;
5646         }
5647
5648         /*
5649          * initialize stripe parameters, in case param is converted to specific,
5650          * i.e, 'lfs mkdir -i -1 -c N', always allocate space for lsp_tgts.
5651          */
5652         param = calloc(1, offsetof(typeof(*param),
5653                        lsp_tgts[lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT ?
5654                                 lsa.lsa_stripe_count : lsa.lsa_nr_tgts]));
5655         if (param == NULL) {
5656                 fprintf(stderr,
5657                         "%s %s: cannot allocate memory for parameters: %s\n",
5658                         progname, argv[0], strerror(ENOMEM));
5659                 return CMD_HELP;
5660         }
5661
5662         if (lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT)
5663                 param->lsp_stripe_count = lsa.lsa_stripe_count;
5664         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
5665                 param->lsp_stripe_offset = -1;
5666         else
5667                 param->lsp_stripe_offset = lsa.lsa_stripe_off;
5668         if (lsa.lsa_pattern != LLAPI_LAYOUT_RAID0)
5669                 param->lsp_stripe_pattern = lsa.lsa_pattern;
5670         else
5671                 param->lsp_stripe_pattern = LMV_HASH_TYPE_DEFAULT;
5672         param->lsp_pool = lsa.lsa_pool_name;
5673         param->lsp_is_specific = false;
5674         if (lsa.lsa_nr_tgts > 1) {
5675                 if (lsa.lsa_stripe_count > 0 &&
5676                     lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT &&
5677                     lsa.lsa_stripe_count != lsa.lsa_nr_tgts) {
5678                         fprintf(stderr, "error: %s: stripe count %lld doesn't "
5679                                 "match the number of MDTs: %d\n",
5680                                 argv[0], lsa.lsa_stripe_count, lsa.lsa_nr_tgts);
5681                         free(param);
5682                         return CMD_HELP;
5683                 }
5684
5685                 param->lsp_is_specific = true;
5686                 param->lsp_stripe_count = lsa.lsa_nr_tgts;
5687                 memcpy(param->lsp_tgts, mdts, sizeof(*mdts) * lsa.lsa_nr_tgts);
5688         }
5689
5690         if (!default_stripe && (lsa.lsa_pattern & LMV_HASH_FLAG_SPACE)) {
5691                 fprintf(stderr, "%s %s: can only specify -H space with -D\n",
5692                         progname, argv[0]);
5693                 free(param);
5694                 return CMD_HELP;
5695         }
5696
5697         if (param->lsp_stripe_offset != -1 &&
5698             lsa.lsa_pattern & LMV_HASH_FLAG_SPACE) {
5699                 fprintf(stderr, "%s %s: can only specify -H space with -i -1\n",
5700                         progname, argv[0]);
5701                 free(param);
5702                 return CMD_HELP;
5703         }
5704
5705         dname = argv[optind];
5706         do {
5707                 if (default_stripe) {
5708                         result = llapi_dir_set_default_lmv(dname, param);
5709                         if (result)
5710                                 fprintf(stderr,
5711                                         "%s setdirstripe: cannot set default stripe on dir '%s': %s\n",
5712                                         progname, dname, strerror(-result));
5713                         continue;
5714                 }
5715
5716                 /*
5717                  * if current \a dname isn't under the same \a mntdir as the
5718                  * last one, and the last one was auto-distributed, restore
5719                  * \a param.
5720                  */
5721                 if (mntdir[0] != '\0' &&
5722                     strncmp(dname, mntdir, strlen(mntdir)) &&
5723                     auto_distributed) {
5724                         param->lsp_is_specific = false;
5725                         param->lsp_stripe_offset = -1;
5726                         auto_distributed = false;
5727                 }
5728
5729                 /*
5730                  * TODO: when MDT can allocate object with QoS (LU-9435), below
5731                  * code should be removed, instead we should let LMV to allocate
5732                  * the starting MDT object, and then let LOD allocate other MDT
5733                  * objects.
5734                  */
5735                 if (!param->lsp_is_specific && param->lsp_stripe_offset == -1) {
5736                         char path[PATH_MAX] = "";
5737
5738                         if (!lsb) {
5739                                 lsb = malloc(sizeof(*lsb));
5740                                 if (!lsb) {
5741                                         result = -ENOMEM;
5742                                         break;
5743                                 }
5744                         }
5745                         lsb->sb_count = 0;
5746
5747                         /* use mntdir for dirname() temporarily */
5748                         strncpy(mntdir, dname, sizeof(mntdir) - 1);
5749                         if (!realpath(dirname(mntdir), path)) {
5750                                 result = -errno;
5751                                 fprintf(stderr,
5752                                         "error: invalid path '%s': %s\n",
5753                                         argv[optind], strerror(errno));
5754                                 break;
5755                         }
5756                         mntdir[0] = '\0';
5757
5758                         result = llapi_search_mounts(path, 0, mntdir, NULL);
5759                         if (result < 0 || mntdir[0] == '\0') {
5760                                 fprintf(stderr,
5761                                         "No suitable Lustre mount found\n");
5762                                 break;
5763                         }
5764
5765                         result = mntdf(mntdir, NULL, NULL, 0, LL_STATFS_LMV,
5766                                        lsb);
5767                         if (result < 0)
5768                                 break;
5769
5770                         if (param->lsp_stripe_count > lsb->sb_count) {
5771                                 fprintf(stderr,
5772                                         "error: stripe count %d is too big\n",
5773                                         param->lsp_stripe_count);
5774                                 result = -ERANGE;
5775                                 break;
5776                         }
5777
5778                         qsort(lsb->sb_buf, lsb->sb_count,
5779                               sizeof(struct ll_statfs_data),
5780                               ll_statfs_data_comp);
5781
5782                         auto_distributed = true;
5783                 }
5784
5785                 if (auto_distributed) {
5786                         int r;
5787                         int nr = MAX(param->lsp_stripe_count,
5788                                      lsb->sb_count / 2);
5789
5790                         /* don't use server whose usage is above 90% */
5791                         while (nr != param->lsp_stripe_count &&
5792                                obd_statfs_ratio(&lsb->sb_buf[nr].sd_st, false) >
5793                                90)
5794                                 nr = MAX(param->lsp_stripe_count, nr / 2);
5795
5796                         /* get \a r between [0, nr) */
5797                         r = rand() % nr;
5798
5799                         param->lsp_stripe_offset = lsb->sb_buf[r].sd_index;
5800                         if (param->lsp_stripe_count > 1) {
5801                                 int i = 0;
5802
5803                                 param->lsp_is_specific = true;
5804                                 for (; i < param->lsp_stripe_count; i++)
5805                                         param->lsp_tgts[(i + r) % nr] =
5806                                                 lsb->sb_buf[i].sd_index;
5807                         }
5808                 }
5809
5810                 result = llapi_dir_create(dname, mode, param);
5811                 if (result)
5812                         fprintf(stderr,
5813                                 "%s setdirstripe: cannot create dir '%s': %s\n",
5814                                 progname, dname, strerror(-result));
5815         } while (!result && (dname = argv[++optind]));
5816
5817         if (mode_opt != NULL)
5818                 umask(previous_mode);
5819
5820         free(lsb);
5821         free(param);
5822         return result;
5823 }
5824
5825 /* functions */
5826 static int lfs_rmentry(int argc, char **argv)
5827 {
5828         char *dname;
5829         int   index;
5830         int   result = 0;
5831
5832         if (argc <= 1) {
5833                 fprintf(stderr, "error: %s: missing dirname\n",
5834                         argv[0]);
5835                 return CMD_HELP;
5836         }
5837
5838         index = 1;
5839         dname = argv[index];
5840         while (dname != NULL) {
5841                 result = llapi_direntry_remove(dname);
5842                 if (result) {
5843                         fprintf(stderr, "error: %s: remove dir entry '%s' "
5844                                 "failed\n", argv[0], dname);
5845                         break;
5846                 }
5847                 dname = argv[++index];
5848         }
5849         return result;
5850 }
5851
5852 static int lfs_mv(int argc, char **argv)
5853 {
5854         struct lmv_user_md lmu = { LMV_USER_MAGIC };
5855         struct find_param param = {
5856                 .fp_max_depth = -1,
5857                 .fp_mdt_index = -1,
5858         };
5859         char *end;
5860         int c;
5861         int rc = 0;
5862         struct option long_opts[] = {
5863         { .val = 'm',   .name = "mdt",          .has_arg = required_argument },
5864         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument },
5865         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
5866         { .name = NULL } };
5867
5868         while ((c = getopt_long(argc, argv, "m:M:v", long_opts, NULL)) != -1) {
5869                 switch (c) {
5870 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
5871                 case 'M':
5872                         fprintf(stderr, "warning: '-M' deprecated"
5873                                 ", use '--mdt-index' or '-m' instead\n");
5874 #endif
5875                 case 'm':
5876                         lmu.lum_stripe_offset = strtoul(optarg, &end, 0);
5877                         if (*end != '\0') {
5878                                 fprintf(stderr, "%s mv: bad MDT index '%s'\n",
5879                                         progname, optarg);
5880                                 return CMD_HELP;
5881                         }
5882                         break;
5883                 case 'v':
5884                         param.fp_verbose = VERBOSE_DETAIL;
5885                         break;
5886                 default:
5887                         fprintf(stderr, "%s mv: unrecognized option '%s'\n",
5888                                 progname, argv[optind - 1]);
5889                         return CMD_HELP;
5890                 }
5891         }
5892
5893         if (lmu.lum_stripe_offset == -1) {
5894                 fprintf(stderr, "%s mv: MDT index must be specified\n",
5895                         progname);
5896                 return CMD_HELP;
5897         }
5898
5899         if (optind >= argc) {
5900                 fprintf(stderr, "%s mv: DIR must be specified\n", progname);
5901                 return CMD_HELP;
5902         }
5903
5904
5905         /* initialize migrate mdt parameters */
5906         param.fp_lmv_md = &lmu;
5907         param.fp_migrate = 1;
5908         rc = llapi_migrate_mdt(argv[optind], &param);
5909         if (rc != 0)
5910                 fprintf(stderr, "%s mv: cannot migrate '%s' to MDT%04x: %s\n",
5911                         progname, argv[optind], param.fp_mdt_index,
5912                         strerror(-rc));
5913         return rc;
5914 }
5915
5916 static int lfs_osts(int argc, char **argv)
5917 {
5918         return lfs_tgts(argc, argv);
5919 }
5920
5921 static int lfs_mdts(int argc, char **argv)
5922 {
5923         return lfs_tgts(argc, argv);
5924 }
5925
5926 static int lfs_df(int argc, char **argv)
5927 {
5928         char mntdir[PATH_MAX] = {'\0'}, path[PATH_MAX] = {'\0'};
5929         enum mntdf_flags flags = MNTDF_SHOW;
5930         int ops = LL_STATFS_LMV | LL_STATFS_LOV;
5931         int c, rc = 0, index = 0;
5932         char fsname[PATH_MAX] = "", *pool_name = NULL;
5933         struct option long_opts[] = {
5934         { .val = 'h',   .name = "human-readable",
5935                                                 .has_arg = no_argument },
5936         { .val = 'i',   .name = "inodes",       .has_arg = no_argument },
5937         { .val = 'l',   .name = "lazy",         .has_arg = no_argument },
5938         { .val = 'p',   .name = "pool",         .has_arg = required_argument },
5939         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
5940         { .name = NULL} };
5941
5942         while ((c = getopt_long(argc, argv, "hilp:v", long_opts, NULL)) != -1) {
5943                 switch (c) {
5944                 case 'h':
5945                         flags |= MNTDF_COOKED;
5946                         break;
5947                 case 'i':
5948                         flags |= MNTDF_INODES;
5949                         break;
5950                 case 'l':
5951                         flags |= MNTDF_LAZY;
5952                         break;
5953                 case 'p':
5954                         pool_name = optarg;
5955                         break;
5956                 case 'v':
5957                         flags |= MNTDF_VERBOSE;
5958                         break;
5959                 default:
5960                         return CMD_HELP;
5961                 }
5962         }
5963         if (optind < argc && !realpath(argv[optind], path)) {
5964                 rc = -errno;
5965                 fprintf(stderr, "error: invalid path '%s': %s\n",
5966                         argv[optind], strerror(-rc));
5967                 return rc;
5968         }
5969
5970         while (!llapi_search_mounts(path, index++, mntdir, fsname)) {
5971                 /* Check if we have a mount point */
5972                 if (mntdir[0] == '\0')
5973                         continue;
5974
5975                 rc = mntdf(mntdir, fsname, pool_name, flags, ops, NULL);
5976                 if (rc || path[0] != '\0')
5977                         break;
5978                 fsname[0] = '\0'; /* avoid matching in next loop */
5979                 mntdir[0] = '\0'; /* avoid matching in next loop */
5980         }
5981
5982         return rc;
5983 }
5984
5985 static int print_instance(const char *mntdir, char *fsname, size_t fsnamelen,
5986                           bool opt_instance, bool opt_fsname, bool opt_mntdir)
5987 {
5988         char *buf = fsname;
5989
5990         /* llapi_search_mounts() fills "fsname", but that is not called if
5991          * explicit paths are specified on the command-line
5992          */
5993         if (opt_instance || (opt_fsname && fsname[0] == '\0')) {
5994                 int rc = llapi_getname(mntdir, fsname, fsnamelen);
5995
5996                 if (rc < 0) {
5997                         fprintf(stderr, "cannot get instance for '%s': %s\n",
5998                                 mntdir, strerror(-rc));
5999                         return rc;
6000                 }
6001                 buf = fsname;
6002                 if (!opt_instance) {
6003                         /* print only the fsname name */
6004                         buf = strchr(fsname, '-');
6005                         if (buf)
6006                                 *buf = '\0';
6007                         buf = fsname;
6008                 } else if (!opt_fsname) {
6009                         /* print only the instance name */
6010                         buf = strchr(fsname, '-');
6011                         if (buf)
6012                                 buf++;
6013                         else
6014                                 buf = fsname;
6015                 }
6016         } else if (opt_fsname) {
6017                 /* print only the fsname */
6018                 buf = fsname;
6019         }
6020
6021         printf("%s %s\n", buf, opt_mntdir ? mntdir : "");
6022
6023         return 0;
6024 }
6025
6026 static int lfs_getname(int argc, char **argv)
6027 {
6028         struct option long_opts[] = {
6029         { .val = 'h',   .name = "help",         .has_arg = no_argument },
6030         { .val = 'i',   .name = "instance",     .has_arg = no_argument },
6031         { .val = 'n',   .name = "fsname",       .has_arg = no_argument },
6032         { .name = NULL} };
6033         bool opt_instance = false, opt_fsname = false;
6034         char fsname[PATH_MAX] = "";
6035         int rc = 0, rc2, c;
6036
6037         while ((c = getopt_long(argc, argv, "hin", long_opts, NULL)) != -1) {
6038                 switch (c) {
6039                 case 'i':
6040                         opt_instance = true;
6041                         break;
6042                 case 'n':
6043                         opt_fsname = true;
6044                         break;
6045                 case 'h':
6046                 default:
6047                         return CMD_HELP;
6048                 }
6049         }
6050
6051         /* If neither option is given, print both instance and fsname */
6052         if (!opt_instance && !opt_fsname)
6053                 opt_instance = opt_fsname = true;
6054
6055         if (optind == argc) { /* no paths specified, get all paths. */
6056                 char mntdir[PATH_MAX] = "", path[PATH_MAX] = "";
6057                 int index = 0;
6058
6059                 while (!llapi_search_mounts(path, index++, mntdir, fsname)) {
6060                         rc2 = print_instance(mntdir, fsname, sizeof(fsname),
6061                                              opt_instance, opt_fsname, true);
6062                         if (!rc)
6063                                 rc = rc2;
6064                         path[0] = fsname[0] = mntdir[0] = '\0';
6065                 }
6066         } else { /* paths specified, only attempt to search these. */
6067                 bool opt_mntdir;
6068
6069                 /* if only one path is given, print only requested info */
6070                 opt_mntdir = argc - optind > 1 || (opt_instance == opt_fsname);
6071
6072                 for (; optind < argc; optind++) {
6073                         rc2 = print_instance(argv[optind], fsname,
6074                                              sizeof(fsname), opt_instance,
6075                                              opt_fsname, opt_mntdir);
6076                         if (!rc)
6077                                 rc = rc2;
6078                         fsname[0] = '\0';
6079                 }
6080         }
6081
6082         return rc;
6083 }
6084
6085 static int lfs_check(int argc, char **argv)
6086 {
6087         char mntdir[PATH_MAX] = {'\0'};
6088         int num_types = 1;
6089         char *obd_types[3];
6090         char obd_type1[4];
6091         char obd_type2[4];
6092         char obd_type3[4];
6093         int rc;
6094
6095         if (argc != 2) {
6096                 fprintf(stderr, "%s check: server type must be specified\n",
6097                         progname);
6098                 return CMD_HELP;
6099         }
6100
6101         obd_types[0] = obd_type1;
6102         obd_types[1] = obd_type2;
6103         obd_types[2] = obd_type3;
6104
6105         if (strcmp(argv[1], "osts") == 0) {
6106                 strcpy(obd_types[0], "osc");
6107         } else if (strcmp(argv[1], "mdts") == 0 ||
6108                    strcmp(argv[1], "mds") == 0) {
6109                 strcpy(obd_types[0], "mdc");
6110         } else if (strcmp(argv[1], "mgts") == 0) {
6111                 strcpy(obd_types[0], "mgc");
6112         } else if (strcmp(argv[1], "all") == 0 ||
6113                    strcmp(argv[1], "servers") == 0) {
6114                 num_types = 3;
6115                 strcpy(obd_types[0], "osc");
6116                 strcpy(obd_types[1], "mdc");
6117                 strcpy(obd_types[2], "mgc");
6118         } else {
6119                 fprintf(stderr, "%s check: unrecognized option '%s'\n",
6120                         progname, argv[1]);
6121                 return CMD_HELP;
6122         }
6123
6124         rc = llapi_search_mounts(NULL, 0, mntdir, NULL);
6125         if (rc < 0 || mntdir[0] == '\0') {
6126                 fprintf(stderr,
6127                         "%s check: cannot find mounted Lustre filesystem: %s\n",
6128                         progname, (rc < 0) ? strerror(-rc) : strerror(ENODEV));
6129                 return rc;
6130         }
6131
6132         rc = llapi_target_check(num_types, obd_types, mntdir);
6133         if (rc)
6134                 fprintf(stderr, "%s check: cannot check target '%s': %s\n",
6135                         progname, argv[1], strerror(-rc));
6136
6137         return rc;
6138
6139 }
6140
6141 #ifdef HAVE_SYS_QUOTA_H
6142 #define ARG2INT(nr, str, msg)                                           \
6143 do {                                                                    \
6144         char *endp;                                                     \
6145         nr = strtol(str, &endp, 0);                                     \
6146         if (*endp != '\0') {                                            \
6147                 fprintf(stderr, "%s: bad %s '%s'\n",                    \
6148                         progname, msg, str);                            \
6149                 return CMD_HELP;                                        \
6150         }                                                               \
6151 } while (0)
6152
6153 #define ADD_OVERFLOW(a,b) ((a + b) < a) ? (a = ULONG_MAX) : (a = a + b)
6154
6155 /* Convert format time string "XXwXXdXXhXXmXXs" into seconds value
6156  * returns the value or ULONG_MAX on integer overflow or incorrect format
6157  * Notes:
6158  *        1. the order of specifiers is arbitrary (may be: 5w3s or 3s5w)
6159  *        2. specifiers may be encountered multiple times (2s3s is 5 seconds)
6160  *        3. empty integer value is interpreted as 0
6161  */
6162 static unsigned long str2sec(const char* timestr)
6163 {
6164         const char spec[] = "smhdw";
6165         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
6166         unsigned long val = 0;
6167         char *tail;
6168
6169         if (strpbrk(timestr, spec) == NULL) {
6170                 /* no specifiers inside the time string,
6171                    should treat it as an integer value */
6172                 val = strtoul(timestr, &tail, 10);
6173                 return *tail ? ULONG_MAX : val;
6174         }
6175
6176         /* format string is XXwXXdXXhXXmXXs */
6177         while (*timestr) {
6178                 unsigned long v;
6179                 int ind;
6180                 char* ptr;
6181
6182                 v = strtoul(timestr, &tail, 10);
6183                 if (v == ULONG_MAX || *tail == '\0')
6184                         /* value too large (ULONG_MAX or more)
6185                            or missing specifier */
6186                         goto error;
6187
6188                 ptr = strchr(spec, *tail);
6189                 if (ptr == NULL)
6190                         /* unknown specifier */
6191                         goto error;
6192
6193                 ind = ptr - spec;
6194
6195                 /* check if product will overflow the type */
6196                 if (!(v < ULONG_MAX / mult[ind]))
6197                         goto error;
6198
6199                 ADD_OVERFLOW(val, mult[ind] * v);
6200                 if (val == ULONG_MAX)
6201                         goto error;
6202
6203                 timestr = tail + 1;
6204         }
6205
6206         return val;
6207
6208 error:
6209         return ULONG_MAX;
6210 }
6211
6212 #define ARG2ULL(nr, str, def_units)                                     \
6213 do {                                                                    \
6214         unsigned long long limit, units = def_units;                    \
6215         int rc;                                                         \
6216                                                                         \
6217         rc = llapi_parse_size(str, &limit, &units, 1);                  \
6218         if (rc < 0) {                                                   \
6219                 fprintf(stderr, "%s: invalid limit '%s'\n",             \
6220                         progname, str);                                 \
6221                 return CMD_HELP;                                        \
6222         }                                                               \
6223         nr = limit;                                                     \
6224 } while (0)
6225
6226 static inline int has_times_option(int argc, char **argv)
6227 {
6228         int i;
6229
6230         for (i = 1; i < argc; i++)
6231                 if (!strcmp(argv[i], "-t"))
6232                         return 1;
6233
6234         return 0;
6235 }
6236
6237 int lfs_setquota_times(int argc, char **argv)
6238 {
6239         int c, rc;
6240         struct if_quotactl qctl;
6241         char *mnt, *obd_type = (char *)qctl.obd_type;
6242         struct obd_dqblk *dqb = &qctl.qc_dqblk;
6243         struct obd_dqinfo *dqi = &qctl.qc_dqinfo;
6244         struct option long_opts[] = {
6245         { .val = 'b',   .name = "block-grace",  .has_arg = required_argument },
6246         { .val = 'g',   .name = "group",        .has_arg = no_argument },
6247         { .val = 'i',   .name = "inode-grace",  .has_arg = required_argument },
6248         { .val = 'p',   .name = "projid",       .has_arg = no_argument },
6249         { .val = 't',   .name = "times",        .has_arg = no_argument },
6250         { .val = 'u',   .name = "user",         .has_arg = no_argument },
6251         { .name = NULL } };
6252         int qtype;
6253
6254         memset(&qctl, 0, sizeof(qctl));
6255         qctl.qc_cmd  = LUSTRE_Q_SETINFO;
6256         qctl.qc_type = ALLQUOTA;
6257
6258         while ((c = getopt_long(argc, argv, "b:gi:ptu",
6259                                 long_opts, NULL)) != -1) {
6260                 switch (c) {
6261                 case 'u':
6262                         qtype = USRQUOTA;
6263                         goto quota_type;
6264                 case 'g':
6265                         qtype = GRPQUOTA;
6266                         goto quota_type;
6267                 case 'p':
6268                         qtype = PRJQUOTA;
6269 quota_type:
6270                         if (qctl.qc_type != ALLQUOTA) {
6271                                 fprintf(stderr, "error: -u/g/p can't be used "
6272                                                 "more than once\n");
6273                                 return CMD_HELP;
6274                         }
6275                         qctl.qc_type = qtype;
6276                         break;
6277                 case 'b':
6278                         if ((dqi->dqi_bgrace = str2sec(optarg)) == ULONG_MAX) {
6279                                 fprintf(stderr, "error: bad block-grace: %s\n",
6280                                         optarg);
6281                                 return CMD_HELP;
6282                         }
6283                         dqb->dqb_valid |= QIF_BTIME;
6284                         break;
6285                 case 'i':
6286                         if ((dqi->dqi_igrace = str2sec(optarg)) == ULONG_MAX) {
6287                                 fprintf(stderr, "error: bad inode-grace: %s\n",
6288                                         optarg);
6289                                 return CMD_HELP;
6290                         }
6291                         dqb->dqb_valid |= QIF_ITIME;
6292                         break;
6293                 case 't': /* Yes, of course! */
6294                         break;
6295                 default: /* getopt prints error message for us when opterr != 0 */
6296                         return CMD_HELP;
6297                 }
6298         }
6299
6300         if (qctl.qc_type == ALLQUOTA) {
6301                 fprintf(stderr, "error: neither -u, -g nor -p specified\n");
6302                 return CMD_HELP;
6303         }
6304
6305         if (optind != argc - 1) {
6306                 fprintf(stderr, "error: unexpected parameters encountered\n");
6307                 return CMD_HELP;
6308         }
6309
6310         if ((dqb->dqb_valid | QIF_BTIME && dqi->dqi_bgrace >= UINT_MAX) ||
6311             (dqb->dqb_valid | QIF_ITIME && dqi->dqi_igrace >= UINT_MAX)) {
6312                 fprintf(stderr, "error: grace time is too large\n");
6313                 return CMD_HELP;
6314         }
6315
6316         mnt = argv[optind];
6317         rc = llapi_quotactl(mnt, &qctl);
6318         if (rc) {
6319                 if (*obd_type)
6320                         fprintf(stderr, "%s %s ", obd_type,
6321                                 obd_uuid2str(&qctl.obd_uuid));
6322                 fprintf(stderr, "setquota failed: %s\n", strerror(-rc));
6323                 return rc;
6324         }
6325
6326         return 0;
6327 }
6328
6329 #define BSLIMIT (1 << 0)
6330 #define BHLIMIT (1 << 1)
6331 #define ISLIMIT (1 << 2)
6332 #define IHLIMIT (1 << 3)
6333
6334 int lfs_setquota(int argc, char **argv)
6335 {
6336         int c, rc = 0;
6337         struct if_quotactl qctl;
6338         char *mnt, *obd_type = (char *)qctl.obd_type;
6339         struct obd_dqblk *dqb = &qctl.qc_dqblk;
6340         struct option long_opts[] = {
6341         { .val = 'b',   .name = "block-softlimit",
6342                                                 .has_arg = required_argument },
6343         { .val = 'B',   .name = "block-hardlimit",
6344                                                 .has_arg = required_argument },
6345         { .val = 'd',   .name = "default",      .has_arg = no_argument },
6346         { .val = 'g',   .name = "group",        .has_arg = required_argument },
6347         { .val = 'G',   .name = "default-grp",  .has_arg = no_argument },
6348         { .val = 'i',   .name = "inode-softlimit",
6349                                                 .has_arg = required_argument },
6350         { .val = 'I',   .name = "inode-hardlimit",
6351                                                 .has_arg = required_argument },
6352         { .val = 'p',   .name = "projid",       .has_arg = required_argument },
6353         { .val = 'P',   .name = "default-prj",  .has_arg = no_argument },
6354         { .val = 'u',   .name = "user",         .has_arg = required_argument },
6355         { .val = 'U',   .name = "default-usr",  .has_arg = no_argument },
6356         { .name = NULL } };
6357         unsigned limit_mask = 0;
6358         char *endptr;
6359         bool use_default = false;
6360         int qtype;
6361
6362         if (has_times_option(argc, argv))
6363                 return lfs_setquota_times(argc, argv);
6364
6365         memset(&qctl, 0, sizeof(qctl));
6366         qctl.qc_cmd  = LUSTRE_Q_SETQUOTA;
6367         qctl.qc_type = ALLQUOTA; /* ALLQUOTA makes no sense for setquota,
6368                                   * so it can be used as a marker that qc_type
6369                                   * isn't reinitialized from command line */
6370
6371         while ((c = getopt_long(argc, argv, "b:B:dg:Gi:I:p:Pu:U",
6372                 long_opts, NULL)) != -1) {
6373                 switch (c) {
6374                 case 'U':
6375                         qctl.qc_cmd = LUSTRE_Q_SETDEFAULT;
6376                         qtype = USRQUOTA;
6377                         qctl.qc_id = 0;
6378                         goto quota_type_def;
6379                 case 'u':
6380                         qtype = USRQUOTA;
6381                         rc = name2uid(&qctl.qc_id, optarg);
6382                         goto quota_type;
6383                 case 'G':
6384                         qctl.qc_cmd = LUSTRE_Q_SETDEFAULT;
6385                         qtype = GRPQUOTA;
6386                         qctl.qc_id = 0;
6387                         goto quota_type_def;
6388                 case 'g':
6389                         qtype = GRPQUOTA;
6390                         rc = name2gid(&qctl.qc_id, optarg);
6391                         goto quota_type;
6392                 case 'P':
6393                         qctl.qc_cmd = LUSTRE_Q_SETDEFAULT;
6394                         qtype = PRJQUOTA;
6395                         qctl.qc_id = 0;
6396                         goto quota_type_def;
6397                 case 'p':
6398                         qtype = PRJQUOTA;
6399                         rc = name2projid(&qctl.qc_id, optarg);
6400 quota_type:
6401                         if (rc) {
6402                                 qctl.qc_id = strtoul(optarg, &endptr, 10);
6403                                 if (*endptr != '\0') {
6404                                         fprintf(stderr, "%s setquota: invalid"
6405                                                 " id '%s'\n", progname, optarg);
6406                                         return -1;
6407                                 }
6408                         }
6409
6410                         if (qctl.qc_id == 0) {
6411                                 fprintf(stderr, "%s setquota: can't set quota"
6412                                         " for root usr/group/project.\n",
6413                                         progname);
6414                                 return -1;
6415                         }
6416
6417 quota_type_def:
6418                         if (qctl.qc_type != ALLQUOTA) {
6419                                 fprintf(stderr,
6420                                         "%s setquota: only one of -u, -U, -g,"
6421                                         " -G, -p or -P may be specified\n",
6422                                         progname);
6423                                 return CMD_HELP;
6424                         }
6425                         qctl.qc_type = qtype;
6426                         break;
6427                 case 'd':
6428                         qctl.qc_cmd = LUSTRE_Q_SETDEFAULT;
6429                         use_default = true;
6430                         break;
6431                 case 'b':
6432                         ARG2ULL(dqb->dqb_bsoftlimit, optarg, 1024);
6433                         dqb->dqb_bsoftlimit >>= 10;
6434                         limit_mask |= BSLIMIT;
6435                         if (dqb->dqb_bsoftlimit &&
6436                             dqb->dqb_bsoftlimit <= 1024) /* <= 1M? */
6437                                 fprintf(stderr,
6438                                         "%s setquota: warning: block softlimit '%llu' smaller than minimum qunit size\n"
6439                                         "See '%s help setquota' or Lustre manual for details\n",
6440                                         progname, dqb->dqb_bsoftlimit,
6441                                         progname);
6442                         break;
6443                 case 'B':
6444                         ARG2ULL(dqb->dqb_bhardlimit, optarg, 1024);
6445                         dqb->dqb_bhardlimit >>= 10;
6446                         limit_mask |= BHLIMIT;
6447                         if (dqb->dqb_bhardlimit &&
6448                             dqb->dqb_bhardlimit <= 1024) /* <= 1M? */
6449                                 fprintf(stderr,
6450                                         "%s setquota: warning: block hardlimit '%llu' smaller than minimum qunit size\n"
6451                                         "See '%s help setquota' or Lustre manual for details\n",
6452                                         progname, dqb->dqb_bhardlimit,
6453                                         progname);
6454                         break;
6455                 case 'i':
6456                         ARG2ULL(dqb->dqb_isoftlimit, optarg, 1);
6457                         limit_mask |= ISLIMIT;
6458                         if (dqb->dqb_isoftlimit &&
6459                             dqb->dqb_isoftlimit <= 1024) /* <= 1K inodes? */
6460                                 fprintf(stderr,
6461                                         "%s setquota: warning: inode softlimit '%llu' smaller than minimum qunit size\n"
6462                                         "See '%s help setquota' or Lustre manual for details\n",
6463                                         progname, dqb->dqb_isoftlimit,
6464                                         progname);
6465                         break;
6466                 case 'I':
6467                         ARG2ULL(dqb->dqb_ihardlimit, optarg, 1);
6468                         limit_mask |= IHLIMIT;
6469                         if (dqb->dqb_ihardlimit &&
6470                             dqb->dqb_ihardlimit <= 1024) /* <= 1K inodes? */
6471                                 fprintf(stderr,
6472                                         "%s setquota: warning: inode hardlimit '%llu' smaller than minimum qunit size\n"
6473                                         "See '%s help setquota' or Lustre manual for details\n",
6474                                         progname, dqb->dqb_ihardlimit,
6475                                         progname);
6476                         break;
6477                 default:
6478                         fprintf(stderr,
6479                                 "%s setquota: unrecognized option '%s'\n",
6480                                 progname, argv[optind - 1]);
6481                         return CMD_HELP;
6482                 }
6483         }
6484
6485         if (qctl.qc_type == ALLQUOTA) {
6486                 fprintf(stderr,
6487                         "%s setquota: either -u or -g must be specified\n",
6488                         progname);
6489                 return CMD_HELP;
6490         }
6491
6492         if (!use_default && limit_mask == 0) {
6493                 fprintf(stderr,
6494                         "%s setquota: at least one limit must be specified\n",
6495                         progname);
6496                 return CMD_HELP;
6497         }
6498
6499         if (use_default && limit_mask != 0) {
6500                 fprintf(stderr,
6501                         "%s setquota: limits should not be specified when"
6502                         " using default quota\n",
6503                         progname);
6504                 return CMD_HELP;
6505         }
6506
6507         if (use_default && qctl.qc_id == 0) {
6508                 fprintf(stderr,
6509                         "%s setquota: can not set default quota for root"
6510                         " user/group/project\n",
6511                         progname);
6512                 return CMD_HELP;
6513         }
6514
6515         if (optind != argc - 1) {
6516                 fprintf(stderr,
6517                         "%s setquota: filesystem not specified or unexpected argument '%s'\n",
6518                         progname, argv[optind]);
6519                 return CMD_HELP;
6520         }
6521
6522         mnt = argv[optind];
6523
6524         if (use_default) {
6525                 dqb->dqb_bhardlimit = 0;
6526                 dqb->dqb_bsoftlimit = 0;
6527                 dqb->dqb_ihardlimit = 0;
6528                 dqb->dqb_isoftlimit = 0;
6529                 dqb->dqb_itime = 0;
6530                 dqb->dqb_btime = 0;
6531                 dqb->dqb_valid |= QIF_LIMITS | QIF_TIMES;
6532         } else if ((!(limit_mask & BHLIMIT) ^ !(limit_mask & BSLIMIT)) ||
6533                    (!(limit_mask & IHLIMIT) ^ !(limit_mask & ISLIMIT))) {
6534                 /* sigh, we can't just set blimits/ilimits */
6535                 struct if_quotactl tmp_qctl = {.qc_cmd  = LUSTRE_Q_GETQUOTA,
6536                                                .qc_type = qctl.qc_type,
6537                                                .qc_id   = qctl.qc_id};
6538
6539                 rc = llapi_quotactl(mnt, &tmp_qctl);
6540                 if (rc < 0)
6541                         return rc;
6542
6543                 if (!(limit_mask & BHLIMIT))
6544                         dqb->dqb_bhardlimit = tmp_qctl.qc_dqblk.dqb_bhardlimit;
6545                 if (!(limit_mask & BSLIMIT))
6546                         dqb->dqb_bsoftlimit = tmp_qctl.qc_dqblk.dqb_bsoftlimit;
6547                 if (!(limit_mask & IHLIMIT))
6548                         dqb->dqb_ihardlimit = tmp_qctl.qc_dqblk.dqb_ihardlimit;
6549                 if (!(limit_mask & ISLIMIT))
6550                         dqb->dqb_isoftlimit = tmp_qctl.qc_dqblk.dqb_isoftlimit;
6551
6552                 /* Keep grace times if we have got no softlimit arguments */
6553                 if ((limit_mask & BHLIMIT) && !(limit_mask & BSLIMIT)) {
6554                         dqb->dqb_valid |= QIF_BTIME;
6555                         dqb->dqb_btime = tmp_qctl.qc_dqblk.dqb_btime;
6556                 }
6557
6558                 if ((limit_mask & IHLIMIT) && !(limit_mask & ISLIMIT)) {
6559                         dqb->dqb_valid |= QIF_ITIME;
6560                         dqb->dqb_itime = tmp_qctl.qc_dqblk.dqb_itime;
6561                 }
6562         }
6563
6564         dqb->dqb_valid |= (limit_mask & (BHLIMIT | BSLIMIT)) ? QIF_BLIMITS : 0;
6565         dqb->dqb_valid |= (limit_mask & (IHLIMIT | ISLIMIT)) ? QIF_ILIMITS : 0;
6566
6567         rc = llapi_quotactl(mnt, &qctl);
6568         if (rc) {
6569                 if (*obd_type)
6570                         fprintf(stderr,
6571                                 "%s setquota: cannot quotactl '%s' '%s': %s",
6572                                 progname, obd_type,
6573                                 obd_uuid2str(&qctl.obd_uuid), strerror(-rc));
6574                 return rc;
6575         }
6576
6577         return 0;
6578 }
6579
6580 /* Converts seconds value into format string
6581  * result is returned in buf
6582  * Notes:
6583  *        1. result is in descenting order: 1w2d3h4m5s
6584  *        2. zero fields are not filled (except for p. 3): 5d1s
6585  *        3. zero seconds value is presented as "0s"
6586  */
6587 static char * __sec2str(time_t seconds, char *buf)
6588 {
6589         const char spec[] = "smhdw";
6590         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
6591         unsigned long c;
6592         char *tail = buf;
6593         int i;
6594
6595         for (i = sizeof(mult) / sizeof(mult[0]) - 1 ; i >= 0; i--) {
6596                 c = seconds / mult[i];
6597
6598                 if (c > 0 || (i == 0 && buf == tail))
6599                         tail += snprintf(tail, 40-(tail-buf), "%lu%c", c, spec[i]);
6600
6601                 seconds %= mult[i];
6602         }
6603
6604         return tail;
6605 }
6606
6607 static void sec2str(time_t seconds, char *buf, int rc)
6608 {
6609         char *tail = buf;
6610
6611         if (rc)
6612                 *tail++ = '[';
6613
6614         tail = __sec2str(seconds, tail);
6615
6616         if (rc && tail - buf < 39) {
6617                 *tail++ = ']';
6618                 *tail++ = 0;
6619         }
6620 }
6621
6622 static void diff2str(time_t seconds, char *buf, time_t now)
6623 {
6624
6625         buf[0] = 0;
6626         if (!seconds)
6627                 return;
6628         if (seconds <= now) {
6629                 strcpy(buf, "none");
6630                 return;
6631         }
6632         __sec2str(seconds - now, buf);
6633 }
6634
6635 static void print_quota_title(char *name, struct if_quotactl *qctl,
6636                               bool human_readable, bool show_default)
6637 {
6638         if (show_default) {
6639                 printf("Disk default %s quota:\n", qtype_name(qctl->qc_type));
6640                 printf("%15s %8s%8s%8s %8s%8s%8s\n",
6641                        "Filesystem", "bquota", "blimit", "bgrace",
6642                        "iquota", "ilimit", "igrace");
6643         } else {
6644                 printf("Disk quotas for %s %s (%cid %u):\n",
6645                        qtype_name(qctl->qc_type), name,
6646                        *qtype_name(qctl->qc_type), qctl->qc_id);
6647                 printf("%15s%8s %7s%8s%8s%8s %7s%8s%8s\n",
6648                        "Filesystem", human_readable ? "used" : "kbytes",
6649                        "quota", "limit", "grace",
6650                        "files", "quota", "limit", "grace");
6651         }
6652 }
6653
6654 static void kbytes2str(__u64 num, char *buf, int buflen, bool h)
6655 {
6656         if (!h) {
6657                 snprintf(buf, buflen, "%ju", (uintmax_t)num);
6658         } else {
6659                 if (num >> 40)
6660                         snprintf(buf, buflen, "%5.4gP",
6661                                  (double)num / ((__u64)1 << 40));
6662                 else if (num >> 30)
6663                         snprintf(buf, buflen, "%5.4gT",
6664                                  (double)num / (1 << 30));
6665                 else if (num >> 20)
6666                         snprintf(buf, buflen, "%5.4gG",
6667                                  (double)num / (1 << 20));
6668                 else if (num >> 10)
6669                         snprintf(buf, buflen, "%5.4gM",
6670                                  (double)num / (1 << 10));
6671                 else
6672                         snprintf(buf, buflen, "%ju%s", (uintmax_t)num, "k");
6673         }
6674 }
6675
6676 #define STRBUF_LEN      32
6677 static void print_quota(char *mnt, struct if_quotactl *qctl, int type,
6678                         int rc, bool h, bool show_default)
6679 {
6680         time_t now;
6681
6682         time(&now);
6683
6684         if (qctl->qc_cmd == LUSTRE_Q_GETQUOTA || qctl->qc_cmd == Q_GETOQUOTA ||
6685             qctl->qc_cmd == LUSTRE_Q_GETDEFAULT) {
6686                 int bover = 0, iover = 0;
6687                 struct obd_dqblk *dqb = &qctl->qc_dqblk;
6688                 char numbuf[3][STRBUF_LEN];
6689                 char timebuf[40];
6690                 char strbuf[STRBUF_LEN];
6691
6692                 if (dqb->dqb_bhardlimit &&
6693                     lustre_stoqb(dqb->dqb_curspace) >= dqb->dqb_bhardlimit) {
6694                         bover = 1;
6695                 } else if (dqb->dqb_bsoftlimit && dqb->dqb_btime) {
6696                         if (dqb->dqb_btime > now) {
6697                                 bover = 2;
6698                         } else {
6699                                 bover = 3;
6700                         }
6701                 }
6702
6703                 if (dqb->dqb_ihardlimit &&
6704                     dqb->dqb_curinodes >= dqb->dqb_ihardlimit) {
6705                         iover = 1;
6706                 } else if (dqb->dqb_isoftlimit && dqb->dqb_itime) {
6707                         if (dqb->dqb_itime > now) {
6708                                 iover = 2;
6709                         } else {
6710                                 iover = 3;
6711                         }
6712                 }
6713
6714
6715                 if (strlen(mnt) > 15)
6716                         printf("%s\n%15s", mnt, "");
6717                 else
6718                         printf("%15s", mnt);
6719
6720                 if (bover)
6721                         diff2str(dqb->dqb_btime, timebuf, now);
6722                 else if (show_default)
6723                         snprintf(timebuf, sizeof(timebuf), "%llu",
6724                                  dqb->dqb_btime);
6725
6726                 kbytes2str(lustre_stoqb(dqb->dqb_curspace),
6727                            strbuf, sizeof(strbuf), h);
6728                 if (rc == -EREMOTEIO)
6729                         sprintf(numbuf[0], "%s*", strbuf);
6730                 else
6731                         sprintf(numbuf[0], (dqb->dqb_valid & QIF_SPACE) ?
6732                                 "%s" : "[%s]", strbuf);
6733
6734                 kbytes2str(dqb->dqb_bsoftlimit, strbuf, sizeof(strbuf), h);
6735                 if (type == QC_GENERAL)
6736                         sprintf(numbuf[1], (dqb->dqb_valid & QIF_BLIMITS) ?
6737                                 "%s" : "[%s]", strbuf);
6738                 else
6739                         sprintf(numbuf[1], "%s", "-");
6740
6741                 kbytes2str(dqb->dqb_bhardlimit, strbuf, sizeof(strbuf), h);
6742                 sprintf(numbuf[2], (dqb->dqb_valid & QIF_BLIMITS) ?
6743                         "%s" : "[%s]", strbuf);
6744
6745                 if (show_default)
6746                         printf(" %6s %7s %7s", numbuf[1], numbuf[2], timebuf);
6747                 else
6748                         printf(" %7s%c %6s %7s %7s",
6749                                numbuf[0], bover ? '*' : ' ', numbuf[1],
6750                                numbuf[2], bover > 1 ? timebuf : "-");
6751
6752
6753                 if (iover)
6754                         diff2str(dqb->dqb_itime, timebuf, now);
6755                 else if (show_default)
6756                         snprintf(timebuf, sizeof(timebuf), "%llu",
6757                                  dqb->dqb_itime);
6758
6759                 snprintf(numbuf[0], sizeof(numbuf),
6760                          (dqb->dqb_valid & QIF_INODES) ? "%ju" : "[%ju]",
6761                          (uintmax_t)dqb->dqb_curinodes);
6762
6763                 if (type == QC_GENERAL)
6764                         sprintf(numbuf[1], (dqb->dqb_valid & QIF_ILIMITS) ?
6765                                 "%ju" : "[%ju]",
6766                                 (uintmax_t)dqb->dqb_isoftlimit);
6767                 else
6768                         sprintf(numbuf[1], "%s", "-");
6769
6770                 sprintf(numbuf[2], (dqb->dqb_valid & QIF_ILIMITS) ?
6771                         "%ju" : "[%ju]", (uintmax_t)dqb->dqb_ihardlimit);
6772
6773                 if (show_default)
6774                         printf(" %6s %7s %7s", numbuf[1], numbuf[2], timebuf);
6775                 else if (type != QC_OSTIDX)
6776                         printf(" %7s%c %6s %7s %7s",
6777                                numbuf[0], iover ? '*' : ' ', numbuf[1],
6778                                numbuf[2], iover > 1 ? timebuf : "-");
6779                 else
6780                         printf(" %7s %7s %7s %7s", "-", "-", "-", "-");
6781                 printf("\n");
6782
6783         } else if (qctl->qc_cmd == LUSTRE_Q_GETINFO ||
6784                    qctl->qc_cmd == Q_GETOINFO) {
6785                 char bgtimebuf[40];
6786                 char igtimebuf[40];
6787
6788                 sec2str(qctl->qc_dqinfo.dqi_bgrace, bgtimebuf, rc);
6789                 sec2str(qctl->qc_dqinfo.dqi_igrace, igtimebuf, rc);
6790                 printf("Block grace time: %s; Inode grace time: %s\n",
6791                        bgtimebuf, igtimebuf);
6792         }
6793 }
6794
6795 static int print_obd_quota(char *mnt, struct if_quotactl *qctl, int is_mdt,
6796                            bool h, __u64 *total)
6797 {
6798         int rc = 0, rc1 = 0, count = 0;
6799         __u32 valid = qctl->qc_valid;
6800
6801         rc = llapi_get_obd_count(mnt, &count, is_mdt);
6802         if (rc) {
6803                 fprintf(stderr, "can not get %s count: %s\n",
6804                         is_mdt ? "mdt": "ost", strerror(-rc));
6805                 return rc;
6806         }
6807
6808         for (qctl->qc_idx = 0; qctl->qc_idx < count; qctl->qc_idx++) {
6809                 qctl->qc_valid = is_mdt ? QC_MDTIDX : QC_OSTIDX;
6810                 rc = llapi_quotactl(mnt, qctl);
6811                 if (rc) {
6812                         /* It is remote client case. */
6813                         if (rc == -EOPNOTSUPP) {
6814                                 rc = 0;
6815                                 goto out;
6816                         }
6817
6818                         if (!rc1)
6819                                 rc1 = rc;
6820                         fprintf(stderr, "quotactl %s%d failed.\n",
6821                                 is_mdt ? "mdt": "ost", qctl->qc_idx);
6822                         continue;
6823                 }
6824
6825                 print_quota(obd_uuid2str(&qctl->obd_uuid), qctl,
6826                             qctl->qc_valid, 0, h, false);
6827                 *total += is_mdt ? qctl->qc_dqblk.dqb_ihardlimit :
6828                                    qctl->qc_dqblk.dqb_bhardlimit;
6829         }
6830 out:
6831         qctl->qc_valid = valid;
6832         return rc ? : rc1;
6833 }
6834
6835 static int get_print_quota(char *mnt, char *name, struct if_quotactl *qctl,
6836                            int verbose, int quiet, bool human_readable,
6837                            bool show_default)
6838 {
6839         int rc1 = 0, rc2 = 0, rc3 = 0;
6840         char *obd_type = (char *)qctl->obd_type;
6841         char *obd_uuid = (char *)qctl->obd_uuid.uuid;
6842         __u64 total_ialloc = 0, total_balloc = 0;
6843         bool use_default_for_blk = false;
6844         bool use_default_for_file = false;
6845         int inacc;
6846
6847         rc1 = llapi_quotactl(mnt, qctl);
6848         if (rc1 < 0) {
6849                 switch (rc1) {
6850                 case -ESRCH:
6851                         fprintf(stderr, "%s quotas are not enabled.\n",
6852                                 qtype_name(qctl->qc_type));
6853                         goto out;
6854                 case -EPERM:
6855                         fprintf(stderr, "Permission denied.\n");
6856                 case -ENODEV:
6857                 case -ENOENT:
6858                         /* We already got error message. */
6859                         goto out;
6860                 default:
6861                         fprintf(stderr, "Unexpected quotactl error: %s\n",
6862                                 strerror(-rc1));
6863                 }
6864         }
6865
6866         if (!show_default && qctl->qc_id == 0) {
6867                 qctl->qc_dqblk.dqb_bhardlimit = 0;
6868                 qctl->qc_dqblk.dqb_bsoftlimit = 0;
6869                 qctl->qc_dqblk.dqb_ihardlimit = 0;
6870                 qctl->qc_dqblk.dqb_isoftlimit = 0;
6871                 qctl->qc_dqblk.dqb_btime = 0;
6872                 qctl->qc_dqblk.dqb_itime = 0;
6873                 qctl->qc_dqblk.dqb_valid |= QIF_LIMITS | QIF_TIMES;
6874         }
6875
6876         if (qctl->qc_dqblk.dqb_valid & QIF_BTIME &&
6877             LQUOTA_FLAG(qctl->qc_dqblk.dqb_btime) & LQUOTA_FLAG_DEFAULT) {
6878                 use_default_for_blk = true;
6879                 qctl->qc_dqblk.dqb_btime &= LQUOTA_GRACE_MASK;
6880         }
6881
6882         if (qctl->qc_dqblk.dqb_valid & QIF_ITIME &&
6883             LQUOTA_FLAG(qctl->qc_dqblk.dqb_itime) & LQUOTA_FLAG_DEFAULT) {
6884                 use_default_for_file = true;
6885                 qctl->qc_dqblk.dqb_itime &= LQUOTA_GRACE_MASK;
6886         }
6887
6888         if ((qctl->qc_cmd == LUSTRE_Q_GETQUOTA ||
6889              qctl->qc_cmd == LUSTRE_Q_GETDEFAULT) && !quiet)
6890                 print_quota_title(name, qctl, human_readable, show_default);
6891
6892         if (rc1 && *obd_type)
6893                 fprintf(stderr, "%s %s ", obd_type, obd_uuid);
6894
6895         if (qctl->qc_valid != QC_GENERAL)
6896                 mnt = "";
6897
6898         inacc = (qctl->qc_cmd == LUSTRE_Q_GETQUOTA) &&
6899                 ((qctl->qc_dqblk.dqb_valid & (QIF_LIMITS|QIF_USAGE)) !=
6900                  (QIF_LIMITS|QIF_USAGE));
6901
6902         print_quota(mnt, qctl, QC_GENERAL, rc1, human_readable, show_default);
6903
6904         if (!show_default && verbose &&
6905             qctl->qc_valid == QC_GENERAL && qctl->qc_cmd != LUSTRE_Q_GETINFO) {
6906                 char strbuf[STRBUF_LEN];
6907
6908                 rc2 = print_obd_quota(mnt, qctl, 1, human_readable,
6909                                       &total_ialloc);
6910                 rc3 = print_obd_quota(mnt, qctl, 0, human_readable,
6911                                       &total_balloc);
6912                 kbytes2str(total_balloc, strbuf, sizeof(strbuf),
6913                            human_readable);
6914                 printf("Total allocated inode limit: %ju, total "
6915                        "allocated block limit: %s\n", (uintmax_t)total_ialloc,
6916                        strbuf);
6917         }
6918
6919         if (use_default_for_blk)
6920                 printf("%cid %u is using default block quota setting\n",
6921                        *qtype_name(qctl->qc_type), qctl->qc_id);
6922
6923         if (use_default_for_file)
6924                 printf("%cid %u is using default file quota setting\n",
6925                        *qtype_name(qctl->qc_type), qctl->qc_id);
6926
6927         if (rc1 || rc2 || rc3 || inacc)
6928                 printf("Some errors happened when getting quota info. "
6929                        "Some devices may be not working or deactivated. "
6930                        "The data in \"[]\" is inaccurate.\n");
6931 out:
6932         return rc1;
6933
6934 }
6935
6936 static int lfs_project(int argc, char **argv)
6937 {
6938         int ret = 0, err = 0, c, i;
6939         struct project_handle_control phc = { 0 };
6940         enum lfs_project_ops_t op;
6941
6942         phc.newline = true;
6943         phc.assign_projid = false;
6944         /* default action */
6945         op = LFS_PROJECT_LIST;
6946
6947         while ((c = getopt(argc, argv, "p:cCsdkr0")) != -1) {
6948                 switch (c) {
6949                 case 'c':
6950                         if (op != LFS_PROJECT_LIST) {
6951                                 fprintf(stderr,
6952                                         "%s: cannot specify '-c' '-C' '-s' together\n",
6953                                         progname);
6954                                 return CMD_HELP;
6955                         }
6956
6957                         op = LFS_PROJECT_CHECK;
6958                         break;
6959                 case 'C':
6960                         if (op != LFS_PROJECT_LIST) {
6961                                 fprintf(stderr,
6962                                         "%s: cannot specify '-c' '-C' '-s' together\n",
6963                                         progname);
6964                                 return CMD_HELP;
6965                         }
6966
6967                         op = LFS_PROJECT_CLEAR;
6968                         break;
6969                 case 's':
6970                         if (op != LFS_PROJECT_LIST) {
6971                                 fprintf(stderr,
6972                                         "%s: cannot specify '-c' '-C' '-s' together\n",
6973                                         progname);
6974                                 return CMD_HELP;
6975                         }
6976
6977                         phc.set_inherit = true;
6978                         op = LFS_PROJECT_SET;
6979                         break;
6980                 case 'd':
6981                         phc.dironly = true;
6982                         break;
6983                 case 'k':
6984                         phc.keep_projid = true;
6985                         break;
6986                 case 'r':
6987                         phc.recursive = true;
6988                         break;
6989                 case 'p':
6990                         phc.projid = strtoul(optarg, NULL, 0);
6991                         phc.assign_projid = true;
6992
6993                         break;
6994                 case '0':
6995                         phc.newline = false;
6996                         break;
6997                 default:
6998                         fprintf(stderr, "%s: invalid option '%c'\n",
6999                                 progname, optopt);
7000                         return CMD_HELP;
7001                 }
7002         }
7003
7004         if (phc.assign_projid && op == LFS_PROJECT_LIST) {
7005                 op = LFS_PROJECT_SET;
7006                 phc.set_projid = true;
7007         } else if (phc.assign_projid && op == LFS_PROJECT_SET) {
7008                 phc.set_projid = true;
7009         }
7010
7011         switch (op) {
7012         case LFS_PROJECT_CHECK:
7013                 if (phc.keep_projid) {
7014                         fprintf(stderr,
7015                                 "%s: '-k' is useless together with '-c'\n",
7016                                 progname);
7017                         return CMD_HELP;
7018                 }
7019                 break;
7020         case LFS_PROJECT_CLEAR:
7021                 if (!phc.newline) {
7022                         fprintf(stderr,
7023                                 "%s: '-0' is useless together with '-C'\n",
7024                                 progname);
7025                         return CMD_HELP;
7026                 }
7027                 if (phc.assign_projid) {
7028                         fprintf(stderr,
7029                                 "%s: '-p' is useless together with '-C'\n",
7030                                 progname);
7031                         return CMD_HELP;
7032                 }
7033                 break;
7034         case LFS_PROJECT_SET:
7035                 if (!phc.newline) {
7036                         fprintf(stderr,
7037                                 "%s: '-0' is useless together with '-s'\n",
7038                                 progname);
7039                         return CMD_HELP;
7040                 }
7041                 if (phc.keep_projid) {
7042                         fprintf(stderr,
7043                                 "%s: '-k' is useless together with '-s'\n",
7044                                 progname);
7045                         return CMD_HELP;
7046                 }
7047                 break;
7048         default:
7049                 if (!phc.newline) {
7050                         fprintf(stderr,
7051                                 "%s: '-0' is useless for list operations\n",
7052                                 progname);
7053                         return CMD_HELP;
7054                 }
7055                 break;
7056         }
7057
7058         argv += optind;
7059         argc -= optind;
7060         if (argc == 0) {
7061                 fprintf(stderr, "%s: missing file or directory target(s)\n",
7062                         progname);
7063                 return CMD_HELP;
7064         }
7065
7066         for (i = 0; i < argc; i++) {
7067                 switch (op) {
7068                 case LFS_PROJECT_CHECK:
7069                         err = lfs_project_check(argv[i], &phc);
7070                         break;
7071                 case LFS_PROJECT_LIST:
7072                         err = lfs_project_list(argv[i], &phc);
7073                         break;
7074                 case LFS_PROJECT_CLEAR:
7075                         err = lfs_project_clear(argv[i], &phc);
7076                         break;
7077                 case LFS_PROJECT_SET:
7078                         err = lfs_project_set(argv[i], &phc);
7079                         break;
7080                 default:
7081                         break;
7082                 }
7083                 if (err && !ret)
7084                         ret = err;
7085         }
7086
7087         return ret;
7088 }
7089
7090 static int lfs_quota(int argc, char **argv)
7091 {
7092         int c;
7093         char *mnt, *name = NULL;
7094         struct if_quotactl qctl = { .qc_cmd = LUSTRE_Q_GETQUOTA,
7095                                     .qc_type = ALLQUOTA };
7096         char *obd_uuid = (char *)qctl.obd_uuid.uuid;
7097         int rc = 0, rc1 = 0, verbose = 0, quiet = 0;
7098         char *endptr;
7099         __u32 valid = QC_GENERAL, idx = 0;
7100         bool human_readable = false;
7101         bool show_default = false;
7102         int qtype;
7103
7104         while ((c = getopt(argc, argv, "gGi:I:o:pPqtuUvh")) != -1) {
7105                 switch (c) {
7106                 case 'U':
7107                         show_default = true;
7108                 case 'u':
7109                         qtype = USRQUOTA;
7110                         goto quota_type;
7111                 case 'G':
7112                         show_default = true;
7113                 case 'g':
7114                         qtype = GRPQUOTA;
7115                         goto quota_type;
7116                 case 'P':
7117                         show_default = true;
7118                 case 'p':
7119                         qtype = PRJQUOTA;
7120 quota_type:
7121                         if (qctl.qc_type != ALLQUOTA) {
7122                                 fprintf(stderr,
7123                                         "%s quota: only one of -u, -g, or -p may be specified\n",
7124                                         progname);
7125                                 return CMD_HELP;
7126                         }
7127                         qctl.qc_type = qtype;
7128                         break;
7129                 case 't':
7130                         qctl.qc_cmd = LUSTRE_Q_GETINFO;
7131                         break;
7132                 case 'o':
7133                         valid = qctl.qc_valid = QC_UUID;
7134                         snprintf(obd_uuid, sizeof(qctl.obd_uuid), "%s", optarg);
7135                         break;
7136                 case 'i':
7137                         valid = qctl.qc_valid = QC_MDTIDX;
7138                         idx = qctl.qc_idx = atoi(optarg);
7139                         if (idx == 0 && *optarg != '0') {
7140                                 fprintf(stderr,
7141                                         "%s quota: invalid MDT index '%s'\n",
7142                                         progname, optarg);
7143                                 return CMD_HELP;
7144                         }
7145                         break;
7146                 case 'I':
7147                         valid = qctl.qc_valid = QC_OSTIDX;
7148                         idx = qctl.qc_idx = atoi(optarg);
7149                         if (idx == 0 && *optarg != '0') {
7150                                 fprintf(stderr,
7151                                         "%s quota: invalid OST index '%s'\n",
7152                                         progname, optarg);
7153                                 return CMD_HELP;
7154                         }
7155                         break;
7156                 case 'v':
7157                         verbose = 1;
7158                         break;
7159                 case 'q':
7160                         quiet = 1;
7161                         break;
7162                 case 'h':
7163                         human_readable = true;
7164                         break;
7165                 default:
7166                         fprintf(stderr, "%s quota: unrecognized option '%s'\n",
7167                                 progname, argv[optind - 1]);
7168                         return CMD_HELP;
7169                 }
7170         }
7171
7172         /* current uid/gid info for "lfs quota /path/to/lustre/mount" */
7173         if (qctl.qc_cmd == LUSTRE_Q_GETQUOTA && qctl.qc_type == ALLQUOTA &&
7174             optind == argc - 1 && !show_default) {
7175
7176                 qctl.qc_cmd = LUSTRE_Q_GETQUOTA;
7177                 qctl.qc_idx = idx;
7178
7179                 for (qtype = USRQUOTA; qtype <= GRPQUOTA; qtype++) {
7180                         qctl.qc_type = qtype;
7181                         qctl.qc_valid = valid;
7182                         if (qtype == USRQUOTA) {
7183                                 qctl.qc_id = geteuid();
7184                                 rc = uid2name(&name, qctl.qc_id);
7185                         } else {
7186                                 qctl.qc_id = getegid();
7187                                 rc = gid2name(&name, qctl.qc_id);
7188                                 memset(&qctl.qc_dqblk, 0,
7189                                        sizeof(qctl.qc_dqblk));
7190                         }
7191                         if (rc)
7192                                 name = "<unknown>";
7193                         mnt = argv[optind];
7194                         rc1 = get_print_quota(mnt, name, &qctl, verbose, quiet,
7195                                               human_readable, show_default);
7196                         if (rc1 && !rc)
7197                                 rc = rc1;
7198                 }
7199                 return rc;
7200         /* lfs quota -u username /path/to/lustre/mount */
7201         } else if (qctl.qc_cmd == LUSTRE_Q_GETQUOTA) {
7202                 /* options should be followed by u/g-name and mntpoint */
7203                 if ((!show_default && optind + 2 != argc) ||
7204                     (show_default && optind + 1 != argc) ||
7205                     qctl.qc_type == ALLQUOTA) {
7206                         fprintf(stderr,
7207                                 "%s quota: name and mount point must be specified\n",
7208                                 progname);
7209                         return CMD_HELP;
7210                 }
7211
7212                 if (!show_default) {
7213                         name = argv[optind++];
7214                         switch (qctl.qc_type) {
7215                         case USRQUOTA:
7216                                 rc = name2uid(&qctl.qc_id, name);
7217                                 break;
7218                         case GRPQUOTA:
7219                                 rc = name2gid(&qctl.qc_id, name);
7220                                 break;
7221                         case PRJQUOTA:
7222                                 rc = name2projid(&qctl.qc_id, name);
7223                                 break;
7224                         default:
7225                                 rc = -ENOTSUP;
7226                                 break;
7227                         }
7228                 } else {
7229                         qctl.qc_valid = QC_GENERAL;
7230                         qctl.qc_cmd = LUSTRE_Q_GETDEFAULT;
7231                         qctl.qc_id = 0;
7232                 }
7233
7234                 if (rc) {
7235                         qctl.qc_id = strtoul(name, &endptr, 10);
7236                         if (*endptr != '\0') {
7237                                 fprintf(stderr, "%s quota: invalid id '%s'\n",
7238                                         progname, name);
7239                                 return CMD_HELP;
7240                         }
7241                 }
7242         } else if (optind + 1 != argc || qctl.qc_type == ALLQUOTA) {
7243                 fprintf(stderr, "%s quota: missing quota info argument(s)\n",
7244                         progname);
7245                 return CMD_HELP;
7246         }
7247
7248         mnt = argv[optind];
7249         rc = get_print_quota(mnt, name, &qctl, verbose, quiet,
7250                              human_readable, show_default);
7251         return rc;
7252 }
7253 #endif /* HAVE_SYS_QUOTA_H! */
7254
7255 static int flushctx_ioctl(char *mp)
7256 {
7257         int fd, rc;
7258
7259         fd = open(mp, O_RDONLY);
7260         if (fd == -1) {
7261                 fprintf(stderr, "flushctx: error open %s: %s\n",
7262                         mp, strerror(errno));
7263                 return -1;
7264         }
7265
7266         rc = ioctl(fd, LL_IOC_FLUSHCTX);
7267         if (rc == -1)
7268                 fprintf(stderr, "flushctx: error ioctl %s: %s\n",
7269                         mp, strerror(errno));
7270
7271         close(fd);
7272         return rc;
7273 }
7274
7275 static int lfs_flushctx(int argc, char **argv)
7276 {
7277         int     kdestroy = 0, c;
7278         char    mntdir[PATH_MAX] = {'\0'};
7279         int     index = 0;
7280         int     rc = 0;
7281
7282         while ((c = getopt(argc, argv, "k")) != -1) {
7283                 switch (c) {
7284                 case 'k':
7285                         kdestroy = 1;
7286                         break;
7287                 default:
7288                         fprintf(stderr, "error: %s: option '-%c' "
7289                                         "unrecognized\n", argv[0], c);
7290                         return CMD_HELP;
7291                 }
7292         }
7293
7294         if (kdestroy) {
7295             if ((rc = system("kdestroy > /dev/null")) != 0) {
7296                 rc = WEXITSTATUS(rc);
7297                 fprintf(stderr, "error destroying tickets: %d, continuing\n", rc);
7298             }
7299         }
7300
7301         if (optind >= argc) {
7302                 /* flush for all mounted lustre fs. */
7303                 while (!llapi_search_mounts(NULL, index++, mntdir, NULL)) {
7304                         /* Check if we have a mount point */
7305                         if (mntdir[0] == '\0')
7306                                 continue;
7307
7308                         if (flushctx_ioctl(mntdir))
7309                                 rc = -1;
7310
7311                         mntdir[0] = '\0'; /* avoid matching in next loop */
7312                 }
7313         } else {
7314                 /* flush fs as specified */
7315                 while (optind < argc) {
7316                         if (flushctx_ioctl(argv[optind++]))
7317                                 rc = -1;
7318                 }
7319         }
7320         return rc;
7321 }
7322
7323 static int lfs_changelog(int argc, char **argv)
7324 {
7325         void *changelog_priv;
7326         struct changelog_rec *rec;
7327         long long startrec = 0, endrec = 0;
7328         char *mdd;
7329         struct option long_opts[] = {
7330                 { .val = 'f', .name = "follow", .has_arg = no_argument },
7331                 { .name = NULL } };
7332         char short_opts[] = "f";
7333         int rc, follow = 0;
7334
7335         while ((rc = getopt_long(argc, argv, short_opts,
7336                 long_opts, NULL)) != -1) {
7337                 switch (rc) {
7338                 case 'f':
7339                         follow++;
7340                         break;
7341                 default:
7342                         fprintf(stderr,
7343                                 "%s changelog: unrecognized option '%s'\n",
7344                                 progname, argv[optind - 1]);
7345                         return CMD_HELP;
7346                 }
7347         }
7348         if (optind >= argc) {
7349                 fprintf(stderr, "%s changelog: mdtname must be specified\n",
7350                         progname);
7351                 return CMD_HELP;
7352         }
7353
7354         mdd = argv[optind++];
7355         if (argc > optind)
7356                 startrec = strtoll(argv[optind++], NULL, 10);
7357         if (argc > optind)
7358                 endrec = strtoll(argv[optind++], NULL, 10);
7359
7360         rc = llapi_changelog_start(&changelog_priv,
7361                                    CHANGELOG_FLAG_BLOCK |
7362                                    CHANGELOG_FLAG_JOBID |
7363                                    CHANGELOG_FLAG_EXTRA_FLAGS |
7364                                    (follow ? CHANGELOG_FLAG_FOLLOW : 0),
7365                                    mdd, startrec);
7366         if (rc < 0) {
7367                 fprintf(stderr, "%s changelog: cannot start changelog: %s\n",
7368                         progname, strerror(errno = -rc));
7369                 return rc;
7370         }
7371
7372         rc = llapi_changelog_set_xflags(changelog_priv,
7373                                         CHANGELOG_EXTRA_FLAG_UIDGID |
7374                                         CHANGELOG_EXTRA_FLAG_NID |
7375                                         CHANGELOG_EXTRA_FLAG_OMODE |
7376                                         CHANGELOG_EXTRA_FLAG_XATTR);
7377         if (rc < 0) {
7378                 fprintf(stderr,
7379                         "%s changelog: cannot set xflags for changelog: %s\n",
7380                         progname, strerror(errno = -rc));
7381                 return rc;
7382         }
7383
7384         while ((rc = llapi_changelog_recv(changelog_priv, &rec)) == 0) {
7385                 time_t secs;
7386                 struct tm ts;
7387
7388                 if (endrec && rec->cr_index > endrec) {
7389                         llapi_changelog_free(&rec);
7390                         break;
7391                 }
7392                 if (rec->cr_index < startrec) {
7393                         llapi_changelog_free(&rec);
7394                         continue;
7395                 }
7396
7397                 secs = rec->cr_time >> 30;
7398                 gmtime_r(&secs, &ts);
7399                 printf("%ju %02d%-5s %02d:%02d:%02d.%09d %04d.%02d.%02d "
7400                        "0x%x t="DFID, (uintmax_t)rec->cr_index, rec->cr_type,
7401                        changelog_type2str(rec->cr_type),
7402                        ts.tm_hour, ts.tm_min, ts.tm_sec,
7403                        (int)(rec->cr_time & ((1 << 30) - 1)),
7404                        ts.tm_year + 1900, ts.tm_mon + 1, ts.tm_mday,
7405                        rec->cr_flags & CLF_FLAGMASK, PFID(&rec->cr_tfid));
7406
7407                 if (rec->cr_flags & CLF_JOBID) {
7408                         struct changelog_ext_jobid *jid =
7409                                 changelog_rec_jobid(rec);
7410
7411                         if (jid->cr_jobid[0] != '\0')
7412                                 printf(" j=%s", jid->cr_jobid);
7413                 }
7414
7415                 if (rec->cr_flags & CLF_EXTRA_FLAGS) {
7416                         struct changelog_ext_extra_flags *ef =
7417                                 changelog_rec_extra_flags(rec);
7418
7419                         printf(" ef=0x%llx", ef->cr_extra_flags);
7420
7421                         if (ef->cr_extra_flags & CLFE_UIDGID) {
7422                                 struct changelog_ext_uidgid *uidgid =
7423                                         changelog_rec_uidgid(rec);
7424
7425                                 printf(" u=%llu:%llu",
7426                                        uidgid->cr_uid, uidgid->cr_gid);
7427                         }
7428                         if (ef->cr_extra_flags & CLFE_NID) {
7429                                 struct changelog_ext_nid *nid =
7430                                         changelog_rec_nid(rec);
7431
7432                                 printf(" nid=%s",
7433                                        libcfs_nid2str(nid->cr_nid));
7434                         }
7435
7436                         if (ef->cr_extra_flags & CLFE_OPEN) {
7437                                 struct changelog_ext_openmode *omd =
7438                                         changelog_rec_openmode(rec);
7439                                 char mode[] = "---";
7440
7441                                 /* exec mode must be exclusive */
7442                                 if (omd->cr_openflags & MDS_FMODE_EXEC) {
7443                                         mode[2] = 'x';
7444                                 } else {
7445                                         if (omd->cr_openflags & MDS_FMODE_READ)
7446                                                 mode[0] = 'r';
7447                                         if (omd->cr_openflags &
7448                                             (MDS_FMODE_WRITE |
7449                                              MDS_OPEN_TRUNC |
7450                                              MDS_OPEN_APPEND))
7451                                                 mode[1] = 'w';
7452                                 }
7453
7454                                 if (strcmp(mode, "---") != 0)
7455                                         printf(" m=%s", mode);
7456
7457                         }
7458
7459                         if (ef->cr_extra_flags & CLFE_XATTR) {
7460                                 struct changelog_ext_xattr *xattr =
7461                                         changelog_rec_xattr(rec);
7462
7463                                 if (xattr->cr_xattr[0] != '\0')
7464                                         printf(" x=%s", xattr->cr_xattr);
7465                         }
7466                 }
7467
7468                 if (rec->cr_namelen)
7469                         printf(" p="DFID" %.*s", PFID(&rec->cr_pfid),
7470                                rec->cr_namelen, changelog_rec_name(rec));
7471
7472                 if (rec->cr_flags & CLF_RENAME) {
7473                         struct changelog_ext_rename *rnm =
7474                                 changelog_rec_rename(rec);
7475
7476                         if (!fid_is_zero(&rnm->cr_sfid))
7477                                 printf(" s="DFID" sp="DFID" %.*s",
7478                                        PFID(&rnm->cr_sfid),
7479                                        PFID(&rnm->cr_spfid),
7480                                        (int)changelog_rec_snamelen(rec),
7481                                        changelog_rec_sname(rec));
7482                 }
7483                 printf("\n");
7484
7485                 llapi_changelog_free(&rec);
7486         }
7487
7488         llapi_changelog_fini(&changelog_priv);
7489
7490         if (rc < 0)
7491                 fprintf(stderr, "%s changelog: cannot access changelog: %s\n",
7492                         progname, strerror(errno = -rc));
7493
7494         return (rc == 1 ? 0 : rc);
7495 }
7496
7497 static int lfs_changelog_clear(int argc, char **argv)
7498 {
7499         long long endrec;
7500         int rc;
7501
7502         if (argc != 4)
7503                 return CMD_HELP;
7504
7505         endrec = strtoll(argv[3], NULL, 10);
7506
7507         rc = llapi_changelog_clear(argv[1], argv[2], endrec);
7508
7509         if (rc == -EINVAL)
7510                 fprintf(stderr, "%s: record out of range: %llu\n",
7511                         argv[0], endrec);
7512         else if (rc == -ENOENT)
7513                 fprintf(stderr, "%s: no changelog user: %s\n",
7514                         argv[0], argv[2]);
7515         else if (rc)
7516                 fprintf(stderr, "%s error: %s\n", argv[0],
7517                         strerror(-rc));
7518
7519         if (rc)
7520                 errno = -rc;
7521
7522         return rc;
7523 }
7524
7525 static int lfs_fid2path(int argc, char **argv)
7526 {
7527         struct option long_opts[] = {
7528                 { .val = 'c',   .name = "cur",  .has_arg = no_argument },
7529                 { .val = 'l',   .name = "link", .has_arg = required_argument },
7530                 { .val = 'r',   .name = "rec",  .has_arg = required_argument },
7531                 { .name = NULL } };
7532         char  short_opts[] = "cl:r:";
7533         char *device, *fid, *path;
7534         long long recno = -1;
7535         int linkno = -1;
7536         int lnktmp;
7537         int printcur = 0;
7538         int rc = 0;
7539         char *endptr = NULL;
7540
7541         while ((rc = getopt_long(argc, argv, short_opts,
7542                 long_opts, NULL)) != -1) {
7543                 switch (rc) {
7544                 case 'c':
7545                         printcur++;
7546                         break;
7547                 case 'l':
7548                         linkno = strtol(optarg, &endptr, 10);
7549                         if (*endptr != '\0') {
7550                                 fprintf(stderr,
7551                                         "%s fid2path: invalid linkno '%s'\n",
7552                                         progname, optarg);
7553                                 return CMD_HELP;
7554                         }
7555                         break;
7556                 case 'r':
7557                         recno = strtoll(optarg, &endptr, 10);
7558                         if (*endptr != '\0') {
7559                                 fprintf(stderr,
7560                                         "%s fid2path: invalid recno '%s'\n",
7561                                         progname, optarg);
7562                                 return CMD_HELP;
7563                         }
7564                         break;
7565                 default:
7566                         fprintf(stderr,
7567                                 "%s fid2path: unrecognized option '%s'\n",
7568                                 progname, argv[optind - 1]);
7569                         return CMD_HELP;
7570                 }
7571         }
7572
7573         if (argc < 3) {
7574                 fprintf(stderr,
7575                         "%s fid2path: <fsname|rootpath> and <fid>... must be specified\n",
7576                         progname);
7577                 return CMD_HELP;
7578         }
7579
7580         device = argv[optind++];
7581         path = calloc(1, PATH_MAX);
7582         if (path == NULL) {
7583                 rc = -errno;
7584                 fprintf(stderr,
7585                         "%s fid2path: cannot allocate memory for path: %s\n",
7586                         progname, strerror(-rc));
7587                 return rc;
7588         }
7589
7590         rc = 0;
7591         while (optind < argc) {
7592                 fid = argv[optind++];
7593
7594                 lnktmp = (linkno >= 0) ? linkno : 0;
7595                 while (1) {
7596                         int oldtmp = lnktmp;
7597                         long long rectmp = recno;
7598                         int rc2;
7599                         rc2 = llapi_fid2path(device, fid, path, PATH_MAX,
7600                                              &rectmp, &lnktmp);
7601                         if (rc2 < 0) {
7602                                 fprintf(stderr,
7603                                         "%s fid2path: cannot find '%s': %s\n",
7604                                         progname, fid, strerror(errno = -rc2));
7605                                 if (rc == 0)
7606                                         rc = rc2;
7607                                 break;
7608                         }
7609
7610                         if (printcur)
7611                                 fprintf(stdout, "%lld ", rectmp);
7612                         if (device[0] == '/') {
7613                                 fprintf(stdout, "%s", device);
7614                                 if (device[strlen(device) - 1] != '/')
7615                                         fprintf(stdout, "/");
7616                         } else if (path[0] == '\0') {
7617                                 fprintf(stdout, "/");
7618                         }
7619                         fprintf(stdout, "%s\n", path);
7620
7621                         if (linkno >= 0)
7622                                 /* specified linkno */
7623                                 break;
7624                         if (oldtmp == lnktmp)
7625                                 /* no more links */
7626                                 break;
7627                 }
7628         }
7629
7630         free(path);
7631         return rc;
7632 }
7633
7634 static int lfs_path2fid(int argc, char **argv)
7635 {
7636         struct option long_opts[] = {
7637                 { .val = 'p', .name = "parents", .has_arg = no_argument },
7638                 { .name = NULL } };
7639         char            **path;
7640         const char        short_opts[] = "p";
7641         const char       *sep = "";
7642         struct lu_fid     fid;
7643         int               rc = 0;
7644         bool              show_parents = false;
7645
7646         while ((rc = getopt_long(argc, argv, short_opts,
7647                                  long_opts, NULL)) != -1) {
7648                 switch (rc) {
7649                 case 'p':
7650                         show_parents = true;
7651                         break;
7652                 default:
7653                         fprintf(stderr,
7654                                 "%s path2fid: unrecognized option '%s'\n",
7655                                 progname, argv[optind - 1]);
7656                         return CMD_HELP;
7657                 }
7658         }
7659
7660         if (optind > argc - 1) {
7661                 fprintf(stderr, "%s path2fid: FILE... must be specified\n",
7662                         progname);
7663                 return CMD_HELP;
7664         }
7665         else if (optind < argc - 1)
7666                 sep = ": ";
7667
7668         rc = 0;
7669         for (path = argv + optind; *path != NULL; path++) {
7670                 int err = 0;
7671                 if (!show_parents) {
7672                         err = llapi_path2fid(*path, &fid);
7673                         if (!err)
7674                                 printf("%s%s"DFID"\n",
7675                                        *sep != '\0' ? *path : "", sep,
7676                                        PFID(&fid));
7677                 } else {
7678                         char            name[NAME_MAX + 1];
7679                         unsigned int    linkno = 0;
7680
7681                         while ((err = llapi_path2parent(*path, linkno, &fid,
7682                                                 name, sizeof(name))) == 0) {
7683                                 if (*sep != '\0' && linkno == 0)
7684                                         printf("%s%s", *path, sep);
7685
7686                                 printf("%s"DFID"/%s", linkno != 0 ? "\t" : "",
7687                                        PFID(&fid), name);
7688                                 linkno++;
7689                         }
7690
7691                         /* err == -ENODATA is end-of-loop */
7692                         if (linkno > 0 && err == -ENODATA) {
7693                                 printf("\n");
7694                                 err = 0;
7695                         }
7696                 }
7697
7698                 if (err) {
7699                         fprintf(stderr,
7700                                 "%s path2fid: cannot get %sfid for '%s': %s\n",
7701                                 progname, show_parents ? "parent " : "", *path,
7702                                 strerror(-err));
7703                         if (rc == 0) {
7704                                 rc = err;
7705                                 errno = -err;
7706                         }
7707                 }
7708         }
7709
7710         return rc;
7711 }
7712
7713 #define MAX_ERRNO       4095
7714 #define IS_ERR_VALUE(x) ((unsigned long)(x) >= (unsigned long)-MAX_ERRNO)
7715
7716 static int lfs_rmfid_and_show_errors(const char *device, struct fid_array *fa)
7717 {
7718         int rc, rc2 = 0, k;
7719
7720         rc = llapi_rmfid(device, fa);
7721         if (rc) {
7722                 fprintf(stderr, "rmfid(): rc = %d\n", rc);
7723                 return rc;
7724         }
7725
7726         for (k = 0; k < fa->fa_nr; k++) {
7727                 rc = (__s32)fa->fa_fids[k].f_ver;
7728                 if (!IS_ERR_VALUE(rc))
7729                         continue;
7730                 if (!rc2 && rc)
7731                         rc2 = rc;
7732                 if (!rc)
7733                         continue;
7734                 fa->fa_fids[k].f_ver = 0;
7735                 fprintf(stderr, "rmfid("DFID"): rc = %d\n",
7736                         PFID(&fa->fa_fids[k]), rc);
7737         }
7738
7739         return rc2;
7740 }
7741
7742 static int lfs_rmfid(int argc, char **argv)
7743 {
7744         char *fidstr, *device;
7745         int rc = 0, rc2, nr;
7746         struct fid_array *fa;
7747
7748         if (optind > argc - 1) {
7749                 fprintf(stderr, "%s rmfid: missing dirname\n", progname);
7750                 return CMD_HELP;
7751         }
7752
7753         device = argv[optind++];
7754
7755         nr = argc - optind;
7756         fa = malloc(offsetof(struct fid_array, fa_fids[nr + 1]));
7757         if (fa == NULL)
7758                 return -ENOMEM;
7759
7760         fa->fa_nr = 0;
7761         rc = 0;
7762         while (optind < argc) {
7763                 int found;
7764
7765                 fidstr = argv[optind++];
7766                 while (*fidstr == '[')
7767                         fidstr++;
7768                 found = sscanf(fidstr, SFID, RFID(&fa->fa_fids[fa->fa_nr]));
7769                 if (found != 3) {
7770                         fprintf(stderr, "unrecognized FID: %s\n",
7771                                 argv[optind - 1]);
7772                         exit(1);
7773                 }
7774                 fa->fa_nr++;
7775                 if (fa->fa_nr == OBD_MAX_FIDS_IN_ARRAY) {
7776                         /* start another batch */
7777                         rc2 = lfs_rmfid_and_show_errors(device, fa);
7778                         if (rc2 && !rc)
7779                                 rc = rc2;
7780                         fa->fa_nr = 0;
7781                 }
7782         }
7783         if (fa->fa_nr) {
7784                 rc2 = lfs_rmfid_and_show_errors(device, fa);
7785                 if (rc2 && !rc)
7786                         rc = rc2;
7787         }
7788
7789         return rc;
7790 }
7791
7792 static int lfs_data_version(int argc, char **argv)
7793 {
7794         char *path;
7795         __u64 data_version;
7796         int fd;
7797         int rc;
7798         int c;
7799         int data_version_flags = LL_DV_RD_FLUSH; /* Read by default */
7800
7801         if (argc < 2) {
7802                 fprintf(stderr, "%s data_version: FILE must be specified\n",
7803                         progname);
7804                 return CMD_HELP;
7805         }
7806
7807         while ((c = getopt(argc, argv, "nrw")) != -1) {
7808                 switch (c) {
7809                 case 'n':
7810                         data_version_flags = 0;
7811                         break;
7812                 case 'r':
7813                         data_version_flags |= LL_DV_RD_FLUSH;
7814                         break;
7815                 case 'w':
7816                         data_version_flags |= LL_DV_WR_FLUSH;
7817                         break;
7818                 default:
7819                         fprintf(stderr,
7820                                 "%s data_version: unrecognized option '%s'\n",
7821                                 progname, argv[optind - 1]);
7822                         return CMD_HELP;
7823                 }
7824         }
7825         if (optind == argc) {
7826                 fprintf(stderr, "%s data_version: FILE must be specified\n",
7827                         progname);
7828                 return CMD_HELP;
7829         }
7830
7831         path = argv[optind];
7832         fd = open(path, O_RDONLY);
7833         if (fd < 0) {
7834                 rc = -errno;
7835                 fprintf(stderr, "%s data_version: cannot open file '%s': %s\n",
7836                         progname, path, strerror(-rc));
7837                 return rc;
7838         }
7839
7840         rc = llapi_get_data_version(fd, &data_version, data_version_flags);
7841         if (rc < 0)
7842                 fprintf(stderr,
7843                         "%s data_version: cannot get version for '%s': %s\n",
7844                         progname, path, strerror(-rc));
7845         else
7846                 printf("%ju" "\n", (uintmax_t)data_version);
7847
7848         close(fd);
7849         return rc;
7850 }
7851
7852 static int lfs_hsm_state(int argc, char **argv)
7853 {
7854         int rc;
7855         int i = 1;
7856         char *path;
7857         struct hsm_user_state hus;
7858
7859         if (argc < 2)
7860                 return CMD_HELP;
7861
7862         do {
7863                 path = argv[i];
7864
7865                 rc = llapi_hsm_state_get(path, &hus);
7866                 if (rc) {
7867                         fprintf(stderr, "can't get hsm state for %s: %s\n",
7868                                 path, strerror(errno = -rc));
7869                         return rc;
7870                 }
7871
7872                 /* Display path name and status flags */
7873                 printf("%s: (0x%08x)", path, hus.hus_states);
7874
7875                 if (hus.hus_states & HS_RELEASED)
7876                         printf(" released");
7877                 if (hus.hus_states & HS_EXISTS)
7878                         printf(" exists");
7879                 if (hus.hus_states & HS_DIRTY)
7880                         printf(" dirty");
7881                 if (hus.hus_states & HS_ARCHIVED)
7882                         printf(" archived");
7883                 /* Display user-settable flags */
7884                 if (hus.hus_states & HS_NORELEASE)
7885                         printf(" never_release");
7886                 if (hus.hus_states & HS_NOARCHIVE)
7887                         printf(" never_archive");
7888                 if (hus.hus_states & HS_LOST)
7889                         printf(" lost_from_hsm");
7890
7891                 if (hus.hus_archive_id != 0)
7892                         printf(", archive_id:%d", hus.hus_archive_id);
7893                 printf("\n");
7894
7895         } while (++i < argc);
7896
7897         return 0;
7898 }
7899
7900 #define LFS_HSM_SET   0
7901 #define LFS_HSM_CLEAR 1
7902
7903 /**
7904  * Generic function to set or clear HSM flags.
7905  * Used by hsm_set and hsm_clear.
7906  *
7907  * @mode  if LFS_HSM_SET, set the flags, if LFS_HSM_CLEAR, clear the flags.
7908  */
7909 static int lfs_hsm_change_flags(int argc, char **argv, int mode)
7910 {
7911         struct option long_opts[] = {
7912         { .val = 'A',   .name = "archived",     .has_arg = no_argument },
7913         { .val = 'a',   .name = "noarchive",    .has_arg = no_argument },
7914         { .val = 'd',   .name = "dirty",        .has_arg = no_argument },
7915         { .val = 'e',   .name = "exists",       .has_arg = no_argument },
7916         { .val = 'l',   .name = "lost",         .has_arg = no_argument },
7917         { .val = 'r',   .name = "norelease",    .has_arg = no_argument },
7918         { .val = 'i',   .name = "archive-id",   .has_arg = required_argument },
7919         { .name = NULL } };
7920         char short_opts[] = "lraAdei:";
7921         __u64 mask = 0;
7922         int c, rc;
7923         char *path;
7924         __u32 archive_id = 0;
7925         char *end = NULL;
7926
7927         if (argc < 3)
7928                 return CMD_HELP;
7929
7930         while ((c = getopt_long(argc, argv, short_opts,
7931                                 long_opts, NULL)) != -1) {
7932                 switch (c) {
7933                 case 'l':
7934                         mask |= HS_LOST;
7935                         break;
7936                 case 'a':
7937                         mask |= HS_NOARCHIVE;
7938                         break;
7939                 case 'A':
7940                         mask |= HS_ARCHIVED;
7941                         break;
7942                 case 'r':
7943                         mask |= HS_NORELEASE;
7944                         break;
7945                 case 'd':
7946                         mask |= HS_DIRTY;
7947                         break;
7948                 case 'e':
7949                         mask |= HS_EXISTS;
7950                         break;
7951                 case 'i':
7952                         archive_id = strtol(optarg, &end, 10);
7953                         if (*end != '\0') {
7954                                 fprintf(stderr, "invalid archive_id: '%s'\n",
7955                                         end);
7956                                 return CMD_HELP;
7957                         }
7958                         break;
7959                 case '?':
7960                         return CMD_HELP;
7961                 default:
7962                         fprintf(stderr, "error: %s: option '%s' unrecognized\n",
7963                                 argv[0], argv[optind - 1]);
7964                         return CMD_HELP;
7965                 }
7966         }
7967
7968         /* User should have specified a flag */
7969         if (mask == 0)
7970                 return CMD_HELP;
7971
7972         while (optind < argc) {
7973
7974                 path = argv[optind];
7975
7976                 /* If mode == 0, this means we apply the mask. */
7977                 if (mode == LFS_HSM_SET)
7978                         rc = llapi_hsm_state_set(path, mask, 0, archive_id);
7979                 else
7980                         rc = llapi_hsm_state_set(path, 0, mask, 0);
7981
7982                 if (rc != 0) {
7983                         fprintf(stderr, "Can't change hsm flags for %s: %s\n",
7984                                 path, strerror(errno = -rc));
7985                         return rc;
7986                 }
7987                 optind++;
7988         }
7989
7990         return 0;
7991 }
7992
7993 static int lfs_hsm_action(int argc, char **argv)
7994 {
7995         int                              rc;
7996         int                              i = 1;
7997         char                            *path;
7998         struct hsm_current_action        hca;
7999         struct hsm_extent                he;
8000         enum hsm_user_action             hua;
8001         enum hsm_progress_states         hps;
8002
8003         if (argc < 2)
8004                 return CMD_HELP;
8005
8006         do {
8007                 path = argv[i];
8008
8009                 rc = llapi_hsm_current_action(path, &hca);
8010                 if (rc) {
8011                         fprintf(stderr, "can't get hsm action for %s: %s\n",
8012                                 path, strerror(errno = -rc));
8013                         return rc;
8014                 }
8015                 he = hca.hca_location;
8016                 hua = hca.hca_action;
8017                 hps = hca.hca_state;
8018
8019                 printf("%s: %s", path, hsm_user_action2name(hua));
8020
8021                 /* Skip file without action */
8022                 if (hca.hca_action == HUA_NONE) {
8023                         printf("\n");
8024                         continue;
8025                 }
8026
8027                 printf(" %s ", hsm_progress_state2name(hps));
8028
8029                 if ((hps == HPS_RUNNING) &&
8030                     (hua == HUA_ARCHIVE || hua == HUA_RESTORE))
8031                         printf("(%llu bytes moved)\n",
8032                                (unsigned long long)he.length);
8033                 else if ((he.offset + he.length) == LUSTRE_EOF)
8034                         printf("(from %llu to EOF)\n",
8035                                (unsigned long long)he.offset);
8036                 else
8037                         printf("(from %llu to %llu)\n",
8038                                (unsigned long long)he.offset,
8039                                (unsigned long long)(he.offset + he.length));
8040
8041         } while (++i < argc);
8042
8043         return 0;
8044 }
8045
8046 static int lfs_hsm_set(int argc, char **argv)
8047 {
8048         return lfs_hsm_change_flags(argc, argv, LFS_HSM_SET);
8049 }
8050
8051 static int lfs_hsm_clear(int argc, char **argv)
8052 {
8053         return lfs_hsm_change_flags(argc, argv, LFS_HSM_CLEAR);
8054 }
8055
8056 /**
8057  * Check file state and return its fid, to be used by lfs_hsm_request().
8058  *
8059  * \param[in]     file      Path to file to check
8060  * \param[in,out] fid       Pointer to allocated lu_fid struct.
8061  * \param[in,out] last_dev  Pointer to last device id used.
8062  *
8063  * \return 0 on success.
8064  */
8065 static int lfs_hsm_prepare_file(const char *file, struct lu_fid *fid,
8066                                 dev_t *last_dev)
8067 {
8068         struct stat     st;
8069         int             rc;
8070
8071         rc = lstat(file, &st);
8072         if (rc) {
8073                 fprintf(stderr, "Cannot stat %s: %s\n", file, strerror(errno));
8074                 return -errno;
8075         }
8076         /* Checking for regular file as archiving as posix copytool
8077          * rejects archiving files other than regular files
8078          */
8079         if (!S_ISREG(st.st_mode)) {
8080                 fprintf(stderr, "error: \"%s\" is not a regular file\n", file);
8081                 return CMD_HELP;
8082         }
8083         /* A request should be ... */
8084         if (*last_dev != st.st_dev && *last_dev != 0) {
8085                 fprintf(stderr, "All files should be "
8086                         "on the same filesystem: %s\n", file);
8087                 return -EINVAL;
8088         }
8089         *last_dev = st.st_dev;
8090
8091         rc = llapi_path2fid(file, fid);
8092         if (rc) {
8093                 fprintf(stderr, "Cannot read FID of %s: %s\n",
8094                         file, strerror(-rc));
8095                 return rc;
8096         }
8097         return 0;
8098 }
8099
8100 /* Fill an HSM HUR item with a given file name.
8101  *
8102  * If mntpath is set, then the filename is actually a FID, and no
8103  * lookup on the filesystem will be performed.
8104  *
8105  * \param[in]  hur         the user request to fill
8106  * \param[in]  idx         index of the item inside the HUR to fill
8107  * \param[in]  mntpath     mountpoint of Lustre
8108  * \param[in]  fname       filename (if mtnpath is NULL)
8109  *                         or FID (if mntpath is set)
8110  * \param[in]  last_dev    pointer to last device id used
8111  *
8112  * \retval 0 on success
8113  * \retval CMD_HELP or a negative errno on error
8114  */
8115 static int fill_hur_item(struct hsm_user_request *hur, unsigned int idx,
8116                          const char *mntpath, const char *fname,
8117                          dev_t *last_dev)
8118 {
8119         struct hsm_user_item *hui = &hur->hur_user_item[idx];
8120         int rc;
8121
8122         hui->hui_extent.length = -1;
8123
8124         if (mntpath != NULL) {
8125                 if (*fname == '[')
8126                         fname++;
8127                 rc = sscanf(fname, SFID, RFID(&hui->hui_fid));
8128                 if (rc == 3) {
8129                         rc = 0;
8130                 } else {
8131                         fprintf(stderr, "hsm: '%s' is not a valid FID\n",
8132                                 fname);
8133                         rc = -EINVAL;
8134                 }
8135         } else {
8136                 rc = lfs_hsm_prepare_file(fname, &hui->hui_fid, last_dev);
8137         }
8138
8139         if (rc == 0)
8140                 hur->hur_request.hr_itemcount++;
8141
8142         return rc;
8143 }
8144
8145 static int lfs_hsm_request(int argc, char **argv, int action)
8146 {
8147         struct option long_opts[] = {
8148         { .val = 'a',   .name = "archive",      .has_arg = required_argument },
8149         { .val = 'D',   .name = "data",         .has_arg = required_argument },
8150         { .val = 'l',   .name = "filelist",     .has_arg = required_argument },
8151         { .val = 'm',   .name = "mntpath",      .has_arg = required_argument },
8152         { .name = NULL } };
8153         dev_t                    last_dev = 0;
8154         char                     short_opts[] = "l:D:a:m:";
8155         struct hsm_user_request *hur, *oldhur;
8156         int                      c, i;
8157         size_t                   len;
8158         int                      nbfile;
8159         char                    *line = NULL;
8160         char                    *filelist = NULL;
8161         char                     fullpath[PATH_MAX];
8162         char                    *opaque = NULL;
8163         int                      opaque_len = 0;
8164         int                      archive_id = 0;
8165         FILE                    *fp;
8166         int                      nbfile_alloc = 0;
8167         char                    *some_file = NULL;
8168         char                    *mntpath = NULL;
8169         int                      rc;
8170
8171         if (argc < 2)
8172                 return CMD_HELP;
8173
8174         while ((c = getopt_long(argc, argv, short_opts,
8175                                 long_opts, NULL)) != -1) {
8176                 switch (c) {
8177                 case 'l':
8178                         filelist = optarg;
8179                         break;
8180                 case 'D':
8181                         opaque = optarg;
8182                         break;
8183                 case 'a':
8184                         if (action != HUA_ARCHIVE &&
8185                             action != HUA_REMOVE) {
8186                                 fprintf(stderr,
8187                                         "error: -a is supported only "
8188                                         "when archiving or removing\n");
8189                                 return CMD_HELP;
8190                         }
8191                         archive_id = atoi(optarg);
8192                         break;
8193                 case 'm':
8194                         if (some_file == NULL) {
8195                                 mntpath = optarg;
8196                                 some_file = strdup(optarg);
8197                         }
8198                         break;
8199                 case '?':
8200                         return CMD_HELP;
8201                 default:
8202                         fprintf(stderr, "error: %s: option '%s' unrecognized\n",
8203                                 argv[0], argv[optind - 1]);
8204                         return CMD_HELP;
8205                 }
8206         }
8207
8208         /* All remaining args are files, so we have at least nbfile */
8209         nbfile = argc - optind;
8210
8211         if ((nbfile == 0) && (filelist == NULL))
8212                 return CMD_HELP;
8213
8214         if (opaque != NULL)
8215                 opaque_len = strlen(opaque);
8216
8217         /* Alloc the request structure with enough place to store all files
8218          * from command line. */
8219         hur = llapi_hsm_user_request_alloc(nbfile, opaque_len);
8220         if (hur == NULL) {
8221                 fprintf(stderr, "Cannot create the request: %s\n",
8222                         strerror(errno));
8223                 return errno;
8224         }
8225         nbfile_alloc = nbfile;
8226
8227         hur->hur_request.hr_action = action;
8228         hur->hur_request.hr_archive_id = archive_id;
8229         hur->hur_request.hr_flags = 0;
8230
8231         /* All remaining args are files, add them */
8232         if (nbfile != 0 && some_file == NULL)
8233                 some_file = strdup(argv[optind]);
8234
8235         for (i = 0; i < nbfile; i++) {
8236                 rc = fill_hur_item(hur, i, mntpath, argv[optind + i],
8237                                    &last_dev);
8238                 if (rc)
8239                         goto out_free;
8240         }
8241
8242         /* from here stop using nb_file, use hur->hur_request.hr_itemcount */
8243
8244         /* If a filelist was specified, read the filelist from it. */
8245         if (filelist != NULL) {
8246                 fp = fopen(filelist, "r");
8247                 if (fp == NULL) {
8248                         fprintf(stderr, "Cannot read the file list %s: %s\n",
8249                                 filelist, strerror(errno));
8250                         rc = -errno;
8251                         goto out_free;
8252                 }
8253
8254                 while ((rc = getline(&line, &len, fp)) != -1) {
8255                         /* If allocated buffer was too small, get something
8256                          * larger */
8257                         if (nbfile_alloc <= hur->hur_request.hr_itemcount) {
8258                                 ssize_t size;
8259
8260                                 nbfile_alloc = nbfile_alloc * 2 + 1;
8261                                 oldhur = hur;
8262                                 hur = llapi_hsm_user_request_alloc(nbfile_alloc,
8263                                                                    opaque_len);
8264                                 if (hur == NULL) {
8265                                         fprintf(stderr, "hsm: cannot allocate "
8266                                                 "the request: %s\n",
8267                                                 strerror(errno));
8268                                         hur = oldhur;
8269                                         rc = -errno;
8270                                         fclose(fp);
8271                                         goto out_free;
8272                                 }
8273                                 size = hur_len(oldhur);
8274                                 if (size < 0) {
8275                                         fprintf(stderr, "hsm: cannot allocate "
8276                                                 "%u files + %u bytes data\n",
8277                                             oldhur->hur_request.hr_itemcount,
8278                                             oldhur->hur_request.hr_data_len);
8279                                         free(hur);
8280                                         hur = oldhur;
8281                                         rc = -E2BIG;
8282                                         fclose(fp);
8283                                         goto out_free;
8284                                 }
8285                                 memcpy(hur, oldhur, size);
8286                                 free(oldhur);
8287                         }
8288
8289                         /* Chop CR */
8290                         if (line[strlen(line) - 1] == '\n')
8291                                 line[strlen(line) - 1] = '\0';
8292
8293                         rc = fill_hur_item(hur, hur->hur_request.hr_itemcount,
8294                                            mntpath, line, &last_dev);
8295                         if (rc) {
8296                                 fclose(fp);
8297                                 goto out_free;
8298                         }
8299
8300                         if (some_file == NULL) {
8301                                 some_file = line;
8302                                 line = NULL;
8303                         }
8304                 }
8305
8306                 rc = fclose(fp);
8307                 free(line);
8308         }
8309
8310         /* If a --data was used, add it to the request */
8311         hur->hur_request.hr_data_len = opaque_len;
8312         if (opaque != NULL)
8313                 memcpy(hur_data(hur), opaque, opaque_len);
8314
8315         /* Send the HSM request */
8316         if (realpath(some_file, fullpath) == NULL) {
8317                 fprintf(stderr, "Could not find path '%s': %s\n",
8318                         some_file, strerror(errno));
8319         }
8320         rc = llapi_hsm_request(fullpath, hur);
8321         if (rc) {
8322                 fprintf(stderr, "Cannot send HSM request (use of %s): %s\n",
8323                         some_file, strerror(-rc));
8324                 goto out_free;
8325         }
8326
8327 out_free:
8328         free(some_file);
8329         free(hur);
8330         return rc;
8331 }
8332
8333 static int lfs_hsm_archive(int argc, char **argv)
8334 {
8335         return lfs_hsm_request(argc, argv, HUA_ARCHIVE);
8336 }
8337
8338 static int lfs_hsm_restore(int argc, char **argv)
8339 {
8340         return lfs_hsm_request(argc, argv, HUA_RESTORE);
8341 }
8342
8343 static int lfs_hsm_release(int argc, char **argv)
8344 {
8345         return lfs_hsm_request(argc, argv, HUA_RELEASE);
8346 }
8347
8348 static int lfs_hsm_remove(int argc, char **argv)
8349 {
8350         return lfs_hsm_request(argc, argv, HUA_REMOVE);
8351 }
8352
8353 static int lfs_hsm_cancel(int argc, char **argv)
8354 {
8355         return lfs_hsm_request(argc, argv, HUA_CANCEL);
8356 }
8357
8358 static int lfs_swap_layouts(int argc, char **argv)
8359 {
8360         if (argc != 3)
8361                 return CMD_HELP;
8362
8363         return llapi_swap_layouts(argv[1], argv[2], 0, 0,
8364                                   SWAP_LAYOUTS_KEEP_MTIME |
8365                                   SWAP_LAYOUTS_KEEP_ATIME);
8366 }
8367
8368 static const char *const ladvise_names[] = LU_LADVISE_NAMES;
8369
8370 static const char *const lock_mode_names[] = LOCK_MODE_NAMES;
8371
8372 int lfs_get_mode(const char *string)
8373 {
8374         enum lock_mode_user mode;
8375
8376         for (mode = 0; mode < ARRAY_SIZE(lock_mode_names); mode++) {
8377                 if (lock_mode_names[mode] == NULL)
8378                         continue;
8379                 if (strcmp(string, lock_mode_names[mode]) == 0)
8380                         return mode;
8381         }
8382
8383         return -EINVAL;
8384 }
8385
8386 static enum lu_ladvise_type lfs_get_ladvice(const char *string)
8387 {
8388         enum lu_ladvise_type advice;
8389
8390         for (advice = 0;
8391              advice < ARRAY_SIZE(ladvise_names); advice++) {
8392                 if (ladvise_names[advice] == NULL)
8393                         continue;
8394                 if (strcmp(string, ladvise_names[advice]) == 0)
8395                         return advice;
8396         }
8397
8398         return LU_LADVISE_INVALID;
8399 }
8400
8401 static int lfs_ladvise(int argc, char **argv)
8402 {
8403         struct option long_opts[] = {
8404         { .val = 'a',   .name = "advice",       .has_arg = required_argument },
8405         { .val = 'b',   .name = "background",   .has_arg = no_argument },
8406         { .val = 'e',   .name = "end",          .has_arg = required_argument },
8407         { .val = 'l',   .name = "length",       .has_arg = required_argument },
8408         { .val = 'm',   .name = "mode",         .has_arg = required_argument },
8409         { .val = 's',   .name = "start",        .has_arg = required_argument },
8410         { .val = 'u',   .name = "unset",        .has_arg = no_argument },
8411         { .name = NULL } };
8412         char                     short_opts[] = "a:be:l:m:s:u";
8413         int                      c;
8414         int                      rc = 0;
8415         const char              *path;
8416         int                      fd;
8417         struct llapi_lu_ladvise  advice;
8418         enum lu_ladvise_type     advice_type = LU_LADVISE_INVALID;
8419         unsigned long long       start = 0;
8420         unsigned long long       end = LUSTRE_EOF;
8421         unsigned long long       length = 0;
8422         unsigned long long       size_units;
8423         unsigned long long       flags = 0;
8424         int                      mode = 0;
8425
8426         optind = 0;
8427         while ((c = getopt_long(argc, argv, short_opts,
8428                                 long_opts, NULL)) != -1) {
8429                 switch (c) {
8430                 case 'a':
8431                         advice_type = lfs_get_ladvice(optarg);
8432                         if (advice_type == LU_LADVISE_INVALID) {
8433                                 fprintf(stderr, "%s: invalid advice type "
8434                                         "'%s'\n", argv[0], optarg);
8435                                 fprintf(stderr, "Valid types:");
8436
8437                                 for (advice_type = 0;
8438                                      advice_type < ARRAY_SIZE(ladvise_names);
8439                                      advice_type++) {
8440                                         if (ladvise_names[advice_type] == NULL)
8441                                                 continue;
8442                                         fprintf(stderr, " %s",
8443                                                 ladvise_names[advice_type]);
8444                                 }
8445                                 fprintf(stderr, "\n");
8446
8447                                 return CMD_HELP;
8448                         }
8449                         break;
8450                 case 'b':
8451                         flags |= LF_ASYNC;
8452                         break;
8453                 case 'u':
8454                         flags |= LF_UNSET;
8455                         break;
8456                 case 'e':
8457                         size_units = 1;
8458                         rc = llapi_parse_size(optarg, &end,
8459                                               &size_units, 0);
8460                         if (rc) {
8461                                 fprintf(stderr, "%s: bad end offset '%s'\n",
8462                                         argv[0], optarg);
8463                                 return CMD_HELP;
8464                         }
8465                         break;
8466                 case 's':
8467                         size_units = 1;
8468                         rc = llapi_parse_size(optarg, &start,
8469                                               &size_units, 0);
8470                         if (rc) {
8471                                 fprintf(stderr, "%s: bad start offset "
8472                                         "'%s'\n", argv[0], optarg);
8473                                 return CMD_HELP;
8474                         }
8475                         break;
8476                 case 'l':
8477                         size_units = 1;
8478                         rc = llapi_parse_size(optarg, &length,
8479                                               &size_units, 0);
8480                         if (rc) {
8481                                 fprintf(stderr, "%s: bad length '%s'\n",
8482                                         argv[0], optarg);
8483                                 return CMD_HELP;
8484                         }
8485                         break;
8486                 case 'm':
8487                         mode = lfs_get_mode(optarg);
8488                         if (mode < 0) {
8489                                 fprintf(stderr, "%s: bad mode '%s', valid "
8490                                                  "modes are READ or WRITE\n",
8491                                         argv[0], optarg);
8492                                 return CMD_HELP;
8493                         }
8494                         break;
8495                 case '?':
8496                         return CMD_HELP;
8497                 default:
8498                         fprintf(stderr, "%s: option '%s' unrecognized\n",
8499                                 argv[0], argv[optind - 1]);
8500                         return CMD_HELP;
8501                 }
8502         }
8503
8504         if (advice_type == LU_LADVISE_INVALID) {
8505                 fprintf(stderr, "%s: please give an advice type\n", argv[0]);
8506                 fprintf(stderr, "Valid types:");
8507                 for (advice_type = 0; advice_type < ARRAY_SIZE(ladvise_names);
8508                      advice_type++) {
8509                         if (ladvise_names[advice_type] == NULL)
8510                                 continue;
8511                         fprintf(stderr, " %s", ladvise_names[advice_type]);
8512                 }
8513                 fprintf(stderr, "\n");
8514                 return CMD_HELP;
8515         }
8516
8517         if (advice_type == LU_LADVISE_LOCKNOEXPAND) {
8518                 fprintf(stderr, "%s: Lock no expand advice is a per file "
8519                                  "descriptor advice, so when called from lfs, "
8520                                  "it does nothing.\n", argv[0]);
8521                 return CMD_HELP;
8522         }
8523
8524         if (argc <= optind) {
8525                 fprintf(stderr, "%s: please give one or more file names\n",
8526                         argv[0]);
8527                 return CMD_HELP;
8528         }
8529
8530         if (end != LUSTRE_EOF && length != 0 && end != start + length) {
8531                 fprintf(stderr, "%s: conflicting arguments of -l and -e\n",
8532                         argv[0]);
8533                 return CMD_HELP;
8534         }
8535
8536         if (end == LUSTRE_EOF && length != 0)
8537                 end = start + length;
8538
8539         if (end <= start) {
8540                 fprintf(stderr, "%s: range [%llu, %llu] is invalid\n",
8541                         argv[0], start, end);
8542                 return CMD_HELP;
8543         }
8544
8545         if (advice_type != LU_LADVISE_LOCKAHEAD && mode != 0) {
8546                 fprintf(stderr, "%s: mode is only valid with lockahead\n",
8547                         argv[0]);
8548                 return CMD_HELP;
8549         }
8550
8551         if (advice_type == LU_LADVISE_LOCKAHEAD && mode == 0) {
8552                 fprintf(stderr, "%s: mode is required with lockahead\n",
8553                         argv[0]);
8554                 return CMD_HELP;
8555         }
8556
8557         while (optind < argc) {
8558                 int rc2;
8559
8560                 path = argv[optind++];
8561
8562                 fd = open(path, O_RDONLY);
8563                 if (fd < 0) {
8564                         fprintf(stderr, "%s: cannot open file '%s': %s\n",
8565                                 argv[0], path, strerror(errno));
8566                         rc2 = -errno;
8567                         goto next;
8568                 }
8569
8570                 advice.lla_start = start;
8571                 advice.lla_end = end;
8572                 advice.lla_advice = advice_type;
8573                 advice.lla_value1 = 0;
8574                 advice.lla_value2 = 0;
8575                 advice.lla_value3 = 0;
8576                 advice.lla_value4 = 0;
8577                 if (advice_type == LU_LADVISE_LOCKAHEAD) {
8578                         advice.lla_lockahead_mode = mode;
8579                         advice.lla_peradvice_flags = flags;
8580                 }
8581
8582                 rc2 = llapi_ladvise(fd, flags, 1, &advice);
8583                 close(fd);
8584                 if (rc2 < 0) {
8585                         fprintf(stderr, "%s: cannot give advice '%s' to file "
8586                                 "'%s': %s\n", argv[0],
8587                                 ladvise_names[advice_type],
8588                                 path, strerror(errno));
8589
8590                         goto next;
8591                 }
8592
8593 next:
8594                 if (rc == 0 && rc2 < 0)
8595                         rc = rc2;
8596         }
8597         return rc;
8598 }
8599
8600 static const char *const heat_names[] = LU_HEAT_NAMES;
8601
8602 static int lfs_heat_get(int argc, char **argv)
8603 {
8604         struct lu_heat *heat;
8605         int rc = 0, rc2;
8606         char *path;
8607         int fd;
8608         int i;
8609
8610         if (argc <= 1)
8611                 return CMD_HELP;
8612
8613         heat = calloc(sizeof(*heat) + sizeof(__u64) * OBD_HEAT_COUNT, 1);
8614         if (!heat) {
8615                 fprintf(stderr, "%s: memory allocation failed\n", argv[0]);
8616                 return -ENOMEM;
8617         }
8618
8619         optind = 1;
8620         while (optind < argc) {
8621                 path = argv[optind++];
8622
8623                 fd = open(path, O_RDONLY);
8624                 if (fd < 0) {
8625                         fprintf(stderr, "%s: cannot open file '%s': %s\n",
8626                                 argv[0], path, strerror(errno));
8627                         rc2 = -errno;
8628                         goto next;
8629                 }
8630
8631                 heat->lh_count = OBD_HEAT_COUNT;
8632                 rc2 = llapi_heat_get(fd, heat);
8633                 close(fd);
8634                 if (rc2 < 0) {
8635                         fprintf(stderr, "%s: cannot get heat of file '%s'"
8636                                 ": %s\n", argv[0], path, strerror(errno));
8637                         goto next;
8638                 }
8639
8640                 printf("flags: %x\n", heat->lh_flags);
8641                 for (i = 0; i < heat->lh_count; i++)
8642                         printf("%s: %llu\n", heat_names[i], heat->lh_heat[i]);
8643 next:
8644                 if (rc == 0 && rc2 < 0)
8645                         rc = rc2;
8646         }
8647
8648         free(heat);
8649         return rc;
8650 }
8651
8652 static int lfs_heat_set(int argc, char **argv)
8653 {
8654         struct option long_opts[] = {
8655         { .val = 'c',   .name = "clear",        .has_arg = no_argument },
8656         { .val = 'o',   .name = "off",          .has_arg = no_argument },
8657         { .val = 'O',   .name = "on",           .has_arg = no_argument },
8658         { .name = NULL } };
8659         enum lu_heat_flag flags = 0;
8660         int rc = 0, rc2;
8661         char *path;
8662         int fd;
8663         int c;
8664
8665         if (argc <= 1)
8666                 return CMD_HELP;
8667
8668         optind = 0;
8669         while ((c = getopt_long(argc, argv, "coO", long_opts, NULL)) != -1) {
8670                 switch (c) {
8671                 case 'c':
8672                         flags |= LU_HEAT_FLAG_CLEAR;
8673                         break;
8674                 case 'o':
8675                         flags |= LU_HEAT_FLAG_CLEAR;
8676                         flags |= LU_HEAT_FLAG_OFF;
8677                         break;
8678                 case 'O':
8679                         flags &= ~LU_HEAT_FLAG_OFF;
8680                         break;
8681                 case '?':
8682                         return CMD_HELP;
8683                 default:
8684                         fprintf(stderr, "%s: option '%s' unrecognized\n",
8685                                 argv[0], argv[optind - 1]);
8686                         return CMD_HELP;
8687                 }
8688         }
8689
8690         if (argc <= optind) {
8691                 fprintf(stderr, "%s: please give one or more file names\n",
8692                         argv[0]);
8693                 return CMD_HELP;
8694         }
8695
8696         while (optind < argc) {
8697                 path = argv[optind++];
8698
8699                 fd = open(path, O_RDONLY);
8700                 if (fd < 0) {
8701                         fprintf(stderr, "%s: cannot open file '%s': %s\n",
8702                                 argv[0], path, strerror(errno));
8703                         rc2 = -errno;
8704                         goto next;
8705                 }
8706
8707                 rc2 = llapi_heat_set(fd, flags);
8708                 close(fd);
8709                 if (rc2 < 0) {
8710                         fprintf(stderr, "%s: cannot setflags heat of file '%s'"
8711                                 ": %s\n", argv[0], path, strerror(errno));
8712                         goto next;
8713                 }
8714 next:
8715                 if (rc == 0 && rc2 < 0)
8716                         rc = rc2;
8717         }
8718         return rc;
8719 }
8720
8721 /** The input string contains a comma delimited list of component ids and
8722  * ranges, for example "1,2-4,7".
8723  */
8724 static int parse_mirror_ids(__u16 *ids, int size, char *arg)
8725 {
8726         bool end_of_loop = false;
8727         char *ptr = NULL;
8728         int nr = 0;
8729         int rc;
8730
8731         if (arg == NULL)
8732                 return -EINVAL;
8733
8734         while (!end_of_loop) {
8735                 int start_index;
8736                 int end_index;
8737                 int i;
8738                 char *endptr = NULL;
8739
8740                 rc = -EINVAL;
8741                 ptr = strchrnul(arg, ',');
8742                 end_of_loop = *ptr == '\0';
8743                 *ptr = '\0';
8744
8745                 start_index = strtol(arg, &endptr, 0);
8746                 if (endptr == arg) /* no data at all */
8747                         break;
8748                 if (*endptr != '-' && *endptr != '\0') /* has invalid data */
8749                         break;
8750                 if (start_index < 0)
8751                         break;
8752
8753                 end_index = start_index;
8754                 if (*endptr == '-') {
8755                         end_index = strtol(endptr + 1, &endptr, 0);
8756                         if (*endptr != '\0')
8757                                 break;
8758                         if (end_index < start_index)
8759                                 break;
8760                 }
8761
8762                 for (i = start_index; i <= end_index && size > 0; i++) {
8763                         int j;
8764
8765                         /* remove duplicate */
8766                         for (j = 0; j < nr; j++) {
8767                                 if (ids[j] == i)
8768                                         break;
8769                         }
8770                         if (j == nr) { /* no duplicate */
8771                                 ids[nr++] = i;
8772                                 --size;
8773                         }
8774                 }
8775
8776                 if (size == 0 && i < end_index)
8777                         break;
8778
8779                 *ptr = ',';
8780                 arg = ++ptr;
8781                 rc = 0;
8782         }
8783         if (!end_of_loop && ptr != NULL)
8784                 *ptr = ',';
8785
8786         return rc < 0 ? rc : nr;
8787 }
8788
8789 /**
8790  * struct verify_mirror_id - Mirror id to be verified.
8791  * @mirror_id:   A specified mirror id.
8792  * @is_valid_id: @mirror_id is valid or not in the mirrored file.
8793  */
8794 struct verify_mirror_id {
8795         __u16 mirror_id;
8796         bool is_valid_id;
8797 };
8798
8799 /**
8800  * compare_mirror_ids() - Compare mirror ids.
8801  * @layout: Mirror component list.
8802  * @cbdata: Callback data in verify_mirror_id structure.
8803  *
8804  * This is a callback function called by llapi_layout_comp_iterate()
8805  * to compare the specified mirror id with the one in the current
8806  * component of @layout. If they are the same, then the specified
8807  * mirror id is valid.
8808  *
8809  * Return: a negative error code on failure or
8810  *         LLAPI_LAYOUT_ITER_CONT: Proceed iteration
8811  *         LLAPI_LAYOUT_ITER_STOP: Stop iteration
8812  */
8813 static inline
8814 int compare_mirror_ids(struct llapi_layout *layout, void *cbdata)
8815 {
8816         struct verify_mirror_id *mirror_id_cbdata =
8817                                  (struct verify_mirror_id *)cbdata;
8818         uint32_t mirror_id;
8819         int rc = 0;
8820
8821         rc = llapi_layout_mirror_id_get(layout, &mirror_id);
8822         if (rc < 0) {
8823                 rc = -errno;
8824                 fprintf(stderr,
8825                         "%s: llapi_layout_mirror_id_get failed: %s.\n",
8826                         progname, strerror(errno));
8827                 return rc;
8828         }
8829
8830         if (mirror_id_cbdata->mirror_id == mirror_id) {
8831                 mirror_id_cbdata->is_valid_id = true;
8832                 return LLAPI_LAYOUT_ITER_STOP;
8833         }
8834
8835         return LLAPI_LAYOUT_ITER_CONT;
8836 }
8837
8838 /**
8839  * verify_mirror_ids() - Verify specified mirror ids.
8840  * @fname:      Mirrored file name.
8841  * @mirror_ids: Specified mirror ids to be verified.
8842  * @ids_nr:     Number of specified mirror ids.
8843  *
8844  * This function verifies that specified @mirror_ids are valid
8845  * in the mirrored file @fname.
8846  *
8847  * Return: 0 on success or a negative error code on failure.
8848  */
8849 static inline
8850 int verify_mirror_ids(const char *fname, __u16 *mirror_ids, int ids_nr)
8851 {
8852         struct llapi_layout *layout = NULL;
8853         struct verify_mirror_id mirror_id_cbdata = { 0 };
8854         struct stat stbuf;
8855         uint32_t flr_state;
8856         int i;
8857         int fd;
8858         int rc = 0;
8859         int rc2 = 0;
8860
8861         if (ids_nr <= 0)
8862                 return -EINVAL;
8863
8864         if (stat(fname, &stbuf) < 0) {
8865                 fprintf(stderr, "%s: cannot stat file '%s': %s.\n",
8866                         progname, fname, strerror(errno));
8867                 rc = -errno;
8868                 goto error;
8869         }
8870
8871         if (!S_ISREG(stbuf.st_mode)) {
8872                 fprintf(stderr, "%s: '%s' is not a regular file.\n",
8873                         progname, fname);
8874                 rc = -EINVAL;
8875                 goto error;
8876         }
8877
8878         fd = open(fname, O_DIRECT | O_RDONLY);
8879         if (fd < 0) {
8880                 fprintf(stderr, "%s: cannot open '%s': %s.\n",
8881                         progname, fname, strerror(errno));
8882                 rc = -errno;
8883                 goto error;
8884         }
8885
8886         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
8887         if (rc < 0) {
8888                 fprintf(stderr, "%s: '%s' llapi_lease_acquire failed: %s.\n",
8889                         progname, fname, strerror(errno));
8890                 goto close_fd;
8891         }
8892
8893         layout = llapi_layout_get_by_fd(fd, 0);
8894         if (layout == NULL) {
8895                 fprintf(stderr, "%s: '%s' llapi_layout_get_by_fd failed: %s.\n",
8896                         progname, fname, strerror(errno));
8897                 rc = -errno;
8898                 llapi_lease_release(fd);
8899                 goto close_fd;
8900         }
8901
8902         rc = llapi_layout_flags_get(layout, &flr_state);
8903         if (rc < 0) {
8904                 fprintf(stderr, "%s: '%s' llapi_layout_flags_get failed: %s.\n",
8905                         progname, fname, strerror(errno));
8906                 rc = -errno;
8907                 goto free_layout;
8908         }
8909
8910         flr_state &= LCM_FL_FLR_MASK;
8911         switch (flr_state) {
8912         case LCM_FL_NONE:
8913                 rc = -EINVAL;
8914                 fprintf(stderr, "%s: '%s' file state error: %s.\n",
8915                         progname, fname, llapi_layout_flags_string(flr_state));
8916                 goto free_layout;
8917         default:
8918                 break;
8919         }
8920
8921         rc2 = 0;
8922         for (i = 0; i < ids_nr; i++) {
8923                 mirror_id_cbdata.mirror_id = mirror_ids[i];
8924                 mirror_id_cbdata.is_valid_id = false;
8925
8926                 rc = llapi_layout_comp_iterate(layout, compare_mirror_ids,
8927                                                &mirror_id_cbdata);
8928                 if (rc < 0) {
8929                         rc = -errno;
8930                         fprintf(stderr,
8931                                 "%s: '%s' failed to verify mirror id: %u.\n",
8932                                 progname, fname, mirror_ids[i]);
8933                         goto free_layout;
8934                 }
8935
8936                 if (!mirror_id_cbdata.is_valid_id) {
8937                         rc2 = -EINVAL;
8938                         fprintf(stderr,
8939                                 "%s: '%s' invalid specified mirror id: %u.\n",
8940                                 progname, fname, mirror_ids[i]);
8941                 }
8942         }
8943         rc = rc2;
8944
8945 free_layout:
8946         llapi_layout_free(layout);
8947         llapi_lease_release(fd);
8948 close_fd:
8949         close(fd);
8950 error:
8951         return rc;
8952 }
8953
8954 static inline
8955 int lfs_mirror_resync_file(const char *fname, struct ll_ioc_lease *ioc,
8956                            __u16 *mirror_ids, int ids_nr)
8957 {
8958         struct llapi_resync_comp comp_array[1024] = { { 0 } };
8959         struct llapi_layout *layout;
8960         struct stat stbuf;
8961         uint32_t flr_state;
8962         uint64_t start;
8963         uint64_t end;
8964         int comp_size = 0;
8965         int idx;
8966         int fd;
8967         int rc;
8968         int rc2;
8969
8970         if (stat(fname, &stbuf) < 0) {
8971                 fprintf(stderr, "%s: cannot stat file '%s': %s.\n",
8972                         progname, fname, strerror(errno));
8973                 rc = -errno;
8974                 goto error;
8975         }
8976         if (!S_ISREG(stbuf.st_mode)) {
8977                 fprintf(stderr, "%s: '%s' is not a regular file.\n",
8978                         progname, fname);
8979                 rc = -EINVAL;
8980                 goto error;
8981         }
8982
8983         fd = open(fname, O_DIRECT | O_RDWR);
8984         if (fd < 0) {
8985                 fprintf(stderr, "%s: cannot open '%s': %s.\n",
8986                         progname, fname, strerror(errno));
8987                 rc = -errno;
8988                 goto error;
8989         }
8990
8991         layout = llapi_layout_get_by_fd(fd, 0);
8992         if (layout == NULL) {
8993                 fprintf(stderr, "%s: '%s' llapi_layout_get_by_fd failed: %s.\n",
8994                         progname, fname, strerror(errno));
8995                 rc = -errno;
8996                 goto close_fd;
8997         }
8998
8999         rc = llapi_layout_flags_get(layout, &flr_state);
9000         if (rc) {
9001                 fprintf(stderr, "%s: '%s' llapi_layout_flags_get failed: %s.\n",
9002                         progname, fname, strerror(errno));
9003                 rc = -errno;
9004                 goto free_layout;
9005         }
9006
9007         flr_state &= LCM_FL_FLR_MASK;
9008         if (flr_state == LCM_FL_NONE) {
9009                 rc = -EINVAL;
9010                 fprintf(stderr, "%s: '%s' is not a FLR file.\n",
9011                         progname, fname);
9012                 goto free_layout;
9013         }
9014
9015         /* get stale component info */
9016         comp_size = llapi_mirror_find_stale(layout, comp_array,
9017                                             ARRAY_SIZE(comp_array),
9018                                             mirror_ids, ids_nr);
9019         if (comp_size <= 0) {
9020                 rc = comp_size;
9021                 goto free_layout;
9022         }
9023
9024         ioc->lil_mode = LL_LEASE_WRLCK;
9025         ioc->lil_flags = LL_LEASE_RESYNC;
9026         rc = llapi_lease_set(fd, ioc);
9027         if (rc < 0) {
9028                 if (rc == -EALREADY)
9029                         rc = 0;
9030                 else
9031                         fprintf(stderr,
9032                             "%s: '%s' llapi_lease_get_ext resync failed: %s.\n",
9033                                 progname, fname, strerror(-rc));
9034                 goto free_layout;
9035         }
9036
9037         /* get the read range [start, end) */
9038         start = comp_array[0].lrc_start;
9039         end = comp_array[0].lrc_end;
9040         for (idx = 1; idx < comp_size; idx++) {
9041                 if (comp_array[idx].lrc_start < start)
9042                         start = comp_array[idx].lrc_start;
9043                 if (end < comp_array[idx].lrc_end)
9044                         end = comp_array[idx].lrc_end;
9045         }
9046
9047         rc = llapi_lease_check(fd);
9048         if (rc != LL_LEASE_WRLCK) {
9049                 fprintf(stderr, "%s: '%s' lost lease lock.\n",
9050                         progname, fname);
9051                 goto free_layout;
9052         }
9053
9054         rc = llapi_mirror_resync_many(fd, layout, comp_array, comp_size,
9055                                       start, end);
9056         if (rc < 0)
9057                 fprintf(stderr, "%s: '%s' llapi_mirror_resync_many: %s.\n",
9058                         progname, fname, strerror(-rc));
9059
9060         /* need to do the lease unlock even resync fails */
9061         ioc->lil_mode = LL_LEASE_UNLCK;
9062         ioc->lil_flags = LL_LEASE_RESYNC_DONE;
9063         ioc->lil_count = 0;
9064         for (idx = 0; idx < comp_size; idx++) {
9065                 if (comp_array[idx].lrc_synced) {
9066                         ioc->lil_ids[ioc->lil_count] = comp_array[idx].lrc_id;
9067                         ioc->lil_count++;
9068                 }
9069         }
9070
9071         rc2 = llapi_lease_set(fd, ioc);
9072         /**
9073          * llapi_lease_set returns lease mode when it request to unlock
9074          * the lease lock.
9075          */
9076         if (rc2 <= 0) {
9077                 /* rc2 == 0 means lost lease lock */
9078                 if (rc2 == 0 && rc == 0)
9079                         rc = -EBUSY;
9080                 fprintf(stderr, "%s: resync file '%s' failed: %s.\n",
9081                         progname, fname,
9082                         rc2 == 0 ? "lost lease lock" : strerror(-rc2));
9083         }
9084
9085 free_layout:
9086         llapi_layout_free(layout);
9087 close_fd:
9088         close(fd);
9089 error:
9090         return rc;
9091 }
9092
9093 static inline int lfs_mirror_resync(int argc, char **argv)
9094 {
9095         struct ll_ioc_lease *ioc = NULL;
9096         __u16 mirror_ids[128] = { 0 };
9097         int ids_nr = 0;
9098         int c;
9099         int rc = 0;
9100
9101         struct option long_opts[] = {
9102         { .val = 'o',   .name = "only",         .has_arg = required_argument },
9103         { .name = NULL } };
9104
9105         while ((c = getopt_long(argc, argv, "o:", long_opts, NULL)) >= 0) {
9106                 switch (c) {
9107                 case 'o':
9108                         rc = parse_mirror_ids(mirror_ids,
9109                                         sizeof(mirror_ids) / sizeof(__u16),
9110                                         optarg);
9111                         if (rc < 0) {
9112                                 fprintf(stderr,
9113                                         "%s: bad mirror ids '%s'.\n",
9114                                         argv[0], optarg);
9115                                 goto error;
9116                         }
9117                         ids_nr = rc;
9118                         break;
9119                 default:
9120                         fprintf(stderr, "%s: options '%s' unrecognized.\n",
9121                                 argv[0], argv[optind - 1]);
9122                         rc = -EINVAL;
9123                         goto error;
9124                 }
9125         }
9126
9127         if (argc == optind) {
9128                 fprintf(stderr, "%s: no file name given.\n", argv[0]);
9129                 rc = CMD_HELP;
9130                 goto error;
9131         }
9132
9133         if (ids_nr > 0 && argc > optind + 1) {
9134                 fprintf(stderr,
9135                     "%s: option '--only' cannot be used upon multiple files.\n",
9136                         argv[0]);
9137                 rc = CMD_HELP;
9138                 goto error;
9139
9140         }
9141
9142         if (ids_nr > 0) {
9143                 rc = verify_mirror_ids(argv[optind], mirror_ids, ids_nr);
9144                 if (rc < 0)
9145                         goto error;
9146         }
9147
9148         /* set the lease on the file */
9149         ioc = calloc(sizeof(*ioc) + sizeof(__u32) * 4096, 1);
9150         if (ioc == NULL) {
9151                 fprintf(stderr, "%s: cannot alloc id array for ioc: %s.\n",
9152                         argv[0], strerror(errno));
9153                 rc = -errno;
9154                 goto error;
9155         }
9156
9157         for (; optind < argc; optind++) {
9158                 rc = lfs_mirror_resync_file(argv[optind], ioc,
9159                                             mirror_ids, ids_nr);
9160                 /* ignore previous file's error, continue with next file */
9161
9162                 /* reset ioc */
9163                 memset(ioc, 0, sizeof(*ioc) + sizeof(__u32) * 4096);
9164         }
9165
9166         free(ioc);
9167 error:
9168         return rc;
9169 }
9170
9171 static inline int verify_mirror_id_by_fd(int fd, __u16 mirror_id)
9172 {
9173         struct llapi_layout *layout;
9174         int rc;
9175
9176         layout = llapi_layout_get_by_fd(fd, 0);
9177         if (layout == NULL) {
9178                 fprintf(stderr, "could not get layout.\n");
9179                 return  -EINVAL;
9180         }
9181
9182         rc = llapi_layout_comp_iterate(layout, find_mirror_id, &mirror_id);
9183         if (rc < 0) {
9184                 fprintf(stderr, "failed to iterate layout\n");
9185                 llapi_layout_free(layout);
9186
9187                 return rc;
9188         } else if (rc == LLAPI_LAYOUT_ITER_CONT) {
9189                 fprintf(stderr, "does not find mirror with ID %u\n", mirror_id);
9190                 llapi_layout_free(layout);
9191
9192                 return -EINVAL;
9193         }
9194         llapi_layout_free(layout);
9195
9196         return 0;
9197 }
9198
9199 /**
9200  * Check whether two files are the same file
9201  * \retval      0  same file
9202  * \retval      1  not the same file
9203  * \retval      <0 error code
9204  */
9205 static inline int check_same_file(const char *f1, const char *f2)
9206 {
9207         struct stat stbuf1;
9208         struct stat stbuf2;
9209
9210         if (stat(f1, &stbuf1) < 0) {
9211                 fprintf(stderr, "%s: cannot stat file '%s': %s\n",
9212                         progname, f1, strerror(errno));
9213                 return -errno;
9214         }
9215
9216         if (stat(f2, &stbuf2) < 0) {
9217                 fprintf(stderr, "%s: cannot stat file '%s': %s\n",
9218                         progname, f2, strerror(errno));
9219                 return -errno;
9220         }
9221
9222         if (stbuf1.st_rdev == stbuf2.st_rdev &&
9223             stbuf1.st_ino == stbuf2.st_ino)
9224                 return 0;
9225
9226         return 1;
9227 }
9228
9229 static inline int lfs_mirror_read(int argc, char **argv)
9230 {
9231         int rc = CMD_HELP;
9232         __u16 mirror_id = 0;
9233         const char *outfile = NULL;
9234         char *fname;
9235         int fd = 0;
9236         int outfd;
9237         int c;
9238         void *buf;
9239         const size_t buflen = 4 << 20;
9240         off_t pos;
9241         struct option long_opts[] = {
9242         { .val = 'N',   .name = "mirror-id",    .has_arg = required_argument },
9243         { .val = 'o',   .name = "outfile",      .has_arg = required_argument },
9244         { .name = NULL } };
9245
9246         while ((c = getopt_long(argc, argv, "N:o:", long_opts, NULL)) >= 0) {
9247                 char *end;
9248
9249                 switch (c) {
9250                 case 'N':
9251                         mirror_id = strtoul(optarg, &end, 0);
9252                         if (*end != '\0' || mirror_id == 0) {
9253                                 fprintf(stderr,
9254                                         "%s %s: invalid mirror ID '%s'\n",
9255                                         progname, argv[0], optarg);
9256                                 return rc;
9257                         }
9258                         break;
9259                 case 'o':
9260                         outfile = optarg;
9261                         break;
9262                 default:
9263                         fprintf(stderr, "%s: option '%s' unrecognized.\n",
9264                                 progname, argv[optind - 1]);
9265                         return -EINVAL;
9266                 }
9267         }
9268
9269         if (argc == optind) {
9270                 fprintf(stderr, "%s %s: no mirrored file provided\n",
9271                         progname, argv[0]);
9272                 return rc;
9273         } else if (argc > optind + 1) {
9274                 fprintf(stderr, "%s %s: too many files\n", progname, argv[0]);
9275                 return rc;
9276         }
9277
9278         if (mirror_id == 0) {
9279                 fprintf(stderr, "%s %s: no valid mirror ID is provided\n",
9280                         progname, argv[0]);
9281                 return rc;
9282         }
9283
9284         /* open mirror file */
9285         fname = argv[optind];
9286
9287         if (outfile) {
9288                 rc = check_same_file(fname, outfile);
9289                 if (rc == 0) {
9290                         fprintf(stderr,
9291                         "%s %s: output file cannot be the mirrored file\n",
9292                                 progname, argv[0]);
9293                         return -EINVAL;
9294                 }
9295                 if (rc < 0)
9296                         return rc;
9297         }
9298
9299         fd = open(fname, O_DIRECT | O_RDONLY);
9300         if (fd < 0) {
9301                 fprintf(stderr, "%s %s: cannot open '%s': %s\n",
9302                         progname, argv[0], fname, strerror(errno));
9303                 return rc;
9304         }
9305
9306         /* verify mirror id */
9307         rc = verify_mirror_id_by_fd(fd, mirror_id);
9308         if (rc) {
9309                 fprintf(stderr,
9310                         "%s %s: cannot find mirror with ID %u in '%s'\n",
9311                         progname, argv[0], mirror_id, fname);
9312                 goto close_fd;
9313         }
9314
9315         /* open output file */
9316         if (outfile) {
9317                 outfd = open(outfile, O_EXCL | O_WRONLY | O_CREAT, 0644);
9318                 if (outfd < 0) {
9319                         fprintf(stderr, "%s %s: cannot create file '%s': %s\n",
9320                                 progname, argv[0], outfile, strerror(errno));
9321                         rc = -errno;
9322                         goto close_fd;
9323                 }
9324         } else {
9325                 outfd = STDOUT_FILENO;
9326         }
9327
9328         /* allocate buffer */
9329         rc = posix_memalign(&buf, sysconf(_SC_PAGESIZE), buflen);
9330         if (rc) {
9331                 fprintf(stderr, "%s %s: posix_memalign returns %d\n",
9332                                 progname, argv[0], rc);
9333                 goto close_outfd;
9334         }
9335
9336         pos = 0;
9337         while (1) {
9338                 ssize_t bytes_read;
9339                 ssize_t written = 0;
9340
9341                 bytes_read = llapi_mirror_read(fd, mirror_id, buf, buflen, pos);
9342                 if (bytes_read < 0) {
9343                         rc = bytes_read;
9344                         fprintf(stderr,
9345                                 "%s %s: fail to read data from mirror %u: %s\n",
9346                                 progname, argv[0], mirror_id, strerror(-rc));
9347                         goto free_buf;
9348                 }
9349
9350                 /* EOF reached */
9351                 if (bytes_read == 0)
9352                         break;
9353
9354                 while (written < bytes_read) {
9355                         ssize_t written2;
9356
9357                         written2 = write(outfd, buf + written,
9358                                          bytes_read - written);
9359                         if (written2 < 0) {
9360                                 fprintf(stderr,
9361                                         "%s %s: fail to write %s: %s\n",
9362                                         progname, argv[0], outfile ? : "STDOUT",
9363                                         strerror(errno));
9364                                 rc = -errno;
9365                                 goto free_buf;
9366                         }
9367                         written += written2;
9368                 }
9369
9370                 if (written != bytes_read) {
9371                         fprintf(stderr,
9372                 "%s %s: written %ld bytes does not match with %ld read.\n",
9373                                 progname, argv[0], written, bytes_read);
9374                         rc = -EIO;
9375                         goto free_buf;
9376                 }
9377
9378                 pos += bytes_read;
9379         }
9380
9381         fsync(outfd);
9382         rc = 0;
9383
9384 free_buf:
9385         free(buf);
9386 close_outfd:
9387         if (outfile)
9388                 close(outfd);
9389 close_fd:
9390         close(fd);
9391
9392         return rc;
9393 }
9394
9395 static inline int lfs_mirror_write(int argc, char **argv)
9396 {
9397         int rc = CMD_HELP;
9398         __u16 mirror_id = 0;
9399         const char *inputfile = NULL;
9400         char *fname;
9401         int fd = 0;
9402         int inputfd;
9403         int c;
9404         void *buf;
9405         const size_t buflen = 4 << 20;
9406         off_t pos;
9407         size_t page_size = sysconf(_SC_PAGESIZE);
9408         struct ll_ioc_lease_id ioc;
9409
9410         struct option long_opts[] = {
9411         { .val = 'N',   .name = "mirror-id",    .has_arg = required_argument },
9412         { .val = 'i',   .name = "inputfile",    .has_arg = required_argument },
9413         { .name = NULL } };
9414
9415         while ((c = getopt_long(argc, argv, "N:i:", long_opts, NULL)) >= 0) {
9416                 char *end;
9417
9418                 switch (c) {
9419                 case 'N':
9420                         mirror_id = strtoul(optarg, &end, 0);
9421                         if (*end != '\0' || mirror_id == 0) {
9422                                 fprintf(stderr,
9423                                         "%s %s: invalid mirror ID '%s'\n",
9424                                         progname, argv[0], optarg);
9425                                 return rc;
9426                         }
9427                         break;
9428                 case 'i':
9429                         inputfile = optarg;
9430                         break;
9431                 default:
9432                         fprintf(stderr, "%s: option '%s' unrecognized\n",
9433                                 progname, argv[optind - 1]);
9434                         return -EINVAL;
9435                 }
9436         }
9437
9438         if (argc == optind) {
9439                 fprintf(stderr, "%s %s: no mirrored file provided\n",
9440                         progname, argv[0]);
9441                 return rc;
9442         } else if (argc > optind + 1) {
9443                 fprintf(stderr, "%s %s: too many files\n", progname, argv[0]);
9444                 return rc;
9445         }
9446
9447         if (mirror_id == 0) {
9448                 fprintf(stderr, "%s %s: no valid mirror ID is provided\n",
9449                         progname, argv[0]);
9450                 return rc;
9451         }
9452
9453         /* open mirror file */
9454         fname = argv[optind];
9455
9456         if (inputfile) {
9457                 rc = check_same_file(fname, inputfile);
9458                 if (rc == 0) {
9459                         fprintf(stderr,
9460                         "%s %s: input file cannot be the mirrored file\n",
9461                                 progname, argv[0]);
9462                         return -EINVAL;
9463                 }
9464                 if (rc < 0)
9465                         return rc;
9466         }
9467
9468         fd = open(fname, O_DIRECT | O_WRONLY);
9469         if (fd < 0) {
9470                 fprintf(stderr, "%s %s: cannot open '%s': %s\n",
9471                         progname, argv[0], fname, strerror(errno));
9472                 return rc;
9473         }
9474
9475         /* verify mirror id */
9476         rc = verify_mirror_id_by_fd(fd, mirror_id);
9477         if (rc) {
9478                 fprintf(stderr,
9479                         "%s %s: cannot find mirror with ID %u in '%s'\n",
9480                         progname, argv[0], mirror_id, fname);
9481                 goto close_fd;
9482         }
9483
9484         /* open input file */
9485         if (inputfile) {
9486                 inputfd = open(inputfile, O_RDONLY, 0644);
9487                 if (inputfd < 0) {
9488                         fprintf(stderr, "%s %s: cannot open file '%s': %s\n",
9489                                 progname, argv[0], inputfile, strerror(errno));
9490                         rc = -errno;
9491                         goto close_fd;
9492                 }
9493         } else {
9494                 inputfd = STDIN_FILENO;
9495         }
9496
9497         /* allocate buffer */
9498         rc = posix_memalign(&buf, page_size, buflen);
9499         if (rc) {
9500                 fprintf(stderr, "%s %s: posix_memalign returns %d\n",
9501                         progname, argv[0], rc);
9502                 goto close_inputfd;
9503         }
9504
9505         /* prepare target mirror components instantiation */
9506         ioc.lil_mode = LL_LEASE_WRLCK;
9507         ioc.lil_flags = LL_LEASE_RESYNC;
9508         ioc.lil_mirror_id = mirror_id;
9509         rc = llapi_lease_set(fd, (struct ll_ioc_lease *)&ioc);
9510         if (rc < 0) {
9511                 fprintf(stderr,
9512                         "%s %s: '%s' llapi_lease_get_ext failed: %s\n",
9513                         progname, argv[0], fname, strerror(errno));
9514                 goto free_buf;
9515         }
9516
9517         pos = 0;
9518         while (1) {
9519                 ssize_t bytes_read;
9520                 ssize_t written;
9521                 size_t to_write;
9522
9523                 rc = llapi_lease_check(fd);
9524                 if (rc != LL_LEASE_WRLCK) {
9525                         fprintf(stderr, "%s %s: '%s' lost lease lock\n",
9526                                 progname, argv[0], fname);
9527                         goto free_buf;
9528                 }
9529
9530                 bytes_read = read(inputfd, buf, buflen);
9531                 if (bytes_read < 0) {
9532                         rc = bytes_read;
9533                         fprintf(stderr,
9534                                 "%s %s: fail to read data from '%s': %s\n",
9535                                 progname, argv[0], inputfile ? : "STDIN",
9536                                 strerror(errno));
9537                         rc = -errno;
9538                         goto free_buf;
9539                 }
9540
9541                 /* EOF reached */
9542                 if (bytes_read == 0)
9543                         break;
9544
9545                 /* round up to page align to make direct IO happy. */
9546                 to_write = (bytes_read + page_size - 1) & ~(page_size - 1);
9547
9548                 written = llapi_mirror_write(fd, mirror_id, buf, to_write,
9549                                              pos);
9550                 if (written < 0) {
9551                         rc = written;
9552                         fprintf(stderr,
9553                               "%s %s: fail to write to mirror %u: %s\n",
9554                                 progname, argv[0], mirror_id,
9555                                 strerror(-rc));
9556                         goto free_buf;
9557                 }
9558
9559                 pos += bytes_read;
9560         }
9561
9562         if (pos & (page_size - 1)) {
9563                 rc = llapi_mirror_truncate(fd, mirror_id, pos);
9564                 if (rc < 0)
9565                         goto free_buf;
9566         }
9567
9568         ioc.lil_mode = LL_LEASE_UNLCK;
9569         ioc.lil_flags = LL_LEASE_RESYNC_DONE;
9570         ioc.lil_count = 0;
9571         rc = llapi_lease_set(fd, (struct ll_ioc_lease *)&ioc);
9572         if (rc <= 0) {
9573                 if (rc == 0)
9574                         rc = -EBUSY;
9575                 fprintf(stderr,
9576                         "%s %s: release lease lock of '%s' failed: %s\n",
9577                         progname, argv[0], fname, strerror(errno));
9578                 goto free_buf;
9579         }
9580
9581         rc = 0;
9582
9583 free_buf:
9584         free(buf);
9585 close_inputfd:
9586         if (inputfile)
9587                 close(inputfd);
9588 close_fd:
9589         close(fd);
9590
9591         return rc;
9592 }
9593
9594 struct collect_ids_data {
9595         __u16   *cid_ids;
9596         int     cid_count;
9597         __u16   cid_exclude;
9598 };
9599
9600 static int collect_mirror_id(struct llapi_layout *layout, void *cbdata)
9601 {
9602         struct collect_ids_data *cid = cbdata;
9603         uint32_t id;
9604         int rc;
9605
9606         rc = llapi_layout_mirror_id_get(layout, &id);
9607         if (rc < 0)
9608                 return rc;
9609
9610         if ((__u16)id != cid->cid_exclude) {
9611                 int i;
9612
9613                 for (i = 0; i < cid->cid_count; i++) {
9614                         /* already collected the mirror id */
9615                         if (id == cid->cid_ids[i])
9616                                 return LLAPI_LAYOUT_ITER_CONT;
9617                 }
9618                 cid->cid_ids[cid->cid_count] = id;
9619                 cid->cid_count++;
9620         }
9621
9622         return LLAPI_LAYOUT_ITER_CONT;
9623 }
9624
9625 static inline int get_other_mirror_ids(int fd, __u16 *ids, __u16 exclude_id)
9626 {
9627         struct llapi_layout *layout;
9628         struct collect_ids_data cid = { .cid_ids = ids,
9629                                         .cid_count = 0,
9630                                         .cid_exclude = exclude_id, };
9631         int rc;
9632
9633         layout = llapi_layout_get_by_fd(fd, 0);
9634         if (layout == NULL) {
9635                 fprintf(stderr, "could not get layout\n");
9636                 return -EINVAL;
9637         }
9638
9639         rc = llapi_layout_comp_iterate(layout, collect_mirror_id, &cid);
9640         if (rc < 0) {
9641                 fprintf(stderr, "failed to iterate layout\n");
9642                 llapi_layout_free(layout);
9643
9644                 return rc;
9645         }
9646         llapi_layout_free(layout);
9647
9648         return cid.cid_count;
9649 }
9650
9651 static inline int lfs_mirror_copy(int argc, char **argv)
9652 {
9653         int rc = CMD_HELP;
9654         __u16 read_mirror_id = 0;
9655         __u16 ids[128] = { 0 };
9656         int count = 0;
9657         struct llapi_layout *layout = NULL;
9658         struct llapi_resync_comp comp_array[1024] = { { 0 } };
9659         int comp_size = 0;
9660         char *fname;
9661         int fd = 0;
9662         int c;
9663         int i;
9664         ssize_t copied;
9665         struct ll_ioc_lease *ioc = NULL;
9666         struct ll_ioc_lease_id *resync_ioc;
9667
9668         struct option long_opts[] = {
9669         { .val = 'i',   .name = "read-mirror",  .has_arg = required_argument },
9670         { .val = 'o',   .name = "write-mirror", .has_arg = required_argument },
9671         { .name = NULL } };
9672
9673         while ((c = getopt_long(argc, argv, "i:o:", long_opts, NULL)) >= 0) {
9674                 char *end;
9675
9676                 switch (c) {
9677                 case 'i':
9678                         read_mirror_id = strtoul(optarg, &end, 0);
9679                         if (*end != '\0' || read_mirror_id == 0) {
9680                                 fprintf(stderr,
9681                                         "%s %s: invalid read mirror ID '%s'\n",
9682                                         progname, argv[0], optarg);
9683                                 return rc;
9684                         }
9685                         break;
9686                 case 'o':
9687                         if (!strcmp(optarg, "-1")) {
9688                                 /* specify all other mirrors */
9689                                 ids[0] = (__u16)-1;
9690                                 count = 1;
9691                         } else {
9692                                 count = parse_mirror_ids((__u16 *)ids,
9693                                                          ARRAY_SIZE(ids),
9694                                                          optarg);
9695                                 if (count < 0)
9696                                         return rc;
9697                         }
9698                         break;
9699                 default:
9700                         fprintf(stderr, "%s: option '%s' unrecognized\n",
9701                                 progname, argv[optind - 1]);
9702                         return -EINVAL;
9703                 }
9704         }
9705
9706         if (argc == optind) {
9707                 fprintf(stderr, "%s %s: no mirrored file provided\n",
9708                         progname, argv[0]);
9709                 return rc;
9710         } else if (argc > optind + 1) {
9711                 fprintf(stderr, "%s %s: too many files\n", progname, argv[0]);
9712                 return rc;
9713         }
9714
9715         if (read_mirror_id == 0) {
9716                 fprintf(stderr,
9717                         "%s %s: no valid read mirror ID %d is provided\n",
9718                         progname, argv[0], read_mirror_id);
9719                 return rc;
9720         }
9721
9722         if (count == 0) {
9723                 fprintf(stderr,
9724                         "%s %s: no write mirror ID is provided\n",
9725                         progname, argv[0]);
9726                 return rc;
9727         }
9728
9729         for (i = 0; i < count; i++) {
9730                 if (read_mirror_id == ids[i]) {
9731                         fprintf(stderr,
9732                         "%s %s: read and write mirror ID cannot be the same\n",
9733                                 progname, argv[0]);
9734                         return rc;
9735                 }
9736         }
9737
9738         /* open mirror file */
9739         fname = argv[optind];
9740
9741         fd = open(fname, O_DIRECT | O_RDWR);
9742         if (fd < 0) {
9743                 fprintf(stderr, "%s %s: cannot open '%s': %s\n",
9744                         progname, argv[0], fname, strerror(errno));
9745                 return rc;
9746         }
9747
9748         /* write to all other mirrors */
9749         if (ids[0] == (__u16)-1) {
9750                 count = get_other_mirror_ids(fd, ids, read_mirror_id);
9751                 if (count <= 0) {
9752                         rc = count;
9753                         fprintf(stderr,
9754                         "%s %s: failed to get other mirror ids in '%s': %d\n",
9755                                 progname, argv[0], fname, rc);
9756                         goto close_fd;
9757                 }
9758         }
9759
9760         /* verify mirror id */
9761         rc = verify_mirror_id_by_fd(fd, read_mirror_id);
9762         if (rc) {
9763                 fprintf(stderr,
9764                         "%s %s: cannot find mirror with ID %u in '%s'\n",
9765                         progname, argv[0], read_mirror_id, fname);
9766                 goto close_fd;
9767         }
9768
9769         for (i = 0; i < count; i++) {
9770                 rc = verify_mirror_id_by_fd(fd, ids[i]);
9771                 if (rc) {
9772                         fprintf(stderr,
9773                         "%s %s: cannot find mirror with ID %u in '%s'\n",
9774                                 progname, argv[0], ids[i], fname);
9775                         goto close_fd;
9776                 }
9777         }
9778
9779         ioc = calloc(sizeof(*ioc) + sizeof(__u32) * 4096, 1);
9780         if (ioc == NULL) {
9781                 fprintf(stderr,
9782                         "%s %s: cannot alloc comp id array for ioc: %s\n",
9783                         progname, argv[0], strerror(errno));
9784                 rc = -errno;
9785                 goto close_fd;
9786         }
9787
9788         /* get stale component info */
9789         layout = llapi_layout_get_by_fd(fd, 0);
9790         if (layout == NULL) {
9791                 fprintf(stderr, "%s %s: failed to get layout of '%s': %s\n",
9792                         progname, argv[0], fname, strerror(errno));
9793                 rc = -errno;
9794                 goto free_ioc;
9795         }
9796         comp_size = llapi_mirror_find_stale(layout, comp_array,
9797                                             ARRAY_SIZE(comp_array),
9798                                             ids, count);
9799         llapi_layout_free(layout);
9800         if (comp_size < 0) {
9801                 rc = comp_size;
9802                 goto free_ioc;
9803         }
9804
9805         /* prepare target mirror components instantiation */
9806         resync_ioc = (struct ll_ioc_lease_id *)ioc;
9807         resync_ioc->lil_mode = LL_LEASE_WRLCK;
9808         resync_ioc->lil_flags = LL_LEASE_RESYNC;
9809         if (count == 1)
9810                 resync_ioc->lil_mirror_id = ids[0];
9811         else
9812                 resync_ioc->lil_mirror_id = read_mirror_id | MIRROR_ID_NEG;
9813         rc = llapi_lease_set(fd, ioc);
9814         if (rc < 0) {
9815                 fprintf(stderr,
9816                         "%s %s: '%s' llapi_lease_get_ext failed: %s\n",
9817                         progname, argv[0], fname, strerror(errno));
9818                 goto free_ioc;
9819         }
9820
9821         copied = llapi_mirror_copy_many(fd, read_mirror_id, ids, count);
9822         if (copied < 0) {
9823                 rc = copied;
9824                 fprintf(stderr, "%s %s: copy error: %d\n",
9825                         progname, argv[0], rc);
9826                 goto free_ioc;
9827         }
9828
9829         fprintf(stdout, "mirror copied successfully: ");
9830         for (i = 0; i < copied; i++)
9831                 fprintf(stdout, "%d ", ids[i]);
9832         fprintf(stdout, "\n");
9833
9834         ioc->lil_mode = LL_LEASE_UNLCK;
9835         ioc->lil_flags = LL_LEASE_RESYNC_DONE;
9836         ioc->lil_count = 0;
9837         for (i = 0; i < comp_size; i++) {
9838                 int j;
9839
9840                 for (j = 0; j < copied; j++) {
9841                         if (comp_array[i].lrc_mirror_id != ids[j])
9842                                 continue;
9843
9844                         ioc->lil_ids[ioc->lil_count] = comp_array[i].lrc_id;
9845                         ioc->lil_count++;
9846                 }
9847         }
9848         rc = llapi_lease_set(fd, ioc);
9849         if (rc <= 0) {
9850                 if (rc == 0)
9851                         rc = -EBUSY;
9852                 fprintf(stderr,
9853                         "%s %s: release lease lock of '%s' failed: %s\n",
9854                         progname, argv[0], fname, strerror(errno));
9855                 goto free_ioc;
9856         }
9857
9858         rc = 0;
9859
9860 free_ioc:
9861         free(ioc);
9862 close_fd:
9863         close(fd);
9864
9865         return rc;
9866 }
9867 /**
9868  * struct verify_chunk - Mirror chunk to be verified.
9869  * @chunk:        [start, end) of the chunk.
9870  * @mirror_count: Number of mirror ids in @mirror_id array.
9871  * @mirror_id:    Array of valid mirror ids that cover the chunk.
9872  */
9873 struct verify_chunk {
9874         struct lu_extent chunk;
9875         unsigned int mirror_count;
9876         __u16 mirror_id[LUSTRE_MIRROR_COUNT_MAX];
9877 };
9878
9879 /**
9880  * print_chunks() - Print chunk information.
9881  * @fname:       Mirrored file name.
9882  * @chunks:      Array of chunks.
9883  * @chunk_count: Number of chunks in @chunks array.
9884  *
9885  * This function prints [start, end) of each chunk in @chunks
9886  * for mirrored file @fname, and also prints the valid mirror ids
9887  * that cover the chunk.
9888  *
9889  * Return: void.
9890  */
9891 static inline
9892 void print_chunks(const char *fname, struct verify_chunk *chunks,
9893                   int chunk_count)
9894 {
9895         int i;
9896         int j;
9897
9898         fprintf(stdout, "Chunks to be verified in %s:\n", fname);
9899         for (i = 0; i < chunk_count; i++) {
9900                 fprintf(stdout, DEXT, PEXT(&chunks[i].chunk));
9901
9902                 if (chunks[i].mirror_count == 0)
9903                         fprintf(stdout, "\t[");
9904                 else {
9905                         fprintf(stdout, "\t[%u", chunks[i].mirror_id[0]);
9906                         for (j = 1; j < chunks[i].mirror_count; j++)
9907                                 fprintf(stdout, ", %u", chunks[i].mirror_id[j]);
9908                 }
9909                 fprintf(stdout, "]\t%u\n", chunks[i].mirror_count);
9910         }
9911         fprintf(stdout, "\n");
9912 }
9913
9914 /**
9915  * print_checksums() - Print CRC-32 checksum values.
9916  * @chunk: A chunk and its corresponding valid mirror ids.
9917  * @crc:   CRC-32 checksum values on the chunk for each valid mirror.
9918  *
9919  * This function prints CRC-32 checksum values on @chunk for
9920  * each valid mirror that covers it.
9921  *
9922  * Return: void.
9923  */
9924 static inline
9925 void print_checksums(struct verify_chunk *chunk, unsigned long *crc)
9926 {
9927         int i;
9928
9929         fprintf(stdout,
9930                 "CRC-32 checksum value for chunk "DEXT":\n",
9931                 PEXT(&chunk->chunk));
9932         for (i = 0; i < chunk->mirror_count; i++)
9933                 fprintf(stdout, "Mirror %u:\t%#lx\n",
9934                         chunk->mirror_id[i], crc[i]);
9935         fprintf(stdout, "\n");
9936 }
9937
9938 /**
9939  * filter_mirror_id() - Filter specified mirror ids.
9940  * @chunks:      Array of chunks.
9941  * @chunk_count: Number of chunks in @chunks array.
9942  * @mirror_ids:  Specified mirror ids to be verified.
9943  * @ids_nr:      Number of specified mirror ids.
9944  *
9945  * This function scans valid mirror ids that cover each chunk in @chunks
9946  * and filters specified mirror ids.
9947  *
9948  * Return: void.
9949  */
9950 static inline
9951 void filter_mirror_id(struct verify_chunk *chunks, int chunk_count,
9952                       __u16 *mirror_ids, int ids_nr)
9953 {
9954         int i;
9955         int j;
9956         int k;
9957         __u16 valid_id[LUSTRE_MIRROR_COUNT_MAX] = { 0 };
9958         unsigned int valid_count = 0;
9959
9960         for (i = 0; i < chunk_count; i++) {
9961                 if (chunks[i].mirror_count == 0)
9962                         continue;
9963
9964                 valid_count = 0;
9965                 for (j = 0; j < ids_nr; j++) {
9966                         for (k = 0; k < chunks[i].mirror_count; k++) {
9967                                 if (chunks[i].mirror_id[k] == mirror_ids[j]) {
9968                                         valid_id[valid_count] = mirror_ids[j];
9969                                         valid_count++;
9970                                         break;
9971                                 }
9972                         }
9973                 }
9974
9975                 memcpy(chunks[i].mirror_id, valid_id,
9976                        sizeof(__u16) * valid_count);
9977                 chunks[i].mirror_count = valid_count;
9978         }
9979 }
9980
9981 /**
9982  * lfs_mirror_prepare_chunk() - Find mirror chunks to be verified.
9983  * @layout:      Mirror component list.
9984  * @chunks:      Array of chunks.
9985  * @chunks_size: Array size of @chunks.
9986  *
9987  * This function scans the components in @layout from offset 0 to LUSTRE_EOF
9988  * to find out chunk segments and store them in @chunks array.
9989  *
9990  * The @mirror_id array in each element of @chunks will store the valid
9991  * mirror ids that cover the chunk. If a mirror component covering the
9992  * chunk has LCME_FL_STALE or LCME_FL_OFFLINE flag, then the mirror id
9993  * will not be stored into the @mirror_id array, and the chunk for that
9994  * mirror will not be verified.
9995  *
9996  * The @mirror_count in each element of @chunks will store the number of
9997  * mirror ids in @mirror_id array. If @mirror_count is 0, it indicates the
9998  * chunk is invalid in all of the mirrors. And if @mirror_count is 1, it
9999  * indicates the chunk is valid in only one mirror. In both cases, the
10000  * chunk will not be verified.
10001  *
10002  * Here is an example:
10003  *
10004  *  0      1M     2M     3M     4M           EOF
10005  *  +------+-------------+--------------------+
10006  *  |      |             |      S             |       mirror1
10007  *  +------+------+------+------+-------------+
10008  *  |             |   S  |   S  |             |       mirror2
10009  *  +-------------+------+------+-------------+
10010  *
10011  * prepared @chunks array will contain 5 elements:
10012  * (([0, 1M), [1, 2], 2),
10013  *  ([1M, 2M), [1, 2], 2),
10014  *  ([2M, 3M), [1], 1),
10015  *  ([3M, 4M], [], 0),
10016  *  ([4M, EOF), [2], 1))
10017  *
10018  * Return: the actual array size of @chunks on success
10019  *         or a negative error code on failure.
10020  */
10021 static inline
10022 int lfs_mirror_prepare_chunk(struct llapi_layout *layout,
10023                              struct verify_chunk *chunks,
10024                              size_t chunks_size)
10025 {
10026         uint64_t start;
10027         uint64_t end;
10028         uint32_t mirror_id;
10029         uint32_t flags;
10030         int idx = 0;
10031         int i = 0;
10032         int rc = 0;
10033
10034         memset(chunks, 0, sizeof(*chunks) * chunks_size);
10035
10036         while (1) {
10037                 rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_FIRST);
10038                 if (rc < 0) {
10039                         fprintf(stderr,
10040                                 "%s: move to the first layout component: %s.\n",
10041                                 progname, strerror(errno));
10042                         goto error;
10043                 }
10044
10045                 i = 0;
10046                 rc = 0;
10047                 chunks[idx].chunk.e_end = LUSTRE_EOF;
10048                 while (rc == 0) {
10049                         rc = llapi_layout_comp_extent_get(layout, &start, &end);
10050                         if (rc < 0) {
10051                                 fprintf(stderr,
10052                                         "%s: llapi_layout_comp_extent_get failed: %s.\n",
10053                                         progname, strerror(errno));
10054                                 goto error;
10055                         }
10056
10057                         if (start > chunks[idx].chunk.e_start ||
10058                             end <= chunks[idx].chunk.e_start)
10059                                 goto next;
10060
10061                         if (end < chunks[idx].chunk.e_end)
10062                                 chunks[idx].chunk.e_end = end;
10063
10064                         rc = llapi_layout_comp_flags_get(layout, &flags);
10065                         if (rc < 0) {
10066                                 fprintf(stderr,
10067                                         "%s: llapi_layout_comp_flags_get failed: %s.\n",
10068                                         progname, strerror(errno));
10069                                 goto error;
10070                         }
10071
10072                         if (flags & LCME_FL_STALE || flags & LCME_FL_OFFLINE)
10073                                 goto next;
10074
10075                         rc = llapi_layout_mirror_id_get(layout, &mirror_id);
10076                         if (rc < 0) {
10077                                 fprintf(stderr,
10078                                         "%s: llapi_layout_mirror_id_get failed: %s.\n",
10079                                         progname, strerror(errno));
10080                                 goto error;
10081                         }
10082
10083                         chunks[idx].mirror_id[i] = mirror_id;
10084                         i++;
10085                         if (i >= ARRAY_SIZE(chunks[idx].mirror_id)) {
10086                                 fprintf(stderr,
10087                                         "%s: mirror_id array is too small.\n",
10088                                         progname);
10089                                 rc = -EINVAL;
10090                                 goto error;
10091                         }
10092
10093                 next:
10094                         rc = llapi_layout_comp_use(layout,
10095                                                    LLAPI_LAYOUT_COMP_USE_NEXT);
10096                         if (rc < 0) {
10097                                 fprintf(stderr,
10098                                         "%s: move to the next layout component: %s.\n",
10099                                         progname, strerror(errno));
10100                                 goto error;
10101                         }
10102                 } /* loop through all components */
10103
10104                 chunks[idx].mirror_count = i;
10105
10106                 if (chunks[idx].chunk.e_end == LUSTRE_EOF)
10107                         break;
10108
10109                 idx++;
10110                 if (idx >= chunks_size) {
10111                         fprintf(stderr, "%s: chunks array is too small.\n",
10112                                 progname);
10113                         rc = -EINVAL;
10114                         goto error;
10115                 }
10116
10117                 chunks[idx].chunk.e_start = chunks[idx - 1].chunk.e_end;
10118         }
10119
10120 error:
10121         return rc < 0 ? rc : idx + 1;
10122 }
10123
10124 /**
10125  * lfs_mirror_verify_chunk() - Verify a chunk.
10126  * @fd:        File descriptor of the mirrored file.
10127  * @file_size: Size of the mirrored file.
10128  * @chunk:     A chunk and its corresponding valid mirror ids.
10129  * @verbose:   Verbose mode.
10130  *
10131  * This function verifies a @chunk contains exactly the same data
10132  * ammong the mirrors that cover it.
10133  *
10134  * If @verbose is specified, then the function will print where the
10135  * differences are if the data do not match. Otherwise, it will
10136  * just return an error in that case.
10137  *
10138  * Return: 0 on success or a negative error code on failure.
10139  */
10140 static inline
10141 int lfs_mirror_verify_chunk(int fd, size_t file_size,
10142                             struct verify_chunk *chunk, int verbose)
10143 {
10144         const size_t buflen = 4 * 1024 * 1024; /* 4M */
10145         void *buf;
10146         size_t page_size = sysconf(_SC_PAGESIZE);
10147         ssize_t bytes_read;
10148         ssize_t bytes_done;
10149         size_t count;
10150         off_t pos;
10151         unsigned long crc;
10152         unsigned long crc_array[LUSTRE_MIRROR_COUNT_MAX] = { 0 };
10153         int i;
10154         int rc = 0;
10155
10156         if (file_size == 0)
10157                 return 0;
10158
10159         rc = posix_memalign(&buf, page_size, buflen);
10160         if (rc) /* error code is returned directly */
10161                 return -rc;
10162
10163         if (verbose > 1) {
10164                 fprintf(stdout, "Verifying chunk "DEXT" on mirror:",
10165                         PEXT(&chunk->chunk));
10166                 for (i = 0; i < chunk->mirror_count; i++)
10167                         fprintf(stdout, " %u", chunk->mirror_id[i]);
10168                 fprintf(stdout, "\n");
10169         }
10170
10171         bytes_done = 0;
10172         count = MIN(chunk->chunk.e_end, file_size) - chunk->chunk.e_start;
10173         pos = chunk->chunk.e_start;
10174         while (bytes_done < count) {
10175                 /* compute initial CRC-32 checksum */
10176                 crc = crc32(0L, Z_NULL, 0);
10177                 memset(crc_array, 0, sizeof(crc_array));
10178
10179                 bytes_read = 0;
10180                 for (i = 0; i < chunk->mirror_count; i++) {
10181                         bytes_read = llapi_mirror_read(fd, chunk->mirror_id[i],
10182                                                        buf, buflen, pos);
10183                         if (bytes_read < 0) {
10184                                 rc = bytes_read;
10185                                 fprintf(stderr,
10186                                         "%s: failed to read data from mirror %u: %s.\n",
10187                                         progname, chunk->mirror_id[i],
10188                                         strerror(-rc));
10189                                 goto error;
10190                         }
10191
10192                         /* compute new CRC-32 checksum */
10193                         crc_array[i] = crc32(crc, buf, bytes_read);
10194                 }
10195
10196                 if (verbose)
10197                         print_checksums(chunk, crc_array);
10198
10199                 /* compare CRC-32 checksum values */
10200                 for (i = 1; i < chunk->mirror_count; i++) {
10201                         if (crc_array[i] != crc_array[0]) {
10202                                 rc = -EINVAL;
10203
10204                                 fprintf(stderr,
10205                                         "%s: chunk "DEXT" has different checksum value on mirror %u and mirror %u.\n",
10206                                         progname, PEXT(&chunk->chunk),
10207                                         chunk->mirror_id[0],
10208                                         chunk->mirror_id[i]);
10209                         }
10210                 }
10211
10212                 pos += bytes_read;
10213                 bytes_done += bytes_read;
10214         }
10215
10216         if (verbose > 1 && rc == 0) {
10217                 fprintf(stdout, "Verifying chunk "DEXT" on mirror:",
10218                         PEXT(&chunk->chunk));
10219                 for (i = 0; i < chunk->mirror_count; i++)
10220                         fprintf(stdout, " %u", chunk->mirror_id[i]);
10221                 fprintf(stdout, " PASS\n\n");
10222         }
10223
10224 error:
10225         free(buf);
10226         return rc;
10227 }
10228
10229 /**
10230  * lfs_mirror_verify_file() - Verify a mirrored file.
10231  * @fname:      Mirrored file name.
10232  * @mirror_ids: Specified mirror ids to be verified.
10233  * @ids_nr:     Number of specified mirror ids.
10234  * @verbose:    Verbose mode.
10235  *
10236  * This function verifies that each SYNC mirror of a mirrored file
10237  * specified by @fname contains exactly the same data.
10238  *
10239  * If @mirror_ids is specified, then the function will verify the
10240  * mirrors specified by @mirror_ids contain exactly the same data.
10241  *
10242  * If @verbose is specified, then the function will print where the
10243  * differences are if the data do not match. Otherwise, it will
10244  * just return an error in that case.
10245  *
10246  * Return: 0 on success or a negative error code on failure.
10247  */
10248 static inline
10249 int lfs_mirror_verify_file(const char *fname, __u16 *mirror_ids, int ids_nr,
10250                            int verbose)
10251 {
10252         struct verify_chunk chunks_array[1024] = { };
10253         struct llapi_layout *layout = NULL;
10254         struct stat stbuf;
10255         uint32_t flr_state;
10256         int fd;
10257         int chunk_count = 0;
10258         int idx = 0;
10259         int rc = 0;
10260         int rc1 = 0;
10261         int rc2 = 0;
10262
10263         if (stat(fname, &stbuf) < 0) {
10264                 fprintf(stderr, "%s: cannot stat file '%s': %s.\n",
10265                         progname, fname, strerror(errno));
10266                 rc = -errno;
10267                 goto error;
10268         }
10269
10270         if (!S_ISREG(stbuf.st_mode)) {
10271                 fprintf(stderr, "%s: '%s' is not a regular file.\n",
10272                         progname, fname);
10273                 rc = -EINVAL;
10274                 goto error;
10275         }
10276
10277         if (stbuf.st_size == 0) {
10278                 if (verbose)
10279                         fprintf(stdout, "%s: '%s' file size is 0.\n",
10280                                 progname, fname);
10281                 rc = 0;
10282                 goto error;
10283         }
10284
10285         fd = open(fname, O_DIRECT | O_RDONLY);
10286         if (fd < 0) {
10287                 fprintf(stderr, "%s: cannot open '%s': %s.\n",
10288                         progname, fname, strerror(errno));
10289                 rc = -errno;
10290                 goto error;
10291         }
10292
10293         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
10294         if (rc < 0) {
10295                 fprintf(stderr, "%s: '%s' llapi_lease_acquire failed: %s.\n",
10296                         progname, fname, strerror(errno));
10297                 goto close_fd;
10298         }
10299
10300         layout = llapi_layout_get_by_fd(fd, 0);
10301         if (layout == NULL) {
10302                 fprintf(stderr, "%s: '%s' llapi_layout_get_by_fd failed: %s.\n",
10303                         progname, fname, strerror(errno));
10304                 rc = -errno;
10305                 llapi_lease_release(fd);
10306                 goto close_fd;
10307         }
10308
10309         rc = llapi_layout_flags_get(layout, &flr_state);
10310         if (rc < 0) {
10311                 fprintf(stderr, "%s: '%s' llapi_layout_flags_get failed: %s.\n",
10312                         progname, fname, strerror(errno));
10313                 rc = -errno;
10314                 goto free_layout;
10315         }
10316
10317         flr_state &= LCM_FL_FLR_MASK;
10318         switch (flr_state) {
10319         case LCM_FL_NONE:
10320                 rc = -EINVAL;
10321                 fprintf(stderr, "%s: '%s' file state error: %s.\n",
10322                         progname, fname, llapi_layout_flags_string(flr_state));
10323                 goto free_layout;
10324         default:
10325                 break;
10326         }
10327
10328         /* find out mirror chunks to be verified */
10329         chunk_count = lfs_mirror_prepare_chunk(layout, chunks_array,
10330                                                ARRAY_SIZE(chunks_array));
10331         if (chunk_count < 0) {
10332                 rc = chunk_count;
10333                 goto free_layout;
10334         }
10335
10336         if (ids_nr > 0)
10337                 /* filter specified mirror ids */
10338                 filter_mirror_id(chunks_array, chunk_count, mirror_ids, ids_nr);
10339
10340         if (verbose > 2)
10341                 print_chunks(fname, chunks_array, chunk_count);
10342
10343         for (idx = 0; idx < chunk_count; idx++) {
10344                 if (chunks_array[idx].chunk.e_start >= stbuf.st_size) {
10345                         if (verbose)
10346                                 fprintf(stdout,
10347                                         "%s: '%s' chunk "DEXT" exceeds file size %#llx: skipped\n",
10348                                         progname, fname,
10349                                         PEXT(&chunks_array[idx].chunk),
10350                                         (unsigned long long)stbuf.st_size);
10351                         break;
10352                 }
10353
10354                 if (chunks_array[idx].mirror_count == 0) {
10355                         fprintf(stderr,
10356                                 "%s: '%s' chunk "DEXT" is invalid in all of the mirrors: ",
10357                                 progname, fname,
10358                                 PEXT(&chunks_array[idx].chunk));
10359                         if (verbose) {
10360                                 fprintf(stderr, "skipped\n");
10361                                 continue;
10362                         }
10363                         rc = -EINVAL;
10364                         fprintf(stderr, "failed\n");
10365                         goto free_layout;
10366                 }
10367
10368                 if (chunks_array[idx].mirror_count == 1) {
10369                         if (verbose)
10370                                 fprintf(stdout,
10371                                         "%s: '%s' chunk "DEXT" is only valid in mirror %u: skipped\n",
10372                                         progname, fname,
10373                                         PEXT(&chunks_array[idx].chunk),
10374                                         chunks_array[idx].mirror_id[0]);
10375                         continue;
10376                 }
10377
10378                 rc = llapi_lease_check(fd);
10379                 if (rc != LL_LEASE_RDLCK) {
10380                         fprintf(stderr, "%s: '%s' lost lease lock.\n",
10381                                 progname, fname);
10382                         goto free_layout;
10383                 }
10384
10385                 /* verify one chunk */
10386                 rc1 = lfs_mirror_verify_chunk(fd, stbuf.st_size,
10387                                               &chunks_array[idx], verbose);
10388                 if (rc1 < 0) {
10389                         rc2 = rc1;
10390                         if (!verbose) {
10391                                 rc = rc1;
10392                                 goto free_layout;
10393                         }
10394                 }
10395         }
10396
10397         if (rc2 < 0)
10398                 rc = rc2;
10399
10400 free_layout:
10401         llapi_layout_free(layout);
10402         llapi_lease_release(fd);
10403 close_fd:
10404         close(fd);
10405 error:
10406         return rc;
10407 }
10408
10409 /**
10410  * lfs_mirror_verify() - Parse and execute lfs mirror verify command.
10411  * @argc: The count of lfs mirror verify command line arguments.
10412  * @argv: Array of strings for lfs mirror verify command line arguments.
10413  *
10414  * This function parses lfs mirror verify command and verifies the
10415  * specified mirrored file(s).
10416  *
10417  * Return: 0 on success or a negative error code on failure.
10418  */
10419 static inline int lfs_mirror_verify(int argc, char **argv)
10420 {
10421         __u16 mirror_ids[LUSTRE_MIRROR_COUNT_MAX] = { 0 };
10422         int ids_nr = 0;
10423         int c;
10424         int verbose = 0;
10425         int rc = 0;
10426         int rc1 = 0;
10427         char cmd[PATH_MAX];
10428
10429         struct option long_opts[] = {
10430         { .val = 'o',   .name = "only",         .has_arg = required_argument },
10431         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
10432         { .name = NULL } };
10433
10434         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
10435         progname = cmd;
10436         while ((c = getopt_long(argc, argv, "o:v", long_opts, NULL)) >= 0) {
10437                 switch (c) {
10438                 case 'o':
10439                         rc = parse_mirror_ids(mirror_ids,
10440                                               ARRAY_SIZE(mirror_ids),
10441                                               optarg);
10442                         if (rc < 0) {
10443                                 fprintf(stderr,
10444                                         "%s: bad mirror ids '%s'.\n",
10445                                         progname, optarg);
10446                                 goto error;
10447                         }
10448                         ids_nr = rc;
10449                         if (ids_nr < 2) {
10450                                 fprintf(stderr,
10451                                         "%s: at least 2 mirror ids needed with '--only' option.\n",
10452                                         progname);
10453                                 rc = CMD_HELP;
10454                                 goto error;
10455                         }
10456                         break;
10457                 case 'v':
10458                         verbose++;
10459                         break;
10460                 default:
10461                         fprintf(stderr, "%s: option '%s' unrecognized.\n",
10462                                 progname, argv[optind - 1]);
10463                         rc = -EINVAL;
10464                         goto error;
10465                 }
10466         }
10467
10468         if (argc == optind) {
10469                 fprintf(stderr, "%s: no file name given.\n", progname);
10470                 rc = CMD_HELP;
10471                 goto error;
10472         }
10473
10474         if (ids_nr > 0 && argc > optind + 1) {
10475                 fprintf(stderr,
10476                         "%s: '--only' cannot be used upon multiple files.\n",
10477                         progname);
10478                 rc = CMD_HELP;
10479                 goto error;
10480
10481         }
10482
10483         if (ids_nr > 0) {
10484                 rc = verify_mirror_ids(argv[optind], mirror_ids, ids_nr);
10485                 if (rc < 0)
10486                         goto error;
10487         }
10488
10489         rc = 0;
10490         for (; optind < argc; optind++) {
10491                 rc1 = lfs_mirror_verify_file(argv[optind], mirror_ids, ids_nr,
10492                                              verbose);
10493                 if (rc1 < 0)
10494                         rc = rc1;
10495         }
10496 error:
10497         return rc;
10498 }
10499
10500 /**
10501  * lfs_mirror() - Parse and execute lfs mirror commands.
10502  * @argc: The count of lfs mirror command line arguments.
10503  * @argv: Array of strings for lfs mirror command line arguments.
10504  *
10505  * This function parses lfs mirror commands and performs the
10506  * corresponding functions specified in mirror_cmdlist[].
10507  *
10508  * Return: 0 on success or an error code on failure.
10509  */
10510 static int lfs_mirror(int argc, char **argv)
10511 {
10512         char cmd[PATH_MAX];
10513         int rc = 0;
10514
10515         setlinebuf(stdout);
10516
10517         Parser_init("lfs-mirror > ", mirror_cmdlist);
10518
10519         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
10520         progname = cmd;
10521         program_invocation_short_name = cmd;
10522         if (argc > 1)
10523                 rc = Parser_execarg(argc - 1, argv + 1, mirror_cmdlist);
10524         else
10525                 rc = Parser_commands();
10526
10527         return rc < 0 ? -rc : rc;
10528 }
10529
10530 static void lustre_som_swab(struct lustre_som_attrs *attrs)
10531 {
10532 #if __BYTE_ORDER == __BIG_ENDIAN
10533         __swab16s(&attrs->lsa_valid);
10534         __swab64s(&attrs->lsa_size);
10535         __swab64s(&attrs->lsa_blocks);
10536 #endif
10537 }
10538
10539 enum lfs_som_type {
10540         LFS_SOM_SIZE = 0x1,
10541         LFS_SOM_BLOCKS = 0x2,
10542         LFS_SOM_FLAGS = 0x4,
10543         LFS_SOM_ATTR_ALL = LFS_SOM_SIZE | LFS_SOM_BLOCKS |
10544                            LFS_SOM_FLAGS,
10545 };
10546
10547 static int lfs_getsom(int argc, char **argv)
10548 {
10549         const char *path;
10550         struct lustre_som_attrs *attrs;
10551         char buf[sizeof(*attrs) + 64];
10552         enum lfs_som_type type = LFS_SOM_ATTR_ALL;
10553         int rc = 0, c;
10554
10555         while ((c = getopt(argc, argv, "sbf")) != -1) {
10556                 switch (c) {
10557                 case 's':
10558                         type = LFS_SOM_SIZE;
10559                         break;
10560                 case 'b':
10561                         type = LFS_SOM_BLOCKS;
10562                         break;
10563                 case 'f':
10564                         type = LFS_SOM_FLAGS;
10565                         break;
10566                 default:
10567                         fprintf(stderr, "%s: invalid option '%c'\n",
10568                                 progname, optopt);
10569                         return CMD_HELP;
10570                 }
10571         }
10572
10573         argc -= optind;
10574         argv += optind;
10575
10576         if (argc != 1) {
10577                 fprintf(stderr, "%s: %s\n",
10578                         progname, argc == 0 ? "miss file target" :
10579                         "input more than 2 files");
10580                 return CMD_HELP;
10581         }
10582
10583         path = argv[0];
10584         attrs = (void *)buf;
10585         rc = lgetxattr(path, "trusted.som", attrs, sizeof(buf));
10586         if (rc < 0) {
10587                 rc = -errno;
10588                 fprintf(stderr, "%s failed to get som xattr: %s (%d)\n",
10589                         argv[0], strerror(errno), errno);
10590                 return rc;
10591         }
10592
10593         lustre_som_swab(attrs);
10594
10595         switch (type) {
10596         case LFS_SOM_ATTR_ALL:
10597                 printf("file: %s size: %llu blocks: %llu flags: %x\n",
10598                        path, attrs->lsa_size, attrs->lsa_blocks,
10599                        attrs->lsa_valid);
10600                 break;
10601         case LFS_SOM_SIZE:
10602                 printf("%llu\n", attrs->lsa_size);
10603                 break;
10604         case LFS_SOM_BLOCKS:
10605                 printf("%llu\n", attrs->lsa_blocks);
10606                 break;
10607         case LFS_SOM_FLAGS:
10608                 printf("%x\n", attrs->lsa_valid);
10609                 break;
10610         default:
10611                 fprintf(stderr, "%s: unknown option\n", progname);
10612                 return CMD_HELP;
10613         }
10614
10615         return 0;
10616 }
10617
10618 /**
10619  * lfs_mirror_list_commands() - List lfs mirror commands.
10620  * @argc: The count of command line arguments.
10621  * @argv: Array of strings for command line arguments.
10622  *
10623  * This function lists lfs mirror commands defined in mirror_cmdlist[].
10624  *
10625  * Return: 0 on success.
10626  */
10627 static int lfs_mirror_list_commands(int argc, char **argv)
10628 {
10629         char buffer[81] = "";
10630
10631         Parser_list_commands(mirror_cmdlist, buffer, sizeof(buffer),
10632                              NULL, 0, 4);
10633
10634         return 0;
10635 }
10636
10637 static int lfs_pcc_attach(int argc, char **argv)
10638 {
10639         struct option long_opts[] = {
10640         { .val = 'i',   .name = "id",   .has_arg = required_argument },
10641         { .name = NULL } };
10642         int c;
10643         int rc = 0;
10644         __u32 archive_id = 0;
10645         const char *path;
10646         char *end;
10647         char fullpath[PATH_MAX];
10648         enum lu_pcc_type type = LU_PCC_READWRITE;
10649
10650         optind = 0;
10651         while ((c = getopt_long(argc, argv, "i:",
10652                                 long_opts, NULL)) != -1) {
10653                 switch (c) {
10654                 case 'i':
10655                         archive_id = strtoul(optarg, &end, 0);
10656                         if (*end != '\0' || archive_id == 0) {
10657                                 fprintf(stderr, "error: %s: bad archive ID "
10658                                         "'%s'\n", argv[0], optarg);
10659                                 return CMD_HELP;
10660                         }
10661                         break;
10662                 case '?':
10663                         return CMD_HELP;
10664                 default:
10665                         fprintf(stderr, "%s: option '%s' unrecognized\n",
10666                                 argv[0], argv[optind - 1]);
10667                         return CMD_HELP;
10668                 }
10669         }
10670
10671         if (argc <= optind) {
10672                 fprintf(stderr, "%s: must specify one or more file names\n",
10673                         argv[0]);
10674                 return CMD_HELP;
10675         }
10676
10677         while (optind < argc) {
10678                 int rc2;
10679
10680                 path = argv[optind++];
10681                 if (realpath(path, fullpath) == NULL) {
10682                         fprintf(stderr, "%s: could not find path '%s': %s\n",
10683                                 argv[0], path, strerror(errno));
10684                         if (rc == 0)
10685                                 rc = -EINVAL;
10686                         continue;
10687                 }
10688
10689                 rc2 = llapi_pcc_attach(fullpath, archive_id, type);
10690                 if (rc2 < 0) {
10691                         fprintf(stderr, "%s: cannot attach '%s' to PCC "
10692                                 "with archive ID '%u': %s\n", argv[0],
10693                                 path, archive_id, strerror(-rc2));
10694                         if (rc == 0)
10695                                 rc = rc2;
10696                 }
10697         }
10698         return rc;
10699 }
10700
10701 static int lfs_pcc_attach_fid(int argc, char **argv)
10702 {
10703         struct option long_opts[] = {
10704         { .val = 'i',   .name = "id",   .has_arg = required_argument },
10705         { .val = 'm',   .name = "mnt",  .has_arg = required_argument },
10706         { .name = NULL } };
10707         char                     short_opts[] = "i:m:";
10708         int                      c;
10709         int                      rc = 0;
10710         __u32                    archive_id = 0;
10711         char                    *end;
10712         const char              *mntpath = NULL;
10713         const char              *fidstr;
10714         enum lu_pcc_type         type = LU_PCC_READWRITE;
10715
10716         optind = 0;
10717         while ((c = getopt_long(argc, argv, short_opts,
10718                                 long_opts, NULL)) != -1) {
10719                 switch (c) {
10720                 case 'i':
10721                         archive_id = strtoul(optarg, &end, 0);
10722                         if (*end != '\0') {
10723                                 fprintf(stderr, "error: %s: bad archive ID "
10724                                         "'%s'\n", argv[0], optarg);
10725                                 return CMD_HELP;
10726                         }
10727                         break;
10728                 case 'm':
10729                         mntpath = optarg;
10730                         break;
10731                 case '?':
10732                         return CMD_HELP;
10733                 default:
10734                         fprintf(stderr, "%s: option '%s' unrecognized\n",
10735                                 argv[0], argv[optind - 1]);
10736                         return CMD_HELP;
10737                 }
10738         }
10739
10740         if (archive_id == 0) {
10741                 fprintf(stderr, "%s: must specify an archive ID\n", argv[0]);
10742                 return CMD_HELP;
10743         }
10744
10745         if (mntpath == NULL) {
10746                 fprintf(stderr, "%s: must specify Lustre mount point\n",
10747                         argv[0]);
10748                 return CMD_HELP;
10749         }
10750
10751         if (argc <= optind) {
10752                 fprintf(stderr, "%s: must specify one or more fids\n", argv[0]);
10753                 return CMD_HELP;
10754         }
10755
10756         while (optind < argc) {
10757                 int rc2;
10758
10759                 fidstr = argv[optind++];
10760
10761                 rc2 = llapi_pcc_attach_fid_str(mntpath, fidstr,
10762                                                archive_id, type);
10763                 if (rc2 < 0) {
10764                         fprintf(stderr, "%s: cannot attach '%s' on '%s' to PCC "
10765                                 "with archive ID '%u': %s\n", argv[0],
10766                                 fidstr, mntpath, archive_id, strerror(rc2));
10767                 }
10768                 if (rc == 0 && rc2 < 0)
10769                         rc = rc2;
10770         }
10771         return rc;
10772 }
10773
10774 static int lfs_pcc_detach(int argc, char **argv)
10775 {
10776         struct option long_opts[] = {
10777         { .val = 'k',   .name = "keep", .has_arg = no_argument },
10778         { .name = NULL } };
10779         char                     short_opts[] = "k";
10780         int                      c;
10781         int                      rc = 0;
10782         const char              *path;
10783         char                     fullpath[PATH_MAX];
10784         __u32                    detach_opt = PCC_DETACH_OPT_UNCACHE;
10785
10786         optind = 0;
10787         while ((c = getopt_long(argc, argv, short_opts,
10788                                 long_opts, NULL)) != -1) {
10789                 switch (c) {
10790                 case 'k':
10791                         detach_opt = PCC_DETACH_OPT_NONE;
10792                         break;
10793                 case '?':
10794                         return CMD_HELP;
10795                 default:
10796                         fprintf(stderr, "%s: option '%s' unrecognized\n",
10797                                 argv[0], argv[optind - 1]);
10798                         return CMD_HELP;
10799                 }
10800         }
10801
10802         while (optind < argc) {
10803                 int rc2;
10804
10805                 path = argv[optind++];
10806                 if (realpath(path, fullpath) == NULL) {
10807                         fprintf(stderr, "%s: could not find path '%s': %s\n",
10808                                 argv[0], path, strerror(errno));
10809                         if (rc == 0)
10810                                 rc = -EINVAL;
10811                         continue;
10812                 }
10813
10814                 rc2 = llapi_pcc_detach_file(fullpath, detach_opt);
10815                 if (rc2 < 0) {
10816                         rc2 = -errno;
10817                         fprintf(stderr, "%s: cannot detach '%s' from PCC: "
10818                                 "%s\n", argv[0], path, strerror(errno));
10819                         if (rc == 0)
10820                                 rc = rc2;
10821                 }
10822         }
10823         return rc;
10824 }
10825
10826 static int lfs_pcc_detach_fid(int argc, char **argv)
10827 {
10828         struct option long_opts[] = {
10829         { .val = 'k',   .name = "keep", .has_arg = no_argument },
10830         { .name = NULL } };
10831         char             short_opts[] = "k";
10832         int              c;
10833         int              rc = 0;
10834         const char      *fid;
10835         const char      *mntpath;
10836         __u32            detach_opt = PCC_DETACH_OPT_UNCACHE;
10837
10838         optind = 0;
10839         while ((c = getopt_long(argc, argv, short_opts,
10840                                 long_opts, NULL)) != -1) {
10841                 switch (c) {
10842                 case 'k':
10843                         detach_opt = PCC_DETACH_OPT_NONE;
10844                         break;
10845                 case '?':
10846                         return CMD_HELP;
10847                 default:
10848                         fprintf(stderr, "%s: option '%s' unrecognized\n",
10849                                 argv[0], argv[optind - 1]);
10850                         return CMD_HELP;
10851                 }
10852         }
10853
10854         mntpath = argv[optind++];
10855
10856         while (optind < argc) {
10857                 int rc2;
10858
10859                 fid = argv[optind++];
10860
10861                 rc2 = llapi_pcc_detach_fid_str(mntpath, fid, detach_opt);
10862                 if (rc2 < 0) {
10863                         fprintf(stderr, "%s: cannot detach '%s' on '%s' "
10864                                 "from PCC: %s\n", argv[0], fid, mntpath,
10865                                 strerror(-rc2));
10866                         if (rc == 0)
10867                                 rc = rc2;
10868                 }
10869         }
10870         return rc;
10871 }
10872
10873 static int lfs_pcc_state(int argc, char **argv)
10874 {
10875         int                      rc = 0;
10876         const char              *path;
10877         char                     fullpath[PATH_MAX];
10878         struct lu_pcc_state      state;
10879
10880         optind = 1;
10881
10882         if (argc <= 1) {
10883                 fprintf(stderr, "%s: must specify one or more file names\n",
10884                         argv[0]);
10885                 return CMD_HELP;
10886         }
10887
10888         while (optind < argc) {
10889                 int rc2;
10890
10891                 path = argv[optind++];
10892                 if (realpath(path, fullpath) == NULL) {
10893                         fprintf(stderr, "%s: could not find path '%s': %s\n",
10894                                 argv[0], path, strerror(errno));
10895                         if (rc == 0)
10896                                 rc = -EINVAL;
10897                         continue;
10898                 }
10899
10900                 rc2 = llapi_pcc_state_get(fullpath, &state);
10901                 if (rc2 < 0) {
10902                         if (rc == 0)
10903                                 rc = rc2;
10904                         fprintf(stderr, "%s: cannot get PCC state of '%s': "
10905                                 "%s\n", argv[0], path, strerror(-rc2));
10906                         continue;
10907                 }
10908
10909                 printf("file: %s", path);
10910                 printf(", type: %s", pcc_type2string(state.pccs_type));
10911                 if (state.pccs_type == LU_PCC_NONE &&
10912                     state.pccs_open_count == 0) {
10913                         printf("\n");
10914                         continue;
10915                 }
10916
10917                 printf(", PCC file: %s", state.pccs_path);
10918                 printf(", user number: %u", state.pccs_open_count);
10919                 printf(", flags: %x", state.pccs_flags);
10920                 printf("\n");
10921         }
10922         return rc;
10923 }
10924
10925 /**
10926  * lfs_pcc_list_commands() - List lfs pcc commands.
10927  * @argc: The count of command line arguments.
10928  * @argv: Array of strings for command line arguments.
10929  *
10930  * This function lists lfs pcc commands defined in pcc_cmdlist[].
10931  *
10932  * Return: 0 on success.
10933  */
10934 static int lfs_pcc_list_commands(int argc, char **argv)
10935 {
10936         char buffer[81] = "";
10937
10938         Parser_list_commands(pcc_cmdlist, buffer, sizeof(buffer),
10939                              NULL, 0, 4);
10940
10941         return 0;
10942 }
10943
10944 /**
10945  * lfs_pcc() - Parse and execute lfs pcc commands.
10946  * @argc: The count of lfs pcc command line arguments.
10947  * @argv: Array of strings for lfs pcc command line arguments.
10948  *
10949  * This function parses lfs pcc commands and performs the
10950  * corresponding functions specified in pcc_cmdlist[].
10951  *
10952  * Return: 0 on success or an error code on failure.
10953  */
10954 static int lfs_pcc(int argc, char **argv)
10955 {
10956         char cmd[PATH_MAX];
10957         int rc = 0;
10958
10959         setlinebuf(stdout);
10960
10961         Parser_init("lfs-pcc > ", pcc_cmdlist);
10962
10963         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
10964         progname = cmd;
10965         program_invocation_short_name = cmd;
10966         if (argc > 1)
10967                 rc = Parser_execarg(argc - 1, argv + 1, pcc_cmdlist);
10968         else
10969                 rc = Parser_commands();
10970
10971         return rc < 0 ? -rc : rc;
10972 }
10973
10974 static int lfs_list_commands(int argc, char **argv)
10975 {
10976         char buffer[81] = ""; /* 80 printable chars + terminating NUL */
10977
10978         Parser_list_commands(cmdlist, buffer, sizeof(buffer), NULL, 0, 4);
10979
10980         return 0;
10981 }
10982
10983 int main(int argc, char **argv)
10984 {
10985         int rc;
10986
10987         /* Ensure that liblustreapi constructor has run */
10988         if (!llapi_liblustreapi_initialized())
10989                 fprintf(stderr, "liblustreapi was not properly initialized\n");
10990
10991         setlinebuf(stdout);
10992         opterr = 0;
10993
10994         Parser_init("lfs > ", cmdlist);
10995
10996         progname = program_invocation_short_name; /* Used in error messages */
10997         if (argc > 1) {
10998                 llapi_set_command_name(argv[1]);
10999                 rc = Parser_execarg(argc - 1, argv + 1, cmdlist);
11000                 llapi_clear_command_name();
11001         } else {
11002                 rc = Parser_commands();
11003         }
11004
11005         return rc < 0 ? -rc : rc;
11006 }
11007
11008 #ifdef _LUSTRE_IDL_H_
11009 /* Everything we need here should be included by lustreapi.h. */
11010 # error "lfs should not depend on lustre_idl.h"
11011 #endif /* _LUSTRE_IDL_H_ */