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