Whamcloud - gitweb
LU-12624 lod: alloc dir stripes by QoS
[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         return rc1;
7004
7005 }
7006
7007 static int lfs_project(int argc, char **argv)
7008 {
7009         int ret = 0, err = 0, c, i;
7010         struct project_handle_control phc = { 0 };
7011         enum lfs_project_ops_t op;
7012
7013         phc.newline = true;
7014         phc.assign_projid = false;
7015         /* default action */
7016         op = LFS_PROJECT_LIST;
7017
7018         while ((c = getopt(argc, argv, "p:cCsdkr0")) != -1) {
7019                 switch (c) {
7020                 case 'c':
7021                         if (op != LFS_PROJECT_LIST) {
7022                                 fprintf(stderr,
7023                                         "%s: cannot specify '-c' '-C' '-s' together\n",
7024                                         progname);
7025                                 return CMD_HELP;
7026                         }
7027
7028                         op = LFS_PROJECT_CHECK;
7029                         break;
7030                 case 'C':
7031                         if (op != LFS_PROJECT_LIST) {
7032                                 fprintf(stderr,
7033                                         "%s: cannot specify '-c' '-C' '-s' together\n",
7034                                         progname);
7035                                 return CMD_HELP;
7036                         }
7037
7038                         op = LFS_PROJECT_CLEAR;
7039                         break;
7040                 case 's':
7041                         if (op != LFS_PROJECT_LIST) {
7042                                 fprintf(stderr,
7043                                         "%s: cannot specify '-c' '-C' '-s' together\n",
7044                                         progname);
7045                                 return CMD_HELP;
7046                         }
7047
7048                         phc.set_inherit = true;
7049                         op = LFS_PROJECT_SET;
7050                         break;
7051                 case 'd':
7052                         phc.dironly = true;
7053                         break;
7054                 case 'k':
7055                         phc.keep_projid = true;
7056                         break;
7057                 case 'r':
7058                         phc.recursive = true;
7059                         break;
7060                 case 'p':
7061                         phc.projid = strtoul(optarg, NULL, 0);
7062                         phc.assign_projid = true;
7063
7064                         break;
7065                 case '0':
7066                         phc.newline = false;
7067                         break;
7068                 default:
7069                         fprintf(stderr, "%s: invalid option '%c'\n",
7070                                 progname, optopt);
7071                         return CMD_HELP;
7072                 }
7073         }
7074
7075         if (phc.assign_projid && op == LFS_PROJECT_LIST) {
7076                 op = LFS_PROJECT_SET;
7077                 phc.set_projid = true;
7078         } else if (phc.assign_projid && op == LFS_PROJECT_SET) {
7079                 phc.set_projid = true;
7080         }
7081
7082         switch (op) {
7083         case LFS_PROJECT_CHECK:
7084                 if (phc.keep_projid) {
7085                         fprintf(stderr,
7086                                 "%s: '-k' is useless together with '-c'\n",
7087                                 progname);
7088                         return CMD_HELP;
7089                 }
7090                 break;
7091         case LFS_PROJECT_CLEAR:
7092                 if (!phc.newline) {
7093                         fprintf(stderr,
7094                                 "%s: '-0' is useless together with '-C'\n",
7095                                 progname);
7096                         return CMD_HELP;
7097                 }
7098                 if (phc.assign_projid) {
7099                         fprintf(stderr,
7100                                 "%s: '-p' is useless together with '-C'\n",
7101                                 progname);
7102                         return CMD_HELP;
7103                 }
7104                 break;
7105         case LFS_PROJECT_SET:
7106                 if (!phc.newline) {
7107                         fprintf(stderr,
7108                                 "%s: '-0' is useless together with '-s'\n",
7109                                 progname);
7110                         return CMD_HELP;
7111                 }
7112                 if (phc.keep_projid) {
7113                         fprintf(stderr,
7114                                 "%s: '-k' is useless together with '-s'\n",
7115                                 progname);
7116                         return CMD_HELP;
7117                 }
7118                 break;
7119         default:
7120                 if (!phc.newline) {
7121                         fprintf(stderr,
7122                                 "%s: '-0' is useless for list operations\n",
7123                                 progname);
7124                         return CMD_HELP;
7125                 }
7126                 break;
7127         }
7128
7129         argv += optind;
7130         argc -= optind;
7131         if (argc == 0) {
7132                 fprintf(stderr, "%s: missing file or directory target(s)\n",
7133                         progname);
7134                 return CMD_HELP;
7135         }
7136
7137         for (i = 0; i < argc; i++) {
7138                 switch (op) {
7139                 case LFS_PROJECT_CHECK:
7140                         err = lfs_project_check(argv[i], &phc);
7141                         break;
7142                 case LFS_PROJECT_LIST:
7143                         err = lfs_project_list(argv[i], &phc);
7144                         break;
7145                 case LFS_PROJECT_CLEAR:
7146                         err = lfs_project_clear(argv[i], &phc);
7147                         break;
7148                 case LFS_PROJECT_SET:
7149                         err = lfs_project_set(argv[i], &phc);
7150                         break;
7151                 default:
7152                         break;
7153                 }
7154                 if (err && !ret)
7155                         ret = err;
7156         }
7157
7158         return ret;
7159 }
7160
7161 static int lfs_quota(int argc, char **argv)
7162 {
7163         int c;
7164         char *mnt, *name = NULL;
7165         struct if_quotactl qctl = { .qc_cmd = LUSTRE_Q_GETQUOTA,
7166                                     .qc_type = ALLQUOTA };
7167         char *obd_uuid = (char *)qctl.obd_uuid.uuid;
7168         int rc = 0, rc1 = 0, verbose = 0, quiet = 0;
7169         char *endptr;
7170         __u32 valid = QC_GENERAL, idx = 0;
7171         bool human_readable = false;
7172         bool show_default = false;
7173         int qtype;
7174
7175         while ((c = getopt(argc, argv, "gGi:I:o:pPqtuUvh")) != -1) {
7176                 switch (c) {
7177                 case 'U':
7178                         show_default = true;
7179                 case 'u':
7180                         qtype = USRQUOTA;
7181                         goto quota_type;
7182                 case 'G':
7183                         show_default = true;
7184                 case 'g':
7185                         qtype = GRPQUOTA;
7186                         goto quota_type;
7187                 case 'P':
7188                         show_default = true;
7189                 case 'p':
7190                         qtype = PRJQUOTA;
7191 quota_type:
7192                         if (qctl.qc_type != ALLQUOTA) {
7193                                 fprintf(stderr,
7194                                         "%s quota: only one of -u, -g, or -p may be specified\n",
7195                                         progname);
7196                                 return CMD_HELP;
7197                         }
7198                         qctl.qc_type = qtype;
7199                         break;
7200                 case 't':
7201                         qctl.qc_cmd = LUSTRE_Q_GETINFO;
7202                         break;
7203                 case 'o':
7204                         valid = qctl.qc_valid = QC_UUID;
7205                         snprintf(obd_uuid, sizeof(qctl.obd_uuid), "%s", optarg);
7206                         break;
7207                 case 'i':
7208                         valid = qctl.qc_valid = QC_MDTIDX;
7209                         idx = qctl.qc_idx = atoi(optarg);
7210                         if (idx == 0 && *optarg != '0') {
7211                                 fprintf(stderr,
7212                                         "%s quota: invalid MDT index '%s'\n",
7213                                         progname, optarg);
7214                                 return CMD_HELP;
7215                         }
7216                         break;
7217                 case 'I':
7218                         valid = qctl.qc_valid = QC_OSTIDX;
7219                         idx = qctl.qc_idx = atoi(optarg);
7220                         if (idx == 0 && *optarg != '0') {
7221                                 fprintf(stderr,
7222                                         "%s quota: invalid OST index '%s'\n",
7223                                         progname, optarg);
7224                                 return CMD_HELP;
7225                         }
7226                         break;
7227                 case 'v':
7228                         verbose = 1;
7229                         break;
7230                 case 'q':
7231                         quiet = 1;
7232                         break;
7233                 case 'h':
7234                         human_readable = true;
7235                         break;
7236                 default:
7237                         fprintf(stderr, "%s quota: unrecognized option '%s'\n",
7238                                 progname, argv[optind - 1]);
7239                         return CMD_HELP;
7240                 }
7241         }
7242
7243         /* current uid/gid info for "lfs quota /path/to/lustre/mount" */
7244         if (qctl.qc_cmd == LUSTRE_Q_GETQUOTA && qctl.qc_type == ALLQUOTA &&
7245             optind == argc - 1 && !show_default) {
7246
7247                 qctl.qc_cmd = LUSTRE_Q_GETQUOTA;
7248                 qctl.qc_idx = idx;
7249
7250                 for (qtype = USRQUOTA; qtype <= GRPQUOTA; qtype++) {
7251                         qctl.qc_type = qtype;
7252                         qctl.qc_valid = valid;
7253                         if (qtype == USRQUOTA) {
7254                                 qctl.qc_id = geteuid();
7255                                 rc = uid2name(&name, qctl.qc_id);
7256                         } else {
7257                                 qctl.qc_id = getegid();
7258                                 rc = gid2name(&name, qctl.qc_id);
7259                                 memset(&qctl.qc_dqblk, 0,
7260                                        sizeof(qctl.qc_dqblk));
7261                         }
7262                         if (rc)
7263                                 name = "<unknown>";
7264                         mnt = argv[optind];
7265                         rc1 = get_print_quota(mnt, name, &qctl, verbose, quiet,
7266                                               human_readable, show_default);
7267                         if (rc1 && !rc)
7268                                 rc = rc1;
7269                 }
7270                 return rc;
7271         /* lfs quota -u username /path/to/lustre/mount */
7272         } else if (qctl.qc_cmd == LUSTRE_Q_GETQUOTA) {
7273                 /* options should be followed by u/g-name and mntpoint */
7274                 if ((!show_default && optind + 2 != argc) ||
7275                     (show_default && optind + 1 != argc) ||
7276                     qctl.qc_type == ALLQUOTA) {
7277                         fprintf(stderr,
7278                                 "%s quota: name and mount point must be specified\n",
7279                                 progname);
7280                         return CMD_HELP;
7281                 }
7282
7283                 if (!show_default) {
7284                         name = argv[optind++];
7285                         switch (qctl.qc_type) {
7286                         case USRQUOTA:
7287                                 rc = name2uid(&qctl.qc_id, name);
7288                                 break;
7289                         case GRPQUOTA:
7290                                 rc = name2gid(&qctl.qc_id, name);
7291                                 break;
7292                         case PRJQUOTA:
7293                                 rc = name2projid(&qctl.qc_id, name);
7294                                 break;
7295                         default:
7296                                 rc = -ENOTSUP;
7297                                 break;
7298                         }
7299                 } else {
7300                         qctl.qc_valid = QC_GENERAL;
7301                         qctl.qc_cmd = LUSTRE_Q_GETDEFAULT;
7302                         qctl.qc_id = 0;
7303                 }
7304
7305                 if (rc) {
7306                         qctl.qc_id = strtoul(name, &endptr, 10);
7307                         if (*endptr != '\0') {
7308                                 fprintf(stderr, "%s quota: invalid id '%s'\n",
7309                                         progname, name);
7310                                 return CMD_HELP;
7311                         }
7312                 }
7313         } else if (optind + 1 != argc || qctl.qc_type == ALLQUOTA) {
7314                 fprintf(stderr, "%s quota: missing quota info argument(s)\n",
7315                         progname);
7316                 return CMD_HELP;
7317         }
7318
7319         mnt = argv[optind];
7320         rc = get_print_quota(mnt, name, &qctl, verbose, quiet,
7321                              human_readable, show_default);
7322         return rc;
7323 }
7324 #endif /* HAVE_SYS_QUOTA_H! */
7325
7326 static int flushctx_ioctl(char *mp)
7327 {
7328         int fd, rc;
7329
7330         fd = open(mp, O_RDONLY);
7331         if (fd == -1) {
7332                 fprintf(stderr, "flushctx: error open %s: %s\n",
7333                         mp, strerror(errno));
7334                 return -1;
7335         }
7336
7337         rc = ioctl(fd, LL_IOC_FLUSHCTX);
7338         if (rc == -1)
7339                 fprintf(stderr, "flushctx: error ioctl %s: %s\n",
7340                         mp, strerror(errno));
7341
7342         close(fd);
7343         return rc;
7344 }
7345
7346 static int lfs_flushctx(int argc, char **argv)
7347 {
7348         int     kdestroy = 0, c;
7349         char    mntdir[PATH_MAX] = {'\0'};
7350         int     index = 0;
7351         int     rc = 0;
7352
7353         while ((c = getopt(argc, argv, "k")) != -1) {
7354                 switch (c) {
7355                 case 'k':
7356                         kdestroy = 1;
7357                         break;
7358                 default:
7359                         fprintf(stderr, "error: %s: option '-%c' "
7360                                         "unrecognized\n", argv[0], c);
7361                         return CMD_HELP;
7362                 }
7363         }
7364
7365         if (kdestroy) {
7366             if ((rc = system("kdestroy > /dev/null")) != 0) {
7367                 rc = WEXITSTATUS(rc);
7368                 fprintf(stderr, "error destroying tickets: %d, continuing\n", rc);
7369             }
7370         }
7371
7372         if (optind >= argc) {
7373                 /* flush for all mounted lustre fs. */
7374                 while (!llapi_search_mounts(NULL, index++, mntdir, NULL)) {
7375                         /* Check if we have a mount point */
7376                         if (mntdir[0] == '\0')
7377                                 continue;
7378
7379                         if (flushctx_ioctl(mntdir))
7380                                 rc = -1;
7381
7382                         mntdir[0] = '\0'; /* avoid matching in next loop */
7383                 }
7384         } else {
7385                 /* flush fs as specified */
7386                 while (optind < argc) {
7387                         if (flushctx_ioctl(argv[optind++]))
7388                                 rc = -1;
7389                 }
7390         }
7391         return rc;
7392 }
7393
7394 static int lfs_changelog(int argc, char **argv)
7395 {
7396         void *changelog_priv;
7397         struct changelog_rec *rec;
7398         long long startrec = 0, endrec = 0;
7399         char *mdd;
7400         struct option long_opts[] = {
7401                 { .val = 'f', .name = "follow", .has_arg = no_argument },
7402                 { .name = NULL } };
7403         char short_opts[] = "f";
7404         int rc, follow = 0;
7405
7406         while ((rc = getopt_long(argc, argv, short_opts,
7407                 long_opts, NULL)) != -1) {
7408                 switch (rc) {
7409                 case 'f':
7410                         follow++;
7411                         break;
7412                 default:
7413                         fprintf(stderr,
7414                                 "%s changelog: unrecognized option '%s'\n",
7415                                 progname, argv[optind - 1]);
7416                         return CMD_HELP;
7417                 }
7418         }
7419         if (optind >= argc) {
7420                 fprintf(stderr, "%s changelog: mdtname must be specified\n",
7421                         progname);
7422                 return CMD_HELP;
7423         }
7424
7425         mdd = argv[optind++];
7426         if (argc > optind)
7427                 startrec = strtoll(argv[optind++], NULL, 10);
7428         if (argc > optind)
7429                 endrec = strtoll(argv[optind++], NULL, 10);
7430
7431         rc = llapi_changelog_start(&changelog_priv,
7432                                    CHANGELOG_FLAG_BLOCK |
7433                                    CHANGELOG_FLAG_JOBID |
7434                                    CHANGELOG_FLAG_EXTRA_FLAGS |
7435                                    (follow ? CHANGELOG_FLAG_FOLLOW : 0),
7436                                    mdd, startrec);
7437         if (rc < 0) {
7438                 fprintf(stderr, "%s changelog: cannot start changelog: %s\n",
7439                         progname, strerror(errno = -rc));
7440                 return rc;
7441         }
7442
7443         rc = llapi_changelog_set_xflags(changelog_priv,
7444                                         CHANGELOG_EXTRA_FLAG_UIDGID |
7445                                         CHANGELOG_EXTRA_FLAG_NID |
7446                                         CHANGELOG_EXTRA_FLAG_OMODE |
7447                                         CHANGELOG_EXTRA_FLAG_XATTR);
7448         if (rc < 0) {
7449                 fprintf(stderr,
7450                         "%s changelog: cannot set xflags for changelog: %s\n",
7451                         progname, strerror(errno = -rc));
7452                 return rc;
7453         }
7454
7455         while ((rc = llapi_changelog_recv(changelog_priv, &rec)) == 0) {
7456                 time_t secs;
7457                 struct tm ts;
7458
7459                 if (endrec && rec->cr_index > endrec) {
7460                         llapi_changelog_free(&rec);
7461                         break;
7462                 }
7463                 if (rec->cr_index < startrec) {
7464                         llapi_changelog_free(&rec);
7465                         continue;
7466                 }
7467
7468                 secs = rec->cr_time >> 30;
7469                 gmtime_r(&secs, &ts);
7470                 printf("%ju %02d%-5s %02d:%02d:%02d.%09d %04d.%02d.%02d "
7471                        "0x%x t="DFID, (uintmax_t)rec->cr_index, rec->cr_type,
7472                        changelog_type2str(rec->cr_type),
7473                        ts.tm_hour, ts.tm_min, ts.tm_sec,
7474                        (int)(rec->cr_time & ((1 << 30) - 1)),
7475                        ts.tm_year + 1900, ts.tm_mon + 1, ts.tm_mday,
7476                        rec->cr_flags & CLF_FLAGMASK, PFID(&rec->cr_tfid));
7477
7478                 if (rec->cr_flags & CLF_JOBID) {
7479                         struct changelog_ext_jobid *jid =
7480                                 changelog_rec_jobid(rec);
7481
7482                         if (jid->cr_jobid[0] != '\0')
7483                                 printf(" j=%s", jid->cr_jobid);
7484                 }
7485
7486                 if (rec->cr_flags & CLF_EXTRA_FLAGS) {
7487                         struct changelog_ext_extra_flags *ef =
7488                                 changelog_rec_extra_flags(rec);
7489
7490                         printf(" ef=0x%llx",
7491                                (unsigned long long)ef->cr_extra_flags);
7492
7493                         if (ef->cr_extra_flags & CLFE_UIDGID) {
7494                                 struct changelog_ext_uidgid *uidgid =
7495                                         changelog_rec_uidgid(rec);
7496
7497                                 printf(" u=%llu:%llu",
7498                                        (unsigned long long)uidgid->cr_uid,
7499                                        (unsigned long long)uidgid->cr_gid);
7500                         }
7501                         if (ef->cr_extra_flags & CLFE_NID) {
7502                                 struct changelog_ext_nid *nid =
7503                                         changelog_rec_nid(rec);
7504
7505                                 printf(" nid=%s",
7506                                        libcfs_nid2str(nid->cr_nid));
7507                         }
7508
7509                         if (ef->cr_extra_flags & CLFE_OPEN) {
7510                                 struct changelog_ext_openmode *omd =
7511                                         changelog_rec_openmode(rec);
7512                                 char mode[] = "---";
7513
7514                                 /* exec mode must be exclusive */
7515                                 if (omd->cr_openflags & MDS_FMODE_EXEC) {
7516                                         mode[2] = 'x';
7517                                 } else {
7518                                         if (omd->cr_openflags & MDS_FMODE_READ)
7519                                                 mode[0] = 'r';
7520                                         if (omd->cr_openflags &
7521                                             (MDS_FMODE_WRITE |
7522                                              MDS_OPEN_TRUNC |
7523                                              MDS_OPEN_APPEND))
7524                                                 mode[1] = 'w';
7525                                 }
7526
7527                                 if (strcmp(mode, "---") != 0)
7528                                         printf(" m=%s", mode);
7529
7530                         }
7531
7532                         if (ef->cr_extra_flags & CLFE_XATTR) {
7533                                 struct changelog_ext_xattr *xattr =
7534                                         changelog_rec_xattr(rec);
7535
7536                                 if (xattr->cr_xattr[0] != '\0')
7537                                         printf(" x=%s", xattr->cr_xattr);
7538                         }
7539                 }
7540
7541                 if (rec->cr_namelen)
7542                         printf(" p="DFID" %.*s", PFID(&rec->cr_pfid),
7543                                rec->cr_namelen, changelog_rec_name(rec));
7544
7545                 if (rec->cr_flags & CLF_RENAME) {
7546                         struct changelog_ext_rename *rnm =
7547                                 changelog_rec_rename(rec);
7548
7549                         if (!fid_is_zero(&rnm->cr_sfid))
7550                                 printf(" s="DFID" sp="DFID" %.*s",
7551                                        PFID(&rnm->cr_sfid),
7552                                        PFID(&rnm->cr_spfid),
7553                                        (int)changelog_rec_snamelen(rec),
7554                                        changelog_rec_sname(rec));
7555                 }
7556                 printf("\n");
7557
7558                 llapi_changelog_free(&rec);
7559         }
7560
7561         llapi_changelog_fini(&changelog_priv);
7562
7563         if (rc < 0)
7564                 fprintf(stderr, "%s changelog: cannot access changelog: %s\n",
7565                         progname, strerror(errno = -rc));
7566
7567         return (rc == 1 ? 0 : rc);
7568 }
7569
7570 static int lfs_changelog_clear(int argc, char **argv)
7571 {
7572         long long endrec;
7573         int rc;
7574
7575         if (argc != 4)
7576                 return CMD_HELP;
7577
7578         endrec = strtoll(argv[3], NULL, 10);
7579
7580         rc = llapi_changelog_clear(argv[1], argv[2], endrec);
7581
7582         if (rc == -EINVAL)
7583                 fprintf(stderr, "%s: record out of range: %llu\n",
7584                         argv[0], endrec);
7585         else if (rc == -ENOENT)
7586                 fprintf(stderr, "%s: no changelog user: %s\n",
7587                         argv[0], argv[2]);
7588         else if (rc)
7589                 fprintf(stderr, "%s error: %s\n", argv[0],
7590                         strerror(-rc));
7591
7592         if (rc)
7593                 errno = -rc;
7594
7595         return rc;
7596 }
7597
7598 static int lfs_fid2path(int argc, char **argv)
7599 {
7600         struct option long_opts[] = {
7601                 { .val = 'c',   .name = "cur",  .has_arg = no_argument },
7602                 { .val = 'l',   .name = "link", .has_arg = required_argument },
7603                 { .val = 'r',   .name = "rec",  .has_arg = required_argument },
7604                 { .name = NULL } };
7605         char  short_opts[] = "cl:r:";
7606         char *device, *fid, *path;
7607         long long recno = -1;
7608         int linkno = -1;
7609         int lnktmp;
7610         int printcur = 0;
7611         int rc = 0;
7612         char *endptr = NULL;
7613
7614         while ((rc = getopt_long(argc, argv, short_opts,
7615                 long_opts, NULL)) != -1) {
7616                 switch (rc) {
7617                 case 'c':
7618                         printcur++;
7619                         break;
7620                 case 'l':
7621                         linkno = strtol(optarg, &endptr, 10);
7622                         if (*endptr != '\0') {
7623                                 fprintf(stderr,
7624                                         "%s fid2path: invalid linkno '%s'\n",
7625                                         progname, optarg);
7626                                 return CMD_HELP;
7627                         }
7628                         break;
7629                 case 'r':
7630                         recno = strtoll(optarg, &endptr, 10);
7631                         if (*endptr != '\0') {
7632                                 fprintf(stderr,
7633                                         "%s fid2path: invalid recno '%s'\n",
7634                                         progname, optarg);
7635                                 return CMD_HELP;
7636                         }
7637                         break;
7638                 default:
7639                         fprintf(stderr,
7640                                 "%s fid2path: unrecognized option '%s'\n",
7641                                 progname, argv[optind - 1]);
7642                         return CMD_HELP;
7643                 }
7644         }
7645
7646         if (argc < 3) {
7647                 fprintf(stderr,
7648                         "%s fid2path: <fsname|rootpath> and <fid>... must be specified\n",
7649                         progname);
7650                 return CMD_HELP;
7651         }
7652
7653         device = argv[optind++];
7654         path = calloc(1, PATH_MAX);
7655         if (path == NULL) {
7656                 rc = -errno;
7657                 fprintf(stderr,
7658                         "%s fid2path: cannot allocate memory for path: %s\n",
7659                         progname, strerror(-rc));
7660                 return rc;
7661         }
7662
7663         rc = 0;
7664         while (optind < argc) {
7665                 fid = argv[optind++];
7666
7667                 lnktmp = (linkno >= 0) ? linkno : 0;
7668                 while (1) {
7669                         int oldtmp = lnktmp;
7670                         long long rectmp = recno;
7671                         int rc2;
7672                         rc2 = llapi_fid2path(device, fid, path, PATH_MAX,
7673                                              &rectmp, &lnktmp);
7674                         if (rc2 < 0) {
7675                                 fprintf(stderr,
7676                                         "%s fid2path: cannot find '%s': %s\n",
7677                                         progname, fid, strerror(errno = -rc2));
7678                                 if (rc == 0)
7679                                         rc = rc2;
7680                                 break;
7681                         }
7682
7683                         if (printcur)
7684                                 fprintf(stdout, "%lld ", rectmp);
7685                         if (device[0] == '/') {
7686                                 fprintf(stdout, "%s", device);
7687                                 if (device[strlen(device) - 1] != '/')
7688                                         fprintf(stdout, "/");
7689                         } else if (path[0] == '\0') {
7690                                 fprintf(stdout, "/");
7691                         }
7692                         fprintf(stdout, "%s\n", path);
7693
7694                         if (linkno >= 0)
7695                                 /* specified linkno */
7696                                 break;
7697                         if (oldtmp == lnktmp)
7698                                 /* no more links */
7699                                 break;
7700                 }
7701         }
7702
7703         free(path);
7704         return rc;
7705 }
7706
7707 static int lfs_path2fid(int argc, char **argv)
7708 {
7709         struct option long_opts[] = {
7710                 { .val = 'p', .name = "parents", .has_arg = no_argument },
7711                 { .name = NULL } };
7712         char            **path;
7713         const char        short_opts[] = "p";
7714         const char       *sep = "";
7715         struct lu_fid     fid;
7716         int               rc = 0;
7717         bool              show_parents = false;
7718
7719         while ((rc = getopt_long(argc, argv, short_opts,
7720                                  long_opts, NULL)) != -1) {
7721                 switch (rc) {
7722                 case 'p':
7723                         show_parents = true;
7724                         break;
7725                 default:
7726                         fprintf(stderr,
7727                                 "%s path2fid: unrecognized option '%s'\n",
7728                                 progname, argv[optind - 1]);
7729                         return CMD_HELP;
7730                 }
7731         }
7732
7733         if (optind > argc - 1) {
7734                 fprintf(stderr, "%s path2fid: FILE... must be specified\n",
7735                         progname);
7736                 return CMD_HELP;
7737         }
7738         else if (optind < argc - 1)
7739                 sep = ": ";
7740
7741         rc = 0;
7742         for (path = argv + optind; *path != NULL; path++) {
7743                 int err = 0;
7744                 if (!show_parents) {
7745                         err = llapi_path2fid(*path, &fid);
7746                         if (!err)
7747                                 printf("%s%s"DFID"\n",
7748                                        *sep != '\0' ? *path : "", sep,
7749                                        PFID(&fid));
7750                 } else {
7751                         char            name[NAME_MAX + 1];
7752                         unsigned int    linkno = 0;
7753
7754                         while ((err = llapi_path2parent(*path, linkno, &fid,
7755                                                 name, sizeof(name))) == 0) {
7756                                 if (*sep != '\0' && linkno == 0)
7757                                         printf("%s%s", *path, sep);
7758
7759                                 printf("%s"DFID"/%s", linkno != 0 ? "\t" : "",
7760                                        PFID(&fid), name);
7761                                 linkno++;
7762                         }
7763
7764                         /* err == -ENODATA is end-of-loop */
7765                         if (linkno > 0 && err == -ENODATA) {
7766                                 printf("\n");
7767                                 err = 0;
7768                         }
7769                 }
7770
7771                 if (err) {
7772                         fprintf(stderr,
7773                                 "%s path2fid: cannot get %sfid for '%s': %s\n",
7774                                 progname, show_parents ? "parent " : "", *path,
7775                                 strerror(-err));
7776                         if (rc == 0) {
7777                                 rc = err;
7778                                 errno = -err;
7779                         }
7780                 }
7781         }
7782
7783         return rc;
7784 }
7785
7786 #define MAX_ERRNO       4095
7787 #define IS_ERR_VALUE(x) ((unsigned long)(x) >= (unsigned long)-MAX_ERRNO)
7788
7789 static int lfs_rmfid_and_show_errors(const char *device, struct fid_array *fa)
7790 {
7791         int rc, rc2 = 0, k;
7792
7793         rc = llapi_rmfid(device, fa);
7794         if (rc) {
7795                 fprintf(stderr, "rmfid(): rc = %d\n", rc);
7796                 return rc;
7797         }
7798
7799         for (k = 0; k < fa->fa_nr; k++) {
7800                 rc = (__s32)fa->fa_fids[k].f_ver;
7801                 if (!IS_ERR_VALUE(rc))
7802                         continue;
7803                 if (!rc2 && rc)
7804                         rc2 = rc;
7805                 if (!rc)
7806                         continue;
7807                 fa->fa_fids[k].f_ver = 0;
7808                 fprintf(stderr, "rmfid("DFID"): rc = %d\n",
7809                         PFID(&fa->fa_fids[k]), rc);
7810         }
7811
7812         return rc2;
7813 }
7814
7815 static int lfs_rmfid(int argc, char **argv)
7816 {
7817         char *fidstr, *device;
7818         int rc = 0, rc2, nr;
7819         struct fid_array *fa;
7820
7821         if (optind > argc - 1) {
7822                 fprintf(stderr, "%s rmfid: missing dirname\n", progname);
7823                 return CMD_HELP;
7824         }
7825
7826         device = argv[optind++];
7827
7828         nr = argc - optind;
7829         fa = malloc(offsetof(struct fid_array, fa_fids[nr + 1]));
7830         if (fa == NULL)
7831                 return -ENOMEM;
7832
7833         fa->fa_nr = 0;
7834         rc = 0;
7835         while (optind < argc) {
7836                 int found;
7837
7838                 fidstr = argv[optind++];
7839                 while (*fidstr == '[')
7840                         fidstr++;
7841                 found = sscanf(fidstr, SFID, RFID(&fa->fa_fids[fa->fa_nr]));
7842                 if (found != 3) {
7843                         fprintf(stderr, "unrecognized FID: %s\n",
7844                                 argv[optind - 1]);
7845                         exit(1);
7846                 }
7847                 fa->fa_nr++;
7848                 if (fa->fa_nr == OBD_MAX_FIDS_IN_ARRAY) {
7849                         /* start another batch */
7850                         rc2 = lfs_rmfid_and_show_errors(device, fa);
7851                         if (rc2 && !rc)
7852                                 rc = rc2;
7853                         fa->fa_nr = 0;
7854                 }
7855         }
7856         if (fa->fa_nr) {
7857                 rc2 = lfs_rmfid_and_show_errors(device, fa);
7858                 if (rc2 && !rc)
7859                         rc = rc2;
7860         }
7861
7862         return rc;
7863 }
7864
7865 static int lfs_data_version(int argc, char **argv)
7866 {
7867         char *path;
7868         __u64 data_version;
7869         int fd;
7870         int rc;
7871         int c;
7872         int data_version_flags = LL_DV_RD_FLUSH; /* Read by default */
7873
7874         if (argc < 2) {
7875                 fprintf(stderr, "%s data_version: FILE must be specified\n",
7876                         progname);
7877                 return CMD_HELP;
7878         }
7879
7880         while ((c = getopt(argc, argv, "nrw")) != -1) {
7881                 switch (c) {
7882                 case 'n':
7883                         data_version_flags = 0;
7884                         break;
7885                 case 'r':
7886                         data_version_flags |= LL_DV_RD_FLUSH;
7887                         break;
7888                 case 'w':
7889                         data_version_flags |= LL_DV_WR_FLUSH;
7890                         break;
7891                 default:
7892                         fprintf(stderr,
7893                                 "%s data_version: unrecognized option '%s'\n",
7894                                 progname, argv[optind - 1]);
7895                         return CMD_HELP;
7896                 }
7897         }
7898         if (optind == argc) {
7899                 fprintf(stderr, "%s data_version: FILE must be specified\n",
7900                         progname);
7901                 return CMD_HELP;
7902         }
7903
7904         path = argv[optind];
7905         fd = open(path, O_RDONLY);
7906         if (fd < 0) {
7907                 rc = -errno;
7908                 fprintf(stderr, "%s data_version: cannot open file '%s': %s\n",
7909                         progname, path, strerror(-rc));
7910                 return rc;
7911         }
7912
7913         rc = llapi_get_data_version(fd, &data_version, data_version_flags);
7914         if (rc < 0)
7915                 fprintf(stderr,
7916                         "%s data_version: cannot get version for '%s': %s\n",
7917                         progname, path, strerror(-rc));
7918         else
7919                 printf("%ju" "\n", (uintmax_t)data_version);
7920
7921         close(fd);
7922         return rc;
7923 }
7924
7925 static int lfs_hsm_state(int argc, char **argv)
7926 {
7927         int rc;
7928         int i = 1;
7929         char *path;
7930         struct hsm_user_state hus;
7931
7932         if (argc < 2)
7933                 return CMD_HELP;
7934
7935         do {
7936                 path = argv[i];
7937
7938                 rc = llapi_hsm_state_get(path, &hus);
7939                 if (rc) {
7940                         fprintf(stderr, "can't get hsm state for %s: %s\n",
7941                                 path, strerror(errno = -rc));
7942                         return rc;
7943                 }
7944
7945                 /* Display path name and status flags */
7946                 printf("%s: (0x%08x)", path, hus.hus_states);
7947
7948                 if (hus.hus_states & HS_RELEASED)
7949                         printf(" released");
7950                 if (hus.hus_states & HS_EXISTS)
7951                         printf(" exists");
7952                 if (hus.hus_states & HS_DIRTY)
7953                         printf(" dirty");
7954                 if (hus.hus_states & HS_ARCHIVED)
7955                         printf(" archived");
7956                 /* Display user-settable flags */
7957                 if (hus.hus_states & HS_NORELEASE)
7958                         printf(" never_release");
7959                 if (hus.hus_states & HS_NOARCHIVE)
7960                         printf(" never_archive");
7961                 if (hus.hus_states & HS_LOST)
7962                         printf(" lost_from_hsm");
7963
7964                 if (hus.hus_archive_id != 0)
7965                         printf(", archive_id:%d", hus.hus_archive_id);
7966                 printf("\n");
7967
7968         } while (++i < argc);
7969
7970         return 0;
7971 }
7972
7973 #define LFS_HSM_SET   0
7974 #define LFS_HSM_CLEAR 1
7975
7976 /**
7977  * Generic function to set or clear HSM flags.
7978  * Used by hsm_set and hsm_clear.
7979  *
7980  * @mode  if LFS_HSM_SET, set the flags, if LFS_HSM_CLEAR, clear the flags.
7981  */
7982 static int lfs_hsm_change_flags(int argc, char **argv, int mode)
7983 {
7984         struct option long_opts[] = {
7985         { .val = 'A',   .name = "archived",     .has_arg = no_argument },
7986         { .val = 'a',   .name = "noarchive",    .has_arg = no_argument },
7987         { .val = 'd',   .name = "dirty",        .has_arg = no_argument },
7988         { .val = 'e',   .name = "exists",       .has_arg = no_argument },
7989         { .val = 'l',   .name = "lost",         .has_arg = no_argument },
7990         { .val = 'r',   .name = "norelease",    .has_arg = no_argument },
7991         { .val = 'i',   .name = "archive-id",   .has_arg = required_argument },
7992         { .name = NULL } };
7993         char short_opts[] = "lraAdei:";
7994         __u64 mask = 0;
7995         int c, rc;
7996         char *path;
7997         __u32 archive_id = 0;
7998         char *end = NULL;
7999
8000         if (argc < 3)
8001                 return CMD_HELP;
8002
8003         while ((c = getopt_long(argc, argv, short_opts,
8004                                 long_opts, NULL)) != -1) {
8005                 switch (c) {
8006                 case 'l':
8007                         mask |= HS_LOST;
8008                         break;
8009                 case 'a':
8010                         mask |= HS_NOARCHIVE;
8011                         break;
8012                 case 'A':
8013                         mask |= HS_ARCHIVED;
8014                         break;
8015                 case 'r':
8016                         mask |= HS_NORELEASE;
8017                         break;
8018                 case 'd':
8019                         mask |= HS_DIRTY;
8020                         break;
8021                 case 'e':
8022                         mask |= HS_EXISTS;
8023                         break;
8024                 case 'i':
8025                         archive_id = strtol(optarg, &end, 10);
8026                         if (*end != '\0') {
8027                                 fprintf(stderr, "invalid archive_id: '%s'\n",
8028                                         end);
8029                                 return CMD_HELP;
8030                         }
8031                         break;
8032                 case '?':
8033                         return CMD_HELP;
8034                 default:
8035                         fprintf(stderr, "error: %s: option '%s' unrecognized\n",
8036                                 argv[0], argv[optind - 1]);
8037                         return CMD_HELP;
8038                 }
8039         }
8040
8041         /* User should have specified a flag */
8042         if (mask == 0)
8043                 return CMD_HELP;
8044
8045         while (optind < argc) {
8046
8047                 path = argv[optind];
8048
8049                 /* If mode == 0, this means we apply the mask. */
8050                 if (mode == LFS_HSM_SET)
8051                         rc = llapi_hsm_state_set(path, mask, 0, archive_id);
8052                 else
8053                         rc = llapi_hsm_state_set(path, 0, mask, 0);
8054
8055                 if (rc != 0) {
8056                         fprintf(stderr, "Can't change hsm flags for %s: %s\n",
8057                                 path, strerror(errno = -rc));
8058                         return rc;
8059                 }
8060                 optind++;
8061         }
8062
8063         return 0;
8064 }
8065
8066 static int lfs_hsm_action(int argc, char **argv)
8067 {
8068         int                              rc;
8069         int                              i = 1;
8070         char                            *path;
8071         struct hsm_current_action        hca;
8072         struct hsm_extent                he;
8073         enum hsm_user_action             hua;
8074         enum hsm_progress_states         hps;
8075
8076         if (argc < 2)
8077                 return CMD_HELP;
8078
8079         do {
8080                 path = argv[i];
8081
8082                 rc = llapi_hsm_current_action(path, &hca);
8083                 if (rc) {
8084                         fprintf(stderr, "can't get hsm action for %s: %s\n",
8085                                 path, strerror(errno = -rc));
8086                         return rc;
8087                 }
8088                 he = hca.hca_location;
8089                 hua = hca.hca_action;
8090                 hps = hca.hca_state;
8091
8092                 printf("%s: %s", path, hsm_user_action2name(hua));
8093
8094                 /* Skip file without action */
8095                 if (hca.hca_action == HUA_NONE) {
8096                         printf("\n");
8097                         continue;
8098                 }
8099
8100                 printf(" %s ", hsm_progress_state2name(hps));
8101
8102                 if ((hps == HPS_RUNNING) &&
8103                     (hua == HUA_ARCHIVE || hua == HUA_RESTORE))
8104                         printf("(%llu bytes moved)\n",
8105                                (unsigned long long)he.length);
8106                 else if ((he.offset + he.length) == LUSTRE_EOF)
8107                         printf("(from %llu to EOF)\n",
8108                                (unsigned long long)he.offset);
8109                 else
8110                         printf("(from %llu to %llu)\n",
8111                                (unsigned long long)he.offset,
8112                                (unsigned long long)(he.offset + he.length));
8113
8114         } while (++i < argc);
8115
8116         return 0;
8117 }
8118
8119 static int lfs_hsm_set(int argc, char **argv)
8120 {
8121         return lfs_hsm_change_flags(argc, argv, LFS_HSM_SET);
8122 }
8123
8124 static int lfs_hsm_clear(int argc, char **argv)
8125 {
8126         return lfs_hsm_change_flags(argc, argv, LFS_HSM_CLEAR);
8127 }
8128
8129 /**
8130  * Check file state and return its fid, to be used by lfs_hsm_request().
8131  *
8132  * \param[in]     file      Path to file to check
8133  * \param[in,out] fid       Pointer to allocated lu_fid struct.
8134  * \param[in,out] last_dev  Pointer to last device id used.
8135  *
8136  * \return 0 on success.
8137  */
8138 static int lfs_hsm_prepare_file(const char *file, struct lu_fid *fid,
8139                                 dev_t *last_dev)
8140 {
8141         struct stat     st;
8142         int             rc;
8143
8144         rc = lstat(file, &st);
8145         if (rc) {
8146                 fprintf(stderr, "Cannot stat %s: %s\n", file, strerror(errno));
8147                 return -errno;
8148         }
8149         /* Checking for regular file as archiving as posix copytool
8150          * rejects archiving files other than regular files
8151          */
8152         if (!S_ISREG(st.st_mode)) {
8153                 fprintf(stderr, "error: \"%s\" is not a regular file\n", file);
8154                 return CMD_HELP;
8155         }
8156         /* A request should be ... */
8157         if (*last_dev != st.st_dev && *last_dev != 0) {
8158                 fprintf(stderr, "All files should be "
8159                         "on the same filesystem: %s\n", file);
8160                 return -EINVAL;
8161         }
8162         *last_dev = st.st_dev;
8163
8164         rc = llapi_path2fid(file, fid);
8165         if (rc) {
8166                 fprintf(stderr, "Cannot read FID of %s: %s\n",
8167                         file, strerror(-rc));
8168                 return rc;
8169         }
8170         return 0;
8171 }
8172
8173 /* Fill an HSM HUR item with a given file name.
8174  *
8175  * If mntpath is set, then the filename is actually a FID, and no
8176  * lookup on the filesystem will be performed.
8177  *
8178  * \param[in]  hur         the user request to fill
8179  * \param[in]  idx         index of the item inside the HUR to fill
8180  * \param[in]  mntpath     mountpoint of Lustre
8181  * \param[in]  fname       filename (if mtnpath is NULL)
8182  *                         or FID (if mntpath is set)
8183  * \param[in]  last_dev    pointer to last device id used
8184  *
8185  * \retval 0 on success
8186  * \retval CMD_HELP or a negative errno on error
8187  */
8188 static int fill_hur_item(struct hsm_user_request *hur, unsigned int idx,
8189                          const char *mntpath, const char *fname,
8190                          dev_t *last_dev)
8191 {
8192         struct hsm_user_item *hui = &hur->hur_user_item[idx];
8193         int rc;
8194
8195         hui->hui_extent.length = -1;
8196
8197         if (mntpath != NULL) {
8198                 if (*fname == '[')
8199                         fname++;
8200                 rc = sscanf(fname, SFID, RFID(&hui->hui_fid));
8201                 if (rc == 3) {
8202                         rc = 0;
8203                 } else {
8204                         fprintf(stderr, "hsm: '%s' is not a valid FID\n",
8205                                 fname);
8206                         rc = -EINVAL;
8207                 }
8208         } else {
8209                 rc = lfs_hsm_prepare_file(fname, &hui->hui_fid, last_dev);
8210         }
8211
8212         if (rc == 0)
8213                 hur->hur_request.hr_itemcount++;
8214
8215         return rc;
8216 }
8217
8218 static int lfs_hsm_request(int argc, char **argv, int action)
8219 {
8220         struct option long_opts[] = {
8221         { .val = 'a',   .name = "archive",      .has_arg = required_argument },
8222         { .val = 'D',   .name = "data",         .has_arg = required_argument },
8223         { .val = 'l',   .name = "filelist",     .has_arg = required_argument },
8224         { .val = 'm',   .name = "mntpath",      .has_arg = required_argument },
8225         { .name = NULL } };
8226         dev_t                    last_dev = 0;
8227         char                     short_opts[] = "l:D:a:m:";
8228         struct hsm_user_request *hur, *oldhur;
8229         int                      c, i;
8230         size_t                   len;
8231         int                      nbfile;
8232         char                    *line = NULL;
8233         char                    *filelist = NULL;
8234         char                     fullpath[PATH_MAX];
8235         char                    *opaque = NULL;
8236         int                      opaque_len = 0;
8237         int                      archive_id = 0;
8238         FILE                    *fp;
8239         int                      nbfile_alloc = 0;
8240         char                    *some_file = NULL;
8241         char                    *mntpath = NULL;
8242         int                      rc;
8243
8244         if (argc < 2)
8245                 return CMD_HELP;
8246
8247         while ((c = getopt_long(argc, argv, short_opts,
8248                                 long_opts, NULL)) != -1) {
8249                 switch (c) {
8250                 case 'l':
8251                         filelist = optarg;
8252                         break;
8253                 case 'D':
8254                         opaque = optarg;
8255                         break;
8256                 case 'a':
8257                         if (action != HUA_ARCHIVE &&
8258                             action != HUA_REMOVE) {
8259                                 fprintf(stderr,
8260                                         "error: -a is supported only "
8261                                         "when archiving or removing\n");
8262                                 return CMD_HELP;
8263                         }
8264                         archive_id = atoi(optarg);
8265                         break;
8266                 case 'm':
8267                         if (some_file == NULL) {
8268                                 mntpath = optarg;
8269                                 some_file = strdup(optarg);
8270                         }
8271                         break;
8272                 case '?':
8273                         return CMD_HELP;
8274                 default:
8275                         fprintf(stderr, "error: %s: option '%s' unrecognized\n",
8276                                 argv[0], argv[optind - 1]);
8277                         return CMD_HELP;
8278                 }
8279         }
8280
8281         /* All remaining args are files, so we have at least nbfile */
8282         nbfile = argc - optind;
8283
8284         if ((nbfile == 0) && (filelist == NULL))
8285                 return CMD_HELP;
8286
8287         if (opaque != NULL)
8288                 opaque_len = strlen(opaque);
8289
8290         /* Alloc the request structure with enough place to store all files
8291          * from command line. */
8292         hur = llapi_hsm_user_request_alloc(nbfile, opaque_len);
8293         if (hur == NULL) {
8294                 fprintf(stderr, "Cannot create the request: %s\n",
8295                         strerror(errno));
8296                 return errno;
8297         }
8298         nbfile_alloc = nbfile;
8299
8300         hur->hur_request.hr_action = action;
8301         hur->hur_request.hr_archive_id = archive_id;
8302         hur->hur_request.hr_flags = 0;
8303
8304         /* All remaining args are files, add them */
8305         if (nbfile != 0 && some_file == NULL)
8306                 some_file = strdup(argv[optind]);
8307
8308         for (i = 0; i < nbfile; i++) {
8309                 rc = fill_hur_item(hur, i, mntpath, argv[optind + i],
8310                                    &last_dev);
8311                 if (rc)
8312                         goto out_free;
8313         }
8314
8315         /* from here stop using nb_file, use hur->hur_request.hr_itemcount */
8316
8317         /* If a filelist was specified, read the filelist from it. */
8318         if (filelist != NULL) {
8319                 fp = fopen(filelist, "r");
8320                 if (fp == NULL) {
8321                         fprintf(stderr, "Cannot read the file list %s: %s\n",
8322                                 filelist, strerror(errno));
8323                         rc = -errno;
8324                         goto out_free;
8325                 }
8326
8327                 while ((rc = getline(&line, &len, fp)) != -1) {
8328                         /* If allocated buffer was too small, get something
8329                          * larger */
8330                         if (nbfile_alloc <= hur->hur_request.hr_itemcount) {
8331                                 ssize_t size;
8332
8333                                 nbfile_alloc = nbfile_alloc * 2 + 1;
8334                                 oldhur = hur;
8335                                 hur = llapi_hsm_user_request_alloc(nbfile_alloc,
8336                                                                    opaque_len);
8337                                 if (hur == NULL) {
8338                                         fprintf(stderr, "hsm: cannot allocate "
8339                                                 "the request: %s\n",
8340                                                 strerror(errno));
8341                                         hur = oldhur;
8342                                         rc = -errno;
8343                                         fclose(fp);
8344                                         goto out_free;
8345                                 }
8346                                 size = hur_len(oldhur);
8347                                 if (size < 0) {
8348                                         fprintf(stderr, "hsm: cannot allocate "
8349                                                 "%u files + %u bytes data\n",
8350                                             oldhur->hur_request.hr_itemcount,
8351                                             oldhur->hur_request.hr_data_len);
8352                                         free(hur);
8353                                         hur = oldhur;
8354                                         rc = -E2BIG;
8355                                         fclose(fp);
8356                                         goto out_free;
8357                                 }
8358                                 memcpy(hur, oldhur, size);
8359                                 free(oldhur);
8360                         }
8361
8362                         /* Chop CR */
8363                         if (line[strlen(line) - 1] == '\n')
8364                                 line[strlen(line) - 1] = '\0';
8365
8366                         rc = fill_hur_item(hur, hur->hur_request.hr_itemcount,
8367                                            mntpath, line, &last_dev);
8368                         if (rc) {
8369                                 fclose(fp);
8370                                 goto out_free;
8371                         }
8372
8373                         if (some_file == NULL) {
8374                                 some_file = line;
8375                                 line = NULL;
8376                         }
8377                 }
8378
8379                 rc = fclose(fp);
8380                 free(line);
8381         }
8382
8383         /* If a --data was used, add it to the request */
8384         hur->hur_request.hr_data_len = opaque_len;
8385         if (opaque != NULL)
8386                 memcpy(hur_data(hur), opaque, opaque_len);
8387
8388         /* Send the HSM request */
8389         if (realpath(some_file, fullpath) == NULL) {
8390                 fprintf(stderr, "Could not find path '%s': %s\n",
8391                         some_file, strerror(errno));
8392         }
8393         rc = llapi_hsm_request(fullpath, hur);
8394         if (rc) {
8395                 fprintf(stderr, "Cannot send HSM request (use of %s): %s\n",
8396                         some_file, strerror(-rc));
8397                 goto out_free;
8398         }
8399
8400 out_free:
8401         free(some_file);
8402         free(hur);
8403         return rc;
8404 }
8405
8406 static int lfs_hsm_archive(int argc, char **argv)
8407 {
8408         return lfs_hsm_request(argc, argv, HUA_ARCHIVE);
8409 }
8410
8411 static int lfs_hsm_restore(int argc, char **argv)
8412 {
8413         return lfs_hsm_request(argc, argv, HUA_RESTORE);
8414 }
8415
8416 static int lfs_hsm_release(int argc, char **argv)
8417 {
8418         return lfs_hsm_request(argc, argv, HUA_RELEASE);
8419 }
8420
8421 static int lfs_hsm_remove(int argc, char **argv)
8422 {
8423         return lfs_hsm_request(argc, argv, HUA_REMOVE);
8424 }
8425
8426 static int lfs_hsm_cancel(int argc, char **argv)
8427 {
8428         return lfs_hsm_request(argc, argv, HUA_CANCEL);
8429 }
8430
8431 static int lfs_swap_layouts(int argc, char **argv)
8432 {
8433         if (argc != 3)
8434                 return CMD_HELP;
8435
8436         return llapi_swap_layouts(argv[1], argv[2], 0, 0,
8437                                   SWAP_LAYOUTS_KEEP_MTIME |
8438                                   SWAP_LAYOUTS_KEEP_ATIME);
8439 }
8440
8441 static const char *const ladvise_names[] = LU_LADVISE_NAMES;
8442
8443 static const char *const lock_mode_names[] = LOCK_MODE_NAMES;
8444
8445 int lfs_get_mode(const char *string)
8446 {
8447         enum lock_mode_user mode;
8448
8449         for (mode = 0; mode < ARRAY_SIZE(lock_mode_names); mode++) {
8450                 if (lock_mode_names[mode] == NULL)
8451                         continue;
8452                 if (strcmp(string, lock_mode_names[mode]) == 0)
8453                         return mode;
8454         }
8455
8456         return -EINVAL;
8457 }
8458
8459 static enum lu_ladvise_type lfs_get_ladvice(const char *string)
8460 {
8461         enum lu_ladvise_type advice;
8462
8463         for (advice = 0;
8464              advice < ARRAY_SIZE(ladvise_names); advice++) {
8465                 if (ladvise_names[advice] == NULL)
8466                         continue;
8467                 if (strcmp(string, ladvise_names[advice]) == 0)
8468                         return advice;
8469         }
8470
8471         return LU_LADVISE_INVALID;
8472 }
8473
8474 static int lfs_ladvise(int argc, char **argv)
8475 {
8476         struct option long_opts[] = {
8477         { .val = 'a',   .name = "advice",       .has_arg = required_argument },
8478         { .val = 'b',   .name = "background",   .has_arg = no_argument },
8479         { .val = 'e',   .name = "end",          .has_arg = required_argument },
8480         { .val = 'l',   .name = "length",       .has_arg = required_argument },
8481         { .val = 'm',   .name = "mode",         .has_arg = required_argument },
8482         { .val = 's',   .name = "start",        .has_arg = required_argument },
8483         { .val = 'u',   .name = "unset",        .has_arg = no_argument },
8484         { .name = NULL } };
8485         char                     short_opts[] = "a:be:l:m:s:u";
8486         int                      c;
8487         int                      rc = 0;
8488         const char              *path;
8489         int                      fd;
8490         struct llapi_lu_ladvise  advice;
8491         enum lu_ladvise_type     advice_type = LU_LADVISE_INVALID;
8492         unsigned long long       start = 0;
8493         unsigned long long       end = LUSTRE_EOF;
8494         unsigned long long       length = 0;
8495         unsigned long long       size_units;
8496         unsigned long long       flags = 0;
8497         int                      mode = 0;
8498
8499         optind = 0;
8500         while ((c = getopt_long(argc, argv, short_opts,
8501                                 long_opts, NULL)) != -1) {
8502                 switch (c) {
8503                 case 'a':
8504                         advice_type = lfs_get_ladvice(optarg);
8505                         if (advice_type == LU_LADVISE_INVALID) {
8506                                 fprintf(stderr, "%s: invalid advice type "
8507                                         "'%s'\n", argv[0], optarg);
8508                                 fprintf(stderr, "Valid types:");
8509
8510                                 for (advice_type = 0;
8511                                      advice_type < ARRAY_SIZE(ladvise_names);
8512                                      advice_type++) {
8513                                         if (ladvise_names[advice_type] == NULL)
8514                                                 continue;
8515                                         fprintf(stderr, " %s",
8516                                                 ladvise_names[advice_type]);
8517                                 }
8518                                 fprintf(stderr, "\n");
8519
8520                                 return CMD_HELP;
8521                         }
8522                         break;
8523                 case 'b':
8524                         flags |= LF_ASYNC;
8525                         break;
8526                 case 'u':
8527                         flags |= LF_UNSET;
8528                         break;
8529                 case 'e':
8530                         size_units = 1;
8531                         rc = llapi_parse_size(optarg, &end,
8532                                               &size_units, 0);
8533                         if (rc) {
8534                                 fprintf(stderr, "%s: bad end offset '%s'\n",
8535                                         argv[0], optarg);
8536                                 return CMD_HELP;
8537                         }
8538                         break;
8539                 case 's':
8540                         size_units = 1;
8541                         rc = llapi_parse_size(optarg, &start,
8542                                               &size_units, 0);
8543                         if (rc) {
8544                                 fprintf(stderr, "%s: bad start offset "
8545                                         "'%s'\n", argv[0], optarg);
8546                                 return CMD_HELP;
8547                         }
8548                         break;
8549                 case 'l':
8550                         size_units = 1;
8551                         rc = llapi_parse_size(optarg, &length,
8552                                               &size_units, 0);
8553                         if (rc) {
8554                                 fprintf(stderr, "%s: bad length '%s'\n",
8555                                         argv[0], optarg);
8556                                 return CMD_HELP;
8557                         }
8558                         break;
8559                 case 'm':
8560                         mode = lfs_get_mode(optarg);
8561                         if (mode < 0) {
8562                                 fprintf(stderr, "%s: bad mode '%s', valid "
8563                                                  "modes are READ or WRITE\n",
8564                                         argv[0], optarg);
8565                                 return CMD_HELP;
8566                         }
8567                         break;
8568                 case '?':
8569                         return CMD_HELP;
8570                 default:
8571                         fprintf(stderr, "%s: option '%s' unrecognized\n",
8572                                 argv[0], argv[optind - 1]);
8573                         return CMD_HELP;
8574                 }
8575         }
8576
8577         if (advice_type == LU_LADVISE_INVALID) {
8578                 fprintf(stderr, "%s: please give an advice type\n", argv[0]);
8579                 fprintf(stderr, "Valid types:");
8580                 for (advice_type = 0; advice_type < ARRAY_SIZE(ladvise_names);
8581                      advice_type++) {
8582                         if (ladvise_names[advice_type] == NULL)
8583                                 continue;
8584                         fprintf(stderr, " %s", ladvise_names[advice_type]);
8585                 }
8586                 fprintf(stderr, "\n");
8587                 return CMD_HELP;
8588         }
8589
8590         if (advice_type == LU_LADVISE_LOCKNOEXPAND) {
8591                 fprintf(stderr, "%s: Lock no expand advice is a per file "
8592                                  "descriptor advice, so when called from lfs, "
8593                                  "it does nothing.\n", argv[0]);
8594                 return CMD_HELP;
8595         }
8596
8597         if (argc <= optind) {
8598                 fprintf(stderr, "%s: please give one or more file names\n",
8599                         argv[0]);
8600                 return CMD_HELP;
8601         }
8602
8603         if (end != LUSTRE_EOF && length != 0 && end != start + length) {
8604                 fprintf(stderr, "%s: conflicting arguments of -l and -e\n",
8605                         argv[0]);
8606                 return CMD_HELP;
8607         }
8608
8609         if (end == LUSTRE_EOF && length != 0)
8610                 end = start + length;
8611
8612         if (end <= start) {
8613                 fprintf(stderr, "%s: range [%llu, %llu] is invalid\n",
8614                         argv[0], start, end);
8615                 return CMD_HELP;
8616         }
8617
8618         if (advice_type != LU_LADVISE_LOCKAHEAD && mode != 0) {
8619                 fprintf(stderr, "%s: mode is only valid with lockahead\n",
8620                         argv[0]);
8621                 return CMD_HELP;
8622         }
8623
8624         if (advice_type == LU_LADVISE_LOCKAHEAD && mode == 0) {
8625                 fprintf(stderr, "%s: mode is required with lockahead\n",
8626                         argv[0]);
8627                 return CMD_HELP;
8628         }
8629
8630         while (optind < argc) {
8631                 int rc2;
8632
8633                 path = argv[optind++];
8634
8635                 fd = open(path, O_RDONLY);
8636                 if (fd < 0) {
8637                         fprintf(stderr, "%s: cannot open file '%s': %s\n",
8638                                 argv[0], path, strerror(errno));
8639                         rc2 = -errno;
8640                         goto next;
8641                 }
8642
8643                 advice.lla_start = start;
8644                 advice.lla_end = end;
8645                 advice.lla_advice = advice_type;
8646                 advice.lla_value1 = 0;
8647                 advice.lla_value2 = 0;
8648                 advice.lla_value3 = 0;
8649                 advice.lla_value4 = 0;
8650                 if (advice_type == LU_LADVISE_LOCKAHEAD) {
8651                         advice.lla_lockahead_mode = mode;
8652                         advice.lla_peradvice_flags = flags;
8653                 }
8654
8655                 rc2 = llapi_ladvise(fd, flags, 1, &advice);
8656                 close(fd);
8657                 if (rc2 < 0) {
8658                         fprintf(stderr, "%s: cannot give advice '%s' to file "
8659                                 "'%s': %s\n", argv[0],
8660                                 ladvise_names[advice_type],
8661                                 path, strerror(errno));
8662
8663                         goto next;
8664                 }
8665
8666 next:
8667                 if (rc == 0 && rc2 < 0)
8668                         rc = rc2;
8669         }
8670         return rc;
8671 }
8672
8673 static const char *const heat_names[] = LU_HEAT_NAMES;
8674
8675 static int lfs_heat_get(int argc, char **argv)
8676 {
8677         struct lu_heat *heat;
8678         int rc = 0, rc2;
8679         char *path;
8680         int fd;
8681         int i;
8682
8683         if (argc <= 1)
8684                 return CMD_HELP;
8685
8686         heat = calloc(sizeof(*heat) + sizeof(__u64) * OBD_HEAT_COUNT, 1);
8687         if (!heat) {
8688                 fprintf(stderr, "%s: memory allocation failed\n", argv[0]);
8689                 return -ENOMEM;
8690         }
8691
8692         optind = 1;
8693         while (optind < argc) {
8694                 path = argv[optind++];
8695
8696                 fd = open(path, O_RDONLY);
8697                 if (fd < 0) {
8698                         fprintf(stderr, "%s: cannot open file '%s': %s\n",
8699                                 argv[0], path, strerror(errno));
8700                         rc2 = -errno;
8701                         goto next;
8702                 }
8703
8704                 heat->lh_count = OBD_HEAT_COUNT;
8705                 rc2 = llapi_heat_get(fd, heat);
8706                 close(fd);
8707                 if (rc2 < 0) {
8708                         fprintf(stderr, "%s: cannot get heat of file '%s'"
8709                                 ": %s\n", argv[0], path, strerror(errno));
8710                         goto next;
8711                 }
8712
8713                 printf("flags: %x\n", heat->lh_flags);
8714                 for (i = 0; i < heat->lh_count; i++)
8715                         printf("%s: %llu\n", heat_names[i],
8716                                (unsigned long long)heat->lh_heat[i]);
8717 next:
8718                 if (rc == 0 && rc2 < 0)
8719                         rc = rc2;
8720         }
8721
8722         free(heat);
8723         return rc;
8724 }
8725
8726 static int lfs_heat_set(int argc, char **argv)
8727 {
8728         struct option long_opts[] = {
8729         { .val = 'c',   .name = "clear",        .has_arg = no_argument },
8730         { .val = 'o',   .name = "off",          .has_arg = no_argument },
8731         { .val = 'O',   .name = "on",           .has_arg = no_argument },
8732         { .name = NULL } };
8733         enum lu_heat_flag flags = 0;
8734         int rc = 0, rc2;
8735         char *path;
8736         int fd;
8737         int c;
8738
8739         if (argc <= 1)
8740                 return CMD_HELP;
8741
8742         optind = 0;
8743         while ((c = getopt_long(argc, argv, "coO", long_opts, NULL)) != -1) {
8744                 switch (c) {
8745                 case 'c':
8746                         flags |= LU_HEAT_FLAG_CLEAR;
8747                         break;
8748                 case 'o':
8749                         flags |= LU_HEAT_FLAG_CLEAR;
8750                         flags |= LU_HEAT_FLAG_OFF;
8751                         break;
8752                 case 'O':
8753                         flags &= ~LU_HEAT_FLAG_OFF;
8754                         break;
8755                 case '?':
8756                         return CMD_HELP;
8757                 default:
8758                         fprintf(stderr, "%s: option '%s' unrecognized\n",
8759                                 argv[0], argv[optind - 1]);
8760                         return CMD_HELP;
8761                 }
8762         }
8763
8764         if (argc <= optind) {
8765                 fprintf(stderr, "%s: please give one or more file names\n",
8766                         argv[0]);
8767                 return CMD_HELP;
8768         }
8769
8770         while (optind < argc) {
8771                 path = argv[optind++];
8772
8773                 fd = open(path, O_RDONLY);
8774                 if (fd < 0) {
8775                         fprintf(stderr, "%s: cannot open file '%s': %s\n",
8776                                 argv[0], path, strerror(errno));
8777                         rc2 = -errno;
8778                         goto next;
8779                 }
8780
8781                 rc2 = llapi_heat_set(fd, flags);
8782                 close(fd);
8783                 if (rc2 < 0) {
8784                         fprintf(stderr, "%s: cannot setflags heat of file '%s'"
8785                                 ": %s\n", argv[0], path, strerror(errno));
8786                         goto next;
8787                 }
8788 next:
8789                 if (rc == 0 && rc2 < 0)
8790                         rc = rc2;
8791         }
8792         return rc;
8793 }
8794
8795 /** The input string contains a comma delimited list of component ids and
8796  * ranges, for example "1,2-4,7".
8797  */
8798 static int parse_mirror_ids(__u16 *ids, int size, char *arg)
8799 {
8800         bool end_of_loop = false;
8801         char *ptr = NULL;
8802         int nr = 0;
8803         int rc;
8804
8805         if (arg == NULL)
8806                 return -EINVAL;
8807
8808         while (!end_of_loop) {
8809                 int start_index;
8810                 int end_index;
8811                 int i;
8812                 char *endptr = NULL;
8813
8814                 rc = -EINVAL;
8815                 ptr = strchrnul(arg, ',');
8816                 end_of_loop = *ptr == '\0';
8817                 *ptr = '\0';
8818
8819                 start_index = strtol(arg, &endptr, 0);
8820                 if (endptr == arg) /* no data at all */
8821                         break;
8822                 if (*endptr != '-' && *endptr != '\0') /* has invalid data */
8823                         break;
8824                 if (start_index < 0)
8825                         break;
8826
8827                 end_index = start_index;
8828                 if (*endptr == '-') {
8829                         end_index = strtol(endptr + 1, &endptr, 0);
8830                         if (*endptr != '\0')
8831                                 break;
8832                         if (end_index < start_index)
8833                                 break;
8834                 }
8835
8836                 for (i = start_index; i <= end_index && size > 0; i++) {
8837                         int j;
8838
8839                         /* remove duplicate */
8840                         for (j = 0; j < nr; j++) {
8841                                 if (ids[j] == i)
8842                                         break;
8843                         }
8844                         if (j == nr) { /* no duplicate */
8845                                 ids[nr++] = i;
8846                                 --size;
8847                         }
8848                 }
8849
8850                 if (size == 0 && i < end_index)
8851                         break;
8852
8853                 *ptr = ',';
8854                 arg = ++ptr;
8855                 rc = 0;
8856         }
8857         if (!end_of_loop && ptr != NULL)
8858                 *ptr = ',';
8859
8860         return rc < 0 ? rc : nr;
8861 }
8862
8863 /**
8864  * struct verify_mirror_id - Mirror id to be verified.
8865  * @mirror_id:   A specified mirror id.
8866  * @is_valid_id: @mirror_id is valid or not in the mirrored file.
8867  */
8868 struct verify_mirror_id {
8869         __u16 mirror_id;
8870         bool is_valid_id;
8871 };
8872
8873 /**
8874  * compare_mirror_ids() - Compare mirror ids.
8875  * @layout: Mirror component list.
8876  * @cbdata: Callback data in verify_mirror_id structure.
8877  *
8878  * This is a callback function called by llapi_layout_comp_iterate()
8879  * to compare the specified mirror id with the one in the current
8880  * component of @layout. If they are the same, then the specified
8881  * mirror id is valid.
8882  *
8883  * Return: a negative error code on failure or
8884  *         LLAPI_LAYOUT_ITER_CONT: Proceed iteration
8885  *         LLAPI_LAYOUT_ITER_STOP: Stop iteration
8886  */
8887 static inline
8888 int compare_mirror_ids(struct llapi_layout *layout, void *cbdata)
8889 {
8890         struct verify_mirror_id *mirror_id_cbdata =
8891                                  (struct verify_mirror_id *)cbdata;
8892         uint32_t mirror_id;
8893         int rc = 0;
8894
8895         rc = llapi_layout_mirror_id_get(layout, &mirror_id);
8896         if (rc < 0) {
8897                 rc = -errno;
8898                 fprintf(stderr,
8899                         "%s: llapi_layout_mirror_id_get failed: %s.\n",
8900                         progname, strerror(errno));
8901                 return rc;
8902         }
8903
8904         if (mirror_id_cbdata->mirror_id == mirror_id) {
8905                 mirror_id_cbdata->is_valid_id = true;
8906                 return LLAPI_LAYOUT_ITER_STOP;
8907         }
8908
8909         return LLAPI_LAYOUT_ITER_CONT;
8910 }
8911
8912 /**
8913  * verify_mirror_ids() - Verify specified mirror ids.
8914  * @fname:      Mirrored file name.
8915  * @mirror_ids: Specified mirror ids to be verified.
8916  * @ids_nr:     Number of specified mirror ids.
8917  *
8918  * This function verifies that specified @mirror_ids are valid
8919  * in the mirrored file @fname.
8920  *
8921  * Return: 0 on success or a negative error code on failure.
8922  */
8923 static inline
8924 int verify_mirror_ids(const char *fname, __u16 *mirror_ids, int ids_nr)
8925 {
8926         struct llapi_layout *layout = NULL;
8927         struct verify_mirror_id mirror_id_cbdata = { 0 };
8928         struct stat stbuf;
8929         uint32_t flr_state;
8930         int i;
8931         int fd;
8932         int rc = 0;
8933         int rc2 = 0;
8934
8935         if (ids_nr <= 0)
8936                 return -EINVAL;
8937
8938         if (stat(fname, &stbuf) < 0) {
8939                 fprintf(stderr, "%s: cannot stat file '%s': %s.\n",
8940                         progname, fname, strerror(errno));
8941                 rc = -errno;
8942                 goto error;
8943         }
8944
8945         if (!S_ISREG(stbuf.st_mode)) {
8946                 fprintf(stderr, "%s: '%s' is not a regular file.\n",
8947                         progname, fname);
8948                 rc = -EINVAL;
8949                 goto error;
8950         }
8951
8952         fd = open(fname, O_DIRECT | O_RDONLY);
8953         if (fd < 0) {
8954                 fprintf(stderr, "%s: cannot open '%s': %s.\n",
8955                         progname, fname, strerror(errno));
8956                 rc = -errno;
8957                 goto error;
8958         }
8959
8960         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
8961         if (rc < 0) {
8962                 fprintf(stderr, "%s: '%s' llapi_lease_acquire failed: %s.\n",
8963                         progname, fname, strerror(errno));
8964                 goto close_fd;
8965         }
8966
8967         layout = llapi_layout_get_by_fd(fd, 0);
8968         if (layout == NULL) {
8969                 fprintf(stderr, "%s: '%s' llapi_layout_get_by_fd failed: %s.\n",
8970                         progname, fname, strerror(errno));
8971                 rc = -errno;
8972                 llapi_lease_release(fd);
8973                 goto close_fd;
8974         }
8975
8976         rc = llapi_layout_flags_get(layout, &flr_state);
8977         if (rc < 0) {
8978                 fprintf(stderr, "%s: '%s' llapi_layout_flags_get failed: %s.\n",
8979                         progname, fname, strerror(errno));
8980                 rc = -errno;
8981                 goto free_layout;
8982         }
8983
8984         flr_state &= LCM_FL_FLR_MASK;
8985         switch (flr_state) {
8986         case LCM_FL_NONE:
8987                 rc = -EINVAL;
8988                 fprintf(stderr, "%s: '%s' file state error: %s.\n",
8989                         progname, fname, llapi_layout_flags_string(flr_state));
8990                 goto free_layout;
8991         default:
8992                 break;
8993         }
8994
8995         rc2 = 0;
8996         for (i = 0; i < ids_nr; i++) {
8997                 mirror_id_cbdata.mirror_id = mirror_ids[i];
8998                 mirror_id_cbdata.is_valid_id = false;
8999
9000                 rc = llapi_layout_comp_iterate(layout, compare_mirror_ids,
9001                                                &mirror_id_cbdata);
9002                 if (rc < 0) {
9003                         rc = -errno;
9004                         fprintf(stderr,
9005                                 "%s: '%s' failed to verify mirror id: %u.\n",
9006                                 progname, fname, mirror_ids[i]);
9007                         goto free_layout;
9008                 }
9009
9010                 if (!mirror_id_cbdata.is_valid_id) {
9011                         rc2 = -EINVAL;
9012                         fprintf(stderr,
9013                                 "%s: '%s' invalid specified mirror id: %u.\n",
9014                                 progname, fname, mirror_ids[i]);
9015                 }
9016         }
9017         rc = rc2;
9018
9019 free_layout:
9020         llapi_layout_free(layout);
9021         llapi_lease_release(fd);
9022 close_fd:
9023         close(fd);
9024 error:
9025         return rc;
9026 }
9027
9028 static inline
9029 int lfs_mirror_resync_file(const char *fname, struct ll_ioc_lease *ioc,
9030                            __u16 *mirror_ids, int ids_nr)
9031 {
9032         struct llapi_resync_comp comp_array[1024] = { { 0 } };
9033         struct llapi_layout *layout;
9034         struct stat stbuf;
9035         uint32_t flr_state;
9036         uint64_t start;
9037         uint64_t end;
9038         int comp_size = 0;
9039         int idx;
9040         int fd;
9041         int rc;
9042         int rc2;
9043
9044         if (stat(fname, &stbuf) < 0) {
9045                 fprintf(stderr, "%s: cannot stat file '%s': %s.\n",
9046                         progname, fname, strerror(errno));
9047                 rc = -errno;
9048                 goto error;
9049         }
9050         if (!S_ISREG(stbuf.st_mode)) {
9051                 fprintf(stderr, "%s: '%s' is not a regular file.\n",
9052                         progname, fname);
9053                 rc = -EINVAL;
9054                 goto error;
9055         }
9056
9057         fd = open(fname, O_DIRECT | O_RDWR);
9058         if (fd < 0) {
9059                 fprintf(stderr, "%s: cannot open '%s': %s.\n",
9060                         progname, fname, strerror(errno));
9061                 rc = -errno;
9062                 goto error;
9063         }
9064
9065         layout = llapi_layout_get_by_fd(fd, 0);
9066         if (layout == NULL) {
9067                 fprintf(stderr, "%s: '%s' llapi_layout_get_by_fd failed: %s.\n",
9068                         progname, fname, strerror(errno));
9069                 rc = -errno;
9070                 goto close_fd;
9071         }
9072
9073         rc = llapi_layout_flags_get(layout, &flr_state);
9074         if (rc) {
9075                 fprintf(stderr, "%s: '%s' llapi_layout_flags_get failed: %s.\n",
9076                         progname, fname, strerror(errno));
9077                 rc = -errno;
9078                 goto free_layout;
9079         }
9080
9081         flr_state &= LCM_FL_FLR_MASK;
9082         if (flr_state == LCM_FL_NONE) {
9083                 rc = -EINVAL;
9084                 fprintf(stderr, "%s: '%s' is not a FLR file.\n",
9085                         progname, fname);
9086                 goto free_layout;
9087         }
9088
9089         /* get stale component info */
9090         comp_size = llapi_mirror_find_stale(layout, comp_array,
9091                                             ARRAY_SIZE(comp_array),
9092                                             mirror_ids, ids_nr);
9093         if (comp_size <= 0) {
9094                 rc = comp_size;
9095                 goto free_layout;
9096         }
9097
9098         ioc->lil_mode = LL_LEASE_WRLCK;
9099         ioc->lil_flags = LL_LEASE_RESYNC;
9100         rc = llapi_lease_set(fd, ioc);
9101         if (rc < 0) {
9102                 if (rc == -EALREADY)
9103                         rc = 0;
9104                 else
9105                         fprintf(stderr,
9106                             "%s: '%s' llapi_lease_get_ext resync failed: %s.\n",
9107                                 progname, fname, strerror(-rc));
9108                 goto free_layout;
9109         }
9110
9111         /* get the read range [start, end) */
9112         start = comp_array[0].lrc_start;
9113         end = comp_array[0].lrc_end;
9114         for (idx = 1; idx < comp_size; idx++) {
9115                 if (comp_array[idx].lrc_start < start)
9116                         start = comp_array[idx].lrc_start;
9117                 if (end < comp_array[idx].lrc_end)
9118                         end = comp_array[idx].lrc_end;
9119         }
9120
9121         rc = llapi_lease_check(fd);
9122         if (rc != LL_LEASE_WRLCK) {
9123                 fprintf(stderr, "%s: '%s' lost lease lock.\n",
9124                         progname, fname);
9125                 goto free_layout;
9126         }
9127
9128         rc = llapi_mirror_resync_many(fd, layout, comp_array, comp_size,
9129                                       start, end);
9130         if (rc < 0)
9131                 fprintf(stderr, "%s: '%s' llapi_mirror_resync_many: %s.\n",
9132                         progname, fname, strerror(-rc));
9133
9134         /* need to do the lease unlock even resync fails */
9135         ioc->lil_mode = LL_LEASE_UNLCK;
9136         ioc->lil_flags = LL_LEASE_RESYNC_DONE;
9137         ioc->lil_count = 0;
9138         for (idx = 0; idx < comp_size; idx++) {
9139                 if (comp_array[idx].lrc_synced) {
9140                         ioc->lil_ids[ioc->lil_count] = comp_array[idx].lrc_id;
9141                         ioc->lil_count++;
9142                 }
9143         }
9144
9145         rc2 = llapi_lease_set(fd, ioc);
9146         /**
9147          * llapi_lease_set returns lease mode when it request to unlock
9148          * the lease lock.
9149          */
9150         if (rc2 <= 0) {
9151                 /* rc2 == 0 means lost lease lock */
9152                 if (rc2 == 0 && rc == 0)
9153                         rc = -EBUSY;
9154                 fprintf(stderr, "%s: resync file '%s' failed: %s.\n",
9155                         progname, fname,
9156                         rc2 == 0 ? "lost lease lock" : strerror(-rc2));
9157         }
9158
9159 free_layout:
9160         llapi_layout_free(layout);
9161 close_fd:
9162         close(fd);
9163 error:
9164         return rc;
9165 }
9166
9167 static inline int lfs_mirror_resync(int argc, char **argv)
9168 {
9169         struct ll_ioc_lease *ioc = NULL;
9170         __u16 mirror_ids[128] = { 0 };
9171         int ids_nr = 0;
9172         int c;
9173         int rc = 0;
9174
9175         struct option long_opts[] = {
9176         { .val = 'o',   .name = "only",         .has_arg = required_argument },
9177         { .name = NULL } };
9178
9179         while ((c = getopt_long(argc, argv, "o:", long_opts, NULL)) >= 0) {
9180                 switch (c) {
9181                 case 'o':
9182                         rc = parse_mirror_ids(mirror_ids,
9183                                         sizeof(mirror_ids) / sizeof(__u16),
9184                                         optarg);
9185                         if (rc < 0) {
9186                                 fprintf(stderr,
9187                                         "%s: bad mirror ids '%s'.\n",
9188                                         argv[0], optarg);
9189                                 goto error;
9190                         }
9191                         ids_nr = rc;
9192                         break;
9193                 default:
9194                         fprintf(stderr, "%s: options '%s' unrecognized.\n",
9195                                 argv[0], argv[optind - 1]);
9196                         rc = -EINVAL;
9197                         goto error;
9198                 }
9199         }
9200
9201         if (argc == optind) {
9202                 fprintf(stderr, "%s: no file name given.\n", argv[0]);
9203                 rc = CMD_HELP;
9204                 goto error;
9205         }
9206
9207         if (ids_nr > 0 && argc > optind + 1) {
9208                 fprintf(stderr,
9209                     "%s: option '--only' cannot be used upon multiple files.\n",
9210                         argv[0]);
9211                 rc = CMD_HELP;
9212                 goto error;
9213
9214         }
9215
9216         if (ids_nr > 0) {
9217                 rc = verify_mirror_ids(argv[optind], mirror_ids, ids_nr);
9218                 if (rc < 0)
9219                         goto error;
9220         }
9221
9222         /* set the lease on the file */
9223         ioc = calloc(sizeof(*ioc) + sizeof(__u32) * 4096, 1);
9224         if (ioc == NULL) {
9225                 fprintf(stderr, "%s: cannot alloc id array for ioc: %s.\n",
9226                         argv[0], strerror(errno));
9227                 rc = -errno;
9228                 goto error;
9229         }
9230
9231         for (; optind < argc; optind++) {
9232                 rc = lfs_mirror_resync_file(argv[optind], ioc,
9233                                             mirror_ids, ids_nr);
9234                 /* ignore previous file's error, continue with next file */
9235
9236                 /* reset ioc */
9237                 memset(ioc, 0, sizeof(*ioc) + sizeof(__u32) * 4096);
9238         }
9239
9240         free(ioc);
9241 error:
9242         return rc;
9243 }
9244
9245 static inline int verify_mirror_id_by_fd(int fd, __u16 mirror_id)
9246 {
9247         struct llapi_layout *layout;
9248         int rc;
9249
9250         layout = llapi_layout_get_by_fd(fd, 0);
9251         if (layout == NULL) {
9252                 fprintf(stderr, "could not get layout.\n");
9253                 return  -EINVAL;
9254         }
9255
9256         rc = llapi_layout_comp_iterate(layout, find_mirror_id, &mirror_id);
9257         if (rc < 0) {
9258                 fprintf(stderr, "failed to iterate layout\n");
9259                 llapi_layout_free(layout);
9260
9261                 return rc;
9262         } else if (rc == LLAPI_LAYOUT_ITER_CONT) {
9263                 fprintf(stderr, "does not find mirror with ID %u\n", mirror_id);
9264                 llapi_layout_free(layout);
9265
9266                 return -EINVAL;
9267         }
9268         llapi_layout_free(layout);
9269
9270         return 0;
9271 }
9272
9273 /**
9274  * Check whether two files are the same file
9275  * \retval      0  same file
9276  * \retval      1  not the same file
9277  * \retval      <0 error code
9278  */
9279 static inline int check_same_file(const char *f1, const char *f2)
9280 {
9281         struct stat stbuf1;
9282         struct stat stbuf2;
9283
9284         if (stat(f1, &stbuf1) < 0) {
9285                 fprintf(stderr, "%s: cannot stat file '%s': %s\n",
9286                         progname, f1, strerror(errno));
9287                 return -errno;
9288         }
9289
9290         if (stat(f2, &stbuf2) < 0) {
9291                 fprintf(stderr, "%s: cannot stat file '%s': %s\n",
9292                         progname, f2, strerror(errno));
9293                 return -errno;
9294         }
9295
9296         if (stbuf1.st_rdev == stbuf2.st_rdev &&
9297             stbuf1.st_ino == stbuf2.st_ino)
9298                 return 0;
9299
9300         return 1;
9301 }
9302
9303 static inline int lfs_mirror_read(int argc, char **argv)
9304 {
9305         int rc = CMD_HELP;
9306         __u16 mirror_id = 0;
9307         const char *outfile = NULL;
9308         char *fname;
9309         int fd = 0;
9310         int outfd;
9311         int c;
9312         void *buf;
9313         const size_t buflen = 4 << 20;
9314         off_t pos;
9315         struct option long_opts[] = {
9316         { .val = 'N',   .name = "mirror-id",    .has_arg = required_argument },
9317         { .val = 'o',   .name = "outfile",      .has_arg = required_argument },
9318         { .name = NULL } };
9319
9320         while ((c = getopt_long(argc, argv, "N:o:", long_opts, NULL)) >= 0) {
9321                 char *end;
9322
9323                 switch (c) {
9324                 case 'N':
9325                         mirror_id = strtoul(optarg, &end, 0);
9326                         if (*end != '\0' || mirror_id == 0) {
9327                                 fprintf(stderr,
9328                                         "%s %s: invalid mirror ID '%s'\n",
9329                                         progname, argv[0], optarg);
9330                                 return rc;
9331                         }
9332                         break;
9333                 case 'o':
9334                         outfile = optarg;
9335                         break;
9336                 default:
9337                         fprintf(stderr, "%s: option '%s' unrecognized.\n",
9338                                 progname, argv[optind - 1]);
9339                         return -EINVAL;
9340                 }
9341         }
9342
9343         if (argc == optind) {
9344                 fprintf(stderr, "%s %s: no mirrored file provided\n",
9345                         progname, argv[0]);
9346                 return rc;
9347         } else if (argc > optind + 1) {
9348                 fprintf(stderr, "%s %s: too many files\n", progname, argv[0]);
9349                 return rc;
9350         }
9351
9352         if (mirror_id == 0) {
9353                 fprintf(stderr, "%s %s: no valid mirror ID is provided\n",
9354                         progname, argv[0]);
9355                 return rc;
9356         }
9357
9358         /* open mirror file */
9359         fname = argv[optind];
9360
9361         if (outfile) {
9362                 rc = check_same_file(fname, outfile);
9363                 if (rc == 0) {
9364                         fprintf(stderr,
9365                         "%s %s: output file cannot be the mirrored file\n",
9366                                 progname, argv[0]);
9367                         return -EINVAL;
9368                 }
9369                 if (rc < 0)
9370                         return rc;
9371         }
9372
9373         fd = open(fname, O_DIRECT | O_RDONLY);
9374         if (fd < 0) {
9375                 fprintf(stderr, "%s %s: cannot open '%s': %s\n",
9376                         progname, argv[0], fname, strerror(errno));
9377                 return rc;
9378         }
9379
9380         /* verify mirror id */
9381         rc = verify_mirror_id_by_fd(fd, mirror_id);
9382         if (rc) {
9383                 fprintf(stderr,
9384                         "%s %s: cannot find mirror with ID %u in '%s'\n",
9385                         progname, argv[0], mirror_id, fname);
9386                 goto close_fd;
9387         }
9388
9389         /* open output file */
9390         if (outfile) {
9391                 outfd = open(outfile, O_EXCL | O_WRONLY | O_CREAT, 0644);
9392                 if (outfd < 0) {
9393                         fprintf(stderr, "%s %s: cannot create file '%s': %s\n",
9394                                 progname, argv[0], outfile, strerror(errno));
9395                         rc = -errno;
9396                         goto close_fd;
9397                 }
9398         } else {
9399                 outfd = STDOUT_FILENO;
9400         }
9401
9402         /* allocate buffer */
9403         rc = posix_memalign(&buf, sysconf(_SC_PAGESIZE), buflen);
9404         if (rc) {
9405                 fprintf(stderr, "%s %s: posix_memalign returns %d\n",
9406                                 progname, argv[0], rc);
9407                 goto close_outfd;
9408         }
9409
9410         pos = 0;
9411         while (1) {
9412                 ssize_t bytes_read;
9413                 ssize_t written = 0;
9414
9415                 bytes_read = llapi_mirror_read(fd, mirror_id, buf, buflen, pos);
9416                 if (bytes_read < 0) {
9417                         rc = bytes_read;
9418                         fprintf(stderr,
9419                                 "%s %s: fail to read data from mirror %u: %s\n",
9420                                 progname, argv[0], mirror_id, strerror(-rc));
9421                         goto free_buf;
9422                 }
9423
9424                 /* EOF reached */
9425                 if (bytes_read == 0)
9426                         break;
9427
9428                 while (written < bytes_read) {
9429                         ssize_t written2;
9430
9431                         written2 = write(outfd, buf + written,
9432                                          bytes_read - written);
9433                         if (written2 < 0) {
9434                                 fprintf(stderr,
9435                                         "%s %s: fail to write %s: %s\n",
9436                                         progname, argv[0], outfile ? : "STDOUT",
9437                                         strerror(errno));
9438                                 rc = -errno;
9439                                 goto free_buf;
9440                         }
9441                         written += written2;
9442                 }
9443
9444                 if (written != bytes_read) {
9445                         fprintf(stderr,
9446                 "%s %s: written %ld bytes does not match with %ld read.\n",
9447                                 progname, argv[0], written, bytes_read);
9448                         rc = -EIO;
9449                         goto free_buf;
9450                 }
9451
9452                 pos += bytes_read;
9453         }
9454
9455         fsync(outfd);
9456         rc = 0;
9457
9458 free_buf:
9459         free(buf);
9460 close_outfd:
9461         if (outfile)
9462                 close(outfd);
9463 close_fd:
9464         close(fd);
9465
9466         return rc;
9467 }
9468
9469 static inline int lfs_mirror_write(int argc, char **argv)
9470 {
9471         int rc = CMD_HELP;
9472         __u16 mirror_id = 0;
9473         const char *inputfile = NULL;
9474         char *fname;
9475         int fd = 0;
9476         int inputfd;
9477         int c;
9478         void *buf;
9479         const size_t buflen = 4 << 20;
9480         off_t pos;
9481         size_t page_size = sysconf(_SC_PAGESIZE);
9482         struct ll_ioc_lease_id ioc;
9483
9484         struct option long_opts[] = {
9485         { .val = 'N',   .name = "mirror-id",    .has_arg = required_argument },
9486         { .val = 'i',   .name = "inputfile",    .has_arg = required_argument },
9487         { .name = NULL } };
9488
9489         while ((c = getopt_long(argc, argv, "N:i:", long_opts, NULL)) >= 0) {
9490                 char *end;
9491
9492                 switch (c) {
9493                 case 'N':
9494                         mirror_id = strtoul(optarg, &end, 0);
9495                         if (*end != '\0' || mirror_id == 0) {
9496                                 fprintf(stderr,
9497                                         "%s %s: invalid mirror ID '%s'\n",
9498                                         progname, argv[0], optarg);
9499                                 return rc;
9500                         }
9501                         break;
9502                 case 'i':
9503                         inputfile = optarg;
9504                         break;
9505                 default:
9506                         fprintf(stderr, "%s: option '%s' unrecognized\n",
9507                                 progname, argv[optind - 1]);
9508                         return -EINVAL;
9509                 }
9510         }
9511
9512         if (argc == optind) {
9513                 fprintf(stderr, "%s %s: no mirrored file provided\n",
9514                         progname, argv[0]);
9515                 return rc;
9516         } else if (argc > optind + 1) {
9517                 fprintf(stderr, "%s %s: too many files\n", progname, argv[0]);
9518                 return rc;
9519         }
9520
9521         if (mirror_id == 0) {
9522                 fprintf(stderr, "%s %s: no valid mirror ID is provided\n",
9523                         progname, argv[0]);
9524                 return rc;
9525         }
9526
9527         /* open mirror file */
9528         fname = argv[optind];
9529
9530         if (inputfile) {
9531                 rc = check_same_file(fname, inputfile);
9532                 if (rc == 0) {
9533                         fprintf(stderr,
9534                         "%s %s: input file cannot be the mirrored file\n",
9535                                 progname, argv[0]);
9536                         return -EINVAL;
9537                 }
9538                 if (rc < 0)
9539                         return rc;
9540         }
9541
9542         fd = open(fname, O_DIRECT | O_WRONLY);
9543         if (fd < 0) {
9544                 fprintf(stderr, "%s %s: cannot open '%s': %s\n",
9545                         progname, argv[0], fname, strerror(errno));
9546                 return rc;
9547         }
9548
9549         /* verify mirror id */
9550         rc = verify_mirror_id_by_fd(fd, mirror_id);
9551         if (rc) {
9552                 fprintf(stderr,
9553                         "%s %s: cannot find mirror with ID %u in '%s'\n",
9554                         progname, argv[0], mirror_id, fname);
9555                 goto close_fd;
9556         }
9557
9558         /* open input file */
9559         if (inputfile) {
9560                 inputfd = open(inputfile, O_RDONLY, 0644);
9561                 if (inputfd < 0) {
9562                         fprintf(stderr, "%s %s: cannot open file '%s': %s\n",
9563                                 progname, argv[0], inputfile, strerror(errno));
9564                         rc = -errno;
9565                         goto close_fd;
9566                 }
9567         } else {
9568                 inputfd = STDIN_FILENO;
9569         }
9570
9571         /* allocate buffer */
9572         rc = posix_memalign(&buf, page_size, buflen);
9573         if (rc) {
9574                 fprintf(stderr, "%s %s: posix_memalign returns %d\n",
9575                         progname, argv[0], rc);
9576                 goto close_inputfd;
9577         }
9578
9579         /* prepare target mirror components instantiation */
9580         ioc.lil_mode = LL_LEASE_WRLCK;
9581         ioc.lil_flags = LL_LEASE_RESYNC;
9582         ioc.lil_mirror_id = mirror_id;
9583         rc = llapi_lease_set(fd, (struct ll_ioc_lease *)&ioc);
9584         if (rc < 0) {
9585                 fprintf(stderr,
9586                         "%s %s: '%s' llapi_lease_get_ext failed: %s\n",
9587                         progname, argv[0], fname, strerror(errno));
9588                 goto free_buf;
9589         }
9590
9591         pos = 0;
9592         while (1) {
9593                 ssize_t bytes_read;
9594                 ssize_t written;
9595                 size_t to_write;
9596
9597                 rc = llapi_lease_check(fd);
9598                 if (rc != LL_LEASE_WRLCK) {
9599                         fprintf(stderr, "%s %s: '%s' lost lease lock\n",
9600                                 progname, argv[0], fname);
9601                         goto free_buf;
9602                 }
9603
9604                 bytes_read = read(inputfd, buf, buflen);
9605                 if (bytes_read < 0) {
9606                         rc = bytes_read;
9607                         fprintf(stderr,
9608                                 "%s %s: fail to read data from '%s': %s\n",
9609                                 progname, argv[0], inputfile ? : "STDIN",
9610                                 strerror(errno));
9611                         rc = -errno;
9612                         goto free_buf;
9613                 }
9614
9615                 /* EOF reached */
9616                 if (bytes_read == 0)
9617                         break;
9618
9619                 /* round up to page align to make direct IO happy. */
9620                 to_write = (bytes_read + page_size - 1) & ~(page_size - 1);
9621
9622                 written = llapi_mirror_write(fd, mirror_id, buf, to_write,
9623                                              pos);
9624                 if (written < 0) {
9625                         rc = written;
9626                         fprintf(stderr,
9627                               "%s %s: fail to write to mirror %u: %s\n",
9628                                 progname, argv[0], mirror_id,
9629                                 strerror(-rc));
9630                         goto free_buf;
9631                 }
9632
9633                 pos += bytes_read;
9634         }
9635
9636         if (pos & (page_size - 1)) {
9637                 rc = llapi_mirror_truncate(fd, mirror_id, pos);
9638                 if (rc < 0)
9639                         goto free_buf;
9640         }
9641
9642         ioc.lil_mode = LL_LEASE_UNLCK;
9643         ioc.lil_flags = LL_LEASE_RESYNC_DONE;
9644         ioc.lil_count = 0;
9645         rc = llapi_lease_set(fd, (struct ll_ioc_lease *)&ioc);
9646         if (rc <= 0) {
9647                 if (rc == 0)
9648                         rc = -EBUSY;
9649                 fprintf(stderr,
9650                         "%s %s: release lease lock of '%s' failed: %s\n",
9651                         progname, argv[0], fname, strerror(errno));
9652                 goto free_buf;
9653         }
9654
9655         rc = 0;
9656
9657 free_buf:
9658         free(buf);
9659 close_inputfd:
9660         if (inputfile)
9661                 close(inputfd);
9662 close_fd:
9663         close(fd);
9664
9665         return rc;
9666 }
9667
9668 static inline int get_other_mirror_ids(int fd, __u16 *ids, __u16 exclude_id)
9669 {
9670         struct llapi_layout *layout;
9671         struct collect_ids_data cid = { .cid_ids = ids,
9672                                         .cid_count = 0,
9673                                         .cid_exclude = exclude_id, };
9674         int rc;
9675
9676         layout = llapi_layout_get_by_fd(fd, 0);
9677         if (layout == NULL) {
9678                 fprintf(stderr, "could not get layout\n");
9679                 return -EINVAL;
9680         }
9681
9682         rc = llapi_layout_comp_iterate(layout, collect_mirror_id, &cid);
9683         if (rc < 0) {
9684                 fprintf(stderr, "failed to iterate layout\n");
9685                 llapi_layout_free(layout);
9686
9687                 return rc;
9688         }
9689         llapi_layout_free(layout);
9690
9691         return cid.cid_count;
9692 }
9693
9694 static inline int lfs_mirror_copy(int argc, char **argv)
9695 {
9696         int rc = CMD_HELP;
9697         __u16 read_mirror_id = 0;
9698         __u16 ids[128] = { 0 };
9699         int count = 0;
9700         struct llapi_layout *layout = NULL;
9701         struct llapi_resync_comp comp_array[1024] = { { 0 } };
9702         int comp_size = 0;
9703         char *fname;
9704         int fd = 0;
9705         int c;
9706         int i;
9707         ssize_t copied;
9708         struct ll_ioc_lease *ioc = NULL;
9709         struct ll_ioc_lease_id *resync_ioc;
9710
9711         struct option long_opts[] = {
9712         { .val = 'i',   .name = "read-mirror",  .has_arg = required_argument },
9713         { .val = 'o',   .name = "write-mirror", .has_arg = required_argument },
9714         { .name = NULL } };
9715
9716         while ((c = getopt_long(argc, argv, "i:o:", long_opts, NULL)) >= 0) {
9717                 char *end;
9718
9719                 switch (c) {
9720                 case 'i':
9721                         read_mirror_id = strtoul(optarg, &end, 0);
9722                         if (*end != '\0' || read_mirror_id == 0) {
9723                                 fprintf(stderr,
9724                                         "%s %s: invalid read mirror ID '%s'\n",
9725                                         progname, argv[0], optarg);
9726                                 return rc;
9727                         }
9728                         break;
9729                 case 'o':
9730                         if (!strcmp(optarg, "-1")) {
9731                                 /* specify all other mirrors */
9732                                 ids[0] = (__u16)-1;
9733                                 count = 1;
9734                         } else {
9735                                 count = parse_mirror_ids((__u16 *)ids,
9736                                                          ARRAY_SIZE(ids),
9737                                                          optarg);
9738                                 if (count < 0)
9739                                         return rc;
9740                         }
9741                         break;
9742                 default:
9743                         fprintf(stderr, "%s: option '%s' unrecognized\n",
9744                                 progname, argv[optind - 1]);
9745                         return -EINVAL;
9746                 }
9747         }
9748
9749         if (argc == optind) {
9750                 fprintf(stderr, "%s %s: no mirrored file provided\n",
9751                         progname, argv[0]);
9752                 return rc;
9753         } else if (argc > optind + 1) {
9754                 fprintf(stderr, "%s %s: too many files\n", progname, argv[0]);
9755                 return rc;
9756         }
9757
9758         if (read_mirror_id == 0) {
9759                 fprintf(stderr,
9760                         "%s %s: no valid read mirror ID %d is provided\n",
9761                         progname, argv[0], read_mirror_id);
9762                 return rc;
9763         }
9764
9765         if (count == 0) {
9766                 fprintf(stderr,
9767                         "%s %s: no write mirror ID is provided\n",
9768                         progname, argv[0]);
9769                 return rc;
9770         }
9771
9772         for (i = 0; i < count; i++) {
9773                 if (read_mirror_id == ids[i]) {
9774                         fprintf(stderr,
9775                         "%s %s: read and write mirror ID cannot be the same\n",
9776                                 progname, argv[0]);
9777                         return rc;
9778                 }
9779         }
9780
9781         /* open mirror file */
9782         fname = argv[optind];
9783
9784         fd = open(fname, O_DIRECT | O_RDWR);
9785         if (fd < 0) {
9786                 fprintf(stderr, "%s %s: cannot open '%s': %s\n",
9787                         progname, argv[0], fname, strerror(errno));
9788                 return rc;
9789         }
9790
9791         /* write to all other mirrors */
9792         if (ids[0] == (__u16)-1) {
9793                 count = get_other_mirror_ids(fd, ids, read_mirror_id);
9794                 if (count <= 0) {
9795                         rc = count;
9796                         fprintf(stderr,
9797                         "%s %s: failed to get other mirror ids in '%s': %d\n",
9798                                 progname, argv[0], fname, rc);
9799                         goto close_fd;
9800                 }
9801         }
9802
9803         /* verify mirror id */
9804         rc = verify_mirror_id_by_fd(fd, read_mirror_id);
9805         if (rc) {
9806                 fprintf(stderr,
9807                         "%s %s: cannot find mirror with ID %u in '%s'\n",
9808                         progname, argv[0], read_mirror_id, fname);
9809                 goto close_fd;
9810         }
9811
9812         for (i = 0; i < count; i++) {
9813                 rc = verify_mirror_id_by_fd(fd, ids[i]);
9814                 if (rc) {
9815                         fprintf(stderr,
9816                         "%s %s: cannot find mirror with ID %u in '%s'\n",
9817                                 progname, argv[0], ids[i], fname);
9818                         goto close_fd;
9819                 }
9820         }
9821
9822         ioc = calloc(sizeof(*ioc) + sizeof(__u32) * 4096, 1);
9823         if (ioc == NULL) {
9824                 fprintf(stderr,
9825                         "%s %s: cannot alloc comp id array for ioc: %s\n",
9826                         progname, argv[0], strerror(errno));
9827                 rc = -errno;
9828                 goto close_fd;
9829         }
9830
9831         /* get stale component info */
9832         layout = llapi_layout_get_by_fd(fd, 0);
9833         if (layout == NULL) {
9834                 fprintf(stderr, "%s %s: failed to get layout of '%s': %s\n",
9835                         progname, argv[0], fname, strerror(errno));
9836                 rc = -errno;
9837                 goto free_ioc;
9838         }
9839         comp_size = llapi_mirror_find_stale(layout, comp_array,
9840                                             ARRAY_SIZE(comp_array),
9841                                             ids, count);
9842         llapi_layout_free(layout);
9843         if (comp_size < 0) {
9844                 rc = comp_size;
9845                 goto free_ioc;
9846         }
9847
9848         /* prepare target mirror components instantiation */
9849         resync_ioc = (struct ll_ioc_lease_id *)ioc;
9850         resync_ioc->lil_mode = LL_LEASE_WRLCK;
9851         resync_ioc->lil_flags = LL_LEASE_RESYNC;
9852         if (count == 1)
9853                 resync_ioc->lil_mirror_id = ids[0];
9854         else
9855                 resync_ioc->lil_mirror_id = read_mirror_id | MIRROR_ID_NEG;
9856         rc = llapi_lease_set(fd, ioc);
9857         if (rc < 0) {
9858                 fprintf(stderr,
9859                         "%s %s: '%s' llapi_lease_get_ext failed: %s\n",
9860                         progname, argv[0], fname, strerror(errno));
9861                 goto free_ioc;
9862         }
9863
9864         copied = llapi_mirror_copy_many(fd, read_mirror_id, ids, count);
9865         if (copied < 0) {
9866                 rc = copied;
9867                 fprintf(stderr, "%s %s: copy error: %d\n",
9868                         progname, argv[0], rc);
9869                 goto free_ioc;
9870         }
9871
9872         fprintf(stdout, "mirror copied successfully: ");
9873         for (i = 0; i < copied; i++)
9874                 fprintf(stdout, "%d ", ids[i]);
9875         fprintf(stdout, "\n");
9876
9877         ioc->lil_mode = LL_LEASE_UNLCK;
9878         ioc->lil_flags = LL_LEASE_RESYNC_DONE;
9879         ioc->lil_count = 0;
9880         for (i = 0; i < comp_size; i++) {
9881                 int j;
9882
9883                 for (j = 0; j < copied; j++) {
9884                         if (comp_array[i].lrc_mirror_id != ids[j])
9885                                 continue;
9886
9887                         ioc->lil_ids[ioc->lil_count] = comp_array[i].lrc_id;
9888                         ioc->lil_count++;
9889                 }
9890         }
9891         rc = llapi_lease_set(fd, ioc);
9892         if (rc <= 0) {
9893                 if (rc == 0)
9894                         rc = -EBUSY;
9895                 fprintf(stderr,
9896                         "%s %s: release lease lock of '%s' failed: %s\n",
9897                         progname, argv[0], fname, strerror(errno));
9898                 goto free_ioc;
9899         }
9900
9901         rc = 0;
9902
9903 free_ioc:
9904         free(ioc);
9905 close_fd:
9906         close(fd);
9907
9908         return rc;
9909 }
9910 /**
9911  * struct verify_chunk - Mirror chunk to be verified.
9912  * @chunk:        [start, end) of the chunk.
9913  * @mirror_count: Number of mirror ids in @mirror_id array.
9914  * @mirror_id:    Array of valid mirror ids that cover the chunk.
9915  */
9916 struct verify_chunk {
9917         struct lu_extent chunk;
9918         unsigned int mirror_count;
9919         __u16 mirror_id[LUSTRE_MIRROR_COUNT_MAX];
9920 };
9921
9922 /**
9923  * print_chunks() - Print chunk information.
9924  * @fname:       Mirrored file name.
9925  * @chunks:      Array of chunks.
9926  * @chunk_count: Number of chunks in @chunks array.
9927  *
9928  * This function prints [start, end) of each chunk in @chunks
9929  * for mirrored file @fname, and also prints the valid mirror ids
9930  * that cover the chunk.
9931  *
9932  * Return: void.
9933  */
9934 static inline
9935 void print_chunks(const char *fname, struct verify_chunk *chunks,
9936                   int chunk_count)
9937 {
9938         int i;
9939         int j;
9940
9941         fprintf(stdout, "Chunks to be verified in %s:\n", fname);
9942         for (i = 0; i < chunk_count; i++) {
9943                 fprintf(stdout, DEXT, PEXT(&chunks[i].chunk));
9944
9945                 if (chunks[i].mirror_count == 0)
9946                         fprintf(stdout, "\t[");
9947                 else {
9948                         fprintf(stdout, "\t[%u", chunks[i].mirror_id[0]);
9949                         for (j = 1; j < chunks[i].mirror_count; j++)
9950                                 fprintf(stdout, ", %u", chunks[i].mirror_id[j]);
9951                 }
9952                 fprintf(stdout, "]\t%u\n", chunks[i].mirror_count);
9953         }
9954         fprintf(stdout, "\n");
9955 }
9956
9957 /**
9958  * print_checksums() - Print CRC-32 checksum values.
9959  * @chunk: A chunk and its corresponding valid mirror ids.
9960  * @crc:   CRC-32 checksum values on the chunk for each valid mirror.
9961  *
9962  * This function prints CRC-32 checksum values on @chunk for
9963  * each valid mirror that covers it.
9964  *
9965  * Return: void.
9966  */
9967 static inline
9968 void print_checksums(struct verify_chunk *chunk, unsigned long *crc)
9969 {
9970         int i;
9971
9972         fprintf(stdout,
9973                 "CRC-32 checksum value for chunk "DEXT":\n",
9974                 PEXT(&chunk->chunk));
9975         for (i = 0; i < chunk->mirror_count; i++)
9976                 fprintf(stdout, "Mirror %u:\t%#lx\n",
9977                         chunk->mirror_id[i], crc[i]);
9978         fprintf(stdout, "\n");
9979 }
9980
9981 /**
9982  * filter_mirror_id() - Filter specified mirror ids.
9983  * @chunks:      Array of chunks.
9984  * @chunk_count: Number of chunks in @chunks array.
9985  * @mirror_ids:  Specified mirror ids to be verified.
9986  * @ids_nr:      Number of specified mirror ids.
9987  *
9988  * This function scans valid mirror ids that cover each chunk in @chunks
9989  * and filters specified mirror ids.
9990  *
9991  * Return: void.
9992  */
9993 static inline
9994 void filter_mirror_id(struct verify_chunk *chunks, int chunk_count,
9995                       __u16 *mirror_ids, int ids_nr)
9996 {
9997         int i;
9998         int j;
9999         int k;
10000         __u16 valid_id[LUSTRE_MIRROR_COUNT_MAX] = { 0 };
10001         unsigned int valid_count = 0;
10002
10003         for (i = 0; i < chunk_count; i++) {
10004                 if (chunks[i].mirror_count == 0)
10005                         continue;
10006
10007                 valid_count = 0;
10008                 for (j = 0; j < ids_nr; j++) {
10009                         for (k = 0; k < chunks[i].mirror_count; k++) {
10010                                 if (chunks[i].mirror_id[k] == mirror_ids[j]) {
10011                                         valid_id[valid_count] = mirror_ids[j];
10012                                         valid_count++;
10013                                         break;
10014                                 }
10015                         }
10016                 }
10017
10018                 memcpy(chunks[i].mirror_id, valid_id,
10019                        sizeof(__u16) * valid_count);
10020                 chunks[i].mirror_count = valid_count;
10021         }
10022 }
10023
10024 /**
10025  * lfs_mirror_prepare_chunk() - Find mirror chunks to be verified.
10026  * @layout:      Mirror component list.
10027  * @chunks:      Array of chunks.
10028  * @chunks_size: Array size of @chunks.
10029  *
10030  * This function scans the components in @layout from offset 0 to LUSTRE_EOF
10031  * to find out chunk segments and store them in @chunks array.
10032  *
10033  * The @mirror_id array in each element of @chunks will store the valid
10034  * mirror ids that cover the chunk. If a mirror component covering the
10035  * chunk has LCME_FL_STALE or LCME_FL_OFFLINE flag, then the mirror id
10036  * will not be stored into the @mirror_id array, and the chunk for that
10037  * mirror will not be verified.
10038  *
10039  * The @mirror_count in each element of @chunks will store the number of
10040  * mirror ids in @mirror_id array. If @mirror_count is 0, it indicates the
10041  * chunk is invalid in all of the mirrors. And if @mirror_count is 1, it
10042  * indicates the chunk is valid in only one mirror. In both cases, the
10043  * chunk will not be verified.
10044  *
10045  * Here is an example:
10046  *
10047  *  0      1M     2M     3M     4M           EOF
10048  *  +------+-------------+--------------------+
10049  *  |      |             |      S             |       mirror1
10050  *  +------+------+------+------+-------------+
10051  *  |             |   S  |   S  |             |       mirror2
10052  *  +-------------+------+------+-------------+
10053  *
10054  * prepared @chunks array will contain 5 elements:
10055  * (([0, 1M), [1, 2], 2),
10056  *  ([1M, 2M), [1, 2], 2),
10057  *  ([2M, 3M), [1], 1),
10058  *  ([3M, 4M], [], 0),
10059  *  ([4M, EOF), [2], 1))
10060  *
10061  * Return: the actual array size of @chunks on success
10062  *         or a negative error code on failure.
10063  */
10064 static inline
10065 int lfs_mirror_prepare_chunk(struct llapi_layout *layout,
10066                              struct verify_chunk *chunks,
10067                              size_t chunks_size)
10068 {
10069         uint64_t start;
10070         uint64_t end;
10071         uint32_t mirror_id;
10072         uint32_t flags;
10073         int idx = 0;
10074         int i = 0;
10075         int rc = 0;
10076
10077         memset(chunks, 0, sizeof(*chunks) * chunks_size);
10078
10079         while (1) {
10080                 rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_FIRST);
10081                 if (rc < 0) {
10082                         fprintf(stderr,
10083                                 "%s: move to the first layout component: %s.\n",
10084                                 progname, strerror(errno));
10085                         goto error;
10086                 }
10087
10088                 i = 0;
10089                 rc = 0;
10090                 chunks[idx].chunk.e_end = LUSTRE_EOF;
10091                 while (rc == 0) {
10092                         rc = llapi_layout_comp_extent_get(layout, &start, &end);
10093                         if (rc < 0) {
10094                                 fprintf(stderr,
10095                                         "%s: llapi_layout_comp_extent_get failed: %s.\n",
10096                                         progname, strerror(errno));
10097                                 goto error;
10098                         }
10099
10100                         if (start > chunks[idx].chunk.e_start ||
10101                             end <= chunks[idx].chunk.e_start)
10102                                 goto next;
10103
10104                         if (end < chunks[idx].chunk.e_end)
10105                                 chunks[idx].chunk.e_end = end;
10106
10107                         rc = llapi_layout_comp_flags_get(layout, &flags);
10108                         if (rc < 0) {
10109                                 fprintf(stderr,
10110                                         "%s: llapi_layout_comp_flags_get failed: %s.\n",
10111                                         progname, strerror(errno));
10112                                 goto error;
10113                         }
10114
10115                         if (flags & LCME_FL_STALE || flags & LCME_FL_OFFLINE)
10116                                 goto next;
10117
10118                         rc = llapi_layout_mirror_id_get(layout, &mirror_id);
10119                         if (rc < 0) {
10120                                 fprintf(stderr,
10121                                         "%s: llapi_layout_mirror_id_get failed: %s.\n",
10122                                         progname, strerror(errno));
10123                                 goto error;
10124                         }
10125
10126                         chunks[idx].mirror_id[i] = mirror_id;
10127                         i++;
10128                         if (i >= ARRAY_SIZE(chunks[idx].mirror_id)) {
10129                                 fprintf(stderr,
10130                                         "%s: mirror_id array is too small.\n",
10131                                         progname);
10132                                 rc = -EINVAL;
10133                                 goto error;
10134                         }
10135
10136                 next:
10137                         rc = llapi_layout_comp_use(layout,
10138                                                    LLAPI_LAYOUT_COMP_USE_NEXT);
10139                         if (rc < 0) {
10140                                 fprintf(stderr,
10141                                         "%s: move to the next layout component: %s.\n",
10142                                         progname, strerror(errno));
10143                                 goto error;
10144                         }
10145                 } /* loop through all components */
10146
10147                 chunks[idx].mirror_count = i;
10148
10149                 if (chunks[idx].chunk.e_end == LUSTRE_EOF)
10150                         break;
10151
10152                 idx++;
10153                 if (idx >= chunks_size) {
10154                         fprintf(stderr, "%s: chunks array is too small.\n",
10155                                 progname);
10156                         rc = -EINVAL;
10157                         goto error;
10158                 }
10159
10160                 chunks[idx].chunk.e_start = chunks[idx - 1].chunk.e_end;
10161         }
10162
10163 error:
10164         return rc < 0 ? rc : idx + 1;
10165 }
10166
10167 /**
10168  * lfs_mirror_verify_chunk() - Verify a chunk.
10169  * @fd:        File descriptor of the mirrored file.
10170  * @file_size: Size of the mirrored file.
10171  * @chunk:     A chunk and its corresponding valid mirror ids.
10172  * @verbose:   Verbose mode.
10173  *
10174  * This function verifies a @chunk contains exactly the same data
10175  * ammong the mirrors that cover it.
10176  *
10177  * If @verbose is specified, then the function will print where the
10178  * differences are if the data do not match. Otherwise, it will
10179  * just return an error in that case.
10180  *
10181  * Return: 0 on success or a negative error code on failure.
10182  */
10183 static inline
10184 int lfs_mirror_verify_chunk(int fd, size_t file_size,
10185                             struct verify_chunk *chunk, int verbose)
10186 {
10187         const size_t buflen = 4 * 1024 * 1024; /* 4M */
10188         void *buf;
10189         size_t page_size = sysconf(_SC_PAGESIZE);
10190         ssize_t bytes_read;
10191         ssize_t bytes_done;
10192         size_t count;
10193         off_t pos;
10194         unsigned long crc;
10195         unsigned long crc_array[LUSTRE_MIRROR_COUNT_MAX] = { 0 };
10196         int i;
10197         int rc = 0;
10198
10199         if (file_size == 0)
10200                 return 0;
10201
10202         rc = posix_memalign(&buf, page_size, buflen);
10203         if (rc) /* error code is returned directly */
10204                 return -rc;
10205
10206         if (verbose > 1) {
10207                 fprintf(stdout, "Verifying chunk "DEXT" on mirror:",
10208                         PEXT(&chunk->chunk));
10209                 for (i = 0; i < chunk->mirror_count; i++)
10210                         fprintf(stdout, " %u", chunk->mirror_id[i]);
10211                 fprintf(stdout, "\n");
10212         }
10213
10214         bytes_done = 0;
10215         count = MIN(chunk->chunk.e_end, file_size) - chunk->chunk.e_start;
10216         pos = chunk->chunk.e_start;
10217         while (bytes_done < count) {
10218                 /* compute initial CRC-32 checksum */
10219                 crc = crc32(0L, Z_NULL, 0);
10220                 memset(crc_array, 0, sizeof(crc_array));
10221
10222                 bytes_read = 0;
10223                 for (i = 0; i < chunk->mirror_count; i++) {
10224                         bytes_read = llapi_mirror_read(fd, chunk->mirror_id[i],
10225                                                        buf, buflen, pos);
10226                         if (bytes_read < 0) {
10227                                 rc = bytes_read;
10228                                 fprintf(stderr,
10229                                         "%s: failed to read data from mirror %u: %s.\n",
10230                                         progname, chunk->mirror_id[i],
10231                                         strerror(-rc));
10232                                 goto error;
10233                         }
10234
10235                         /* compute new CRC-32 checksum */
10236                         crc_array[i] = crc32(crc, buf, bytes_read);
10237                 }
10238
10239                 if (verbose)
10240                         print_checksums(chunk, crc_array);
10241
10242                 /* compare CRC-32 checksum values */
10243                 for (i = 1; i < chunk->mirror_count; i++) {
10244                         if (crc_array[i] != crc_array[0]) {
10245                                 rc = -EINVAL;
10246
10247                                 fprintf(stderr,
10248                                         "%s: chunk "DEXT" has different checksum value on mirror %u and mirror %u.\n",
10249                                         progname, PEXT(&chunk->chunk),
10250                                         chunk->mirror_id[0],
10251                                         chunk->mirror_id[i]);
10252                         }
10253                 }
10254
10255                 pos += bytes_read;
10256                 bytes_done += bytes_read;
10257         }
10258
10259         if (verbose > 1 && rc == 0) {
10260                 fprintf(stdout, "Verifying chunk "DEXT" on mirror:",
10261                         PEXT(&chunk->chunk));
10262                 for (i = 0; i < chunk->mirror_count; i++)
10263                         fprintf(stdout, " %u", chunk->mirror_id[i]);
10264                 fprintf(stdout, " PASS\n\n");
10265         }
10266
10267 error:
10268         free(buf);
10269         return rc;
10270 }
10271
10272 /**
10273  * lfs_mirror_verify_file() - Verify a mirrored file.
10274  * @fname:      Mirrored file name.
10275  * @mirror_ids: Specified mirror ids to be verified.
10276  * @ids_nr:     Number of specified mirror ids.
10277  * @verbose:    Verbose mode.
10278  *
10279  * This function verifies that each SYNC mirror of a mirrored file
10280  * specified by @fname contains exactly the same data.
10281  *
10282  * If @mirror_ids is specified, then the function will verify the
10283  * mirrors specified by @mirror_ids contain exactly the same data.
10284  *
10285  * If @verbose is specified, then the function will print where the
10286  * differences are if the data do not match. Otherwise, it will
10287  * just return an error in that case.
10288  *
10289  * Return: 0 on success or a negative error code on failure.
10290  */
10291 static inline
10292 int lfs_mirror_verify_file(const char *fname, __u16 *mirror_ids, int ids_nr,
10293                            int verbose)
10294 {
10295         struct verify_chunk chunks_array[1024] = { };
10296         struct llapi_layout *layout = NULL;
10297         struct stat stbuf;
10298         uint32_t flr_state;
10299         int fd;
10300         int chunk_count = 0;
10301         int idx = 0;
10302         int rc = 0;
10303         int rc1 = 0;
10304         int rc2 = 0;
10305
10306         if (stat(fname, &stbuf) < 0) {
10307                 fprintf(stderr, "%s: cannot stat file '%s': %s.\n",
10308                         progname, fname, strerror(errno));
10309                 rc = -errno;
10310                 goto error;
10311         }
10312
10313         if (!S_ISREG(stbuf.st_mode)) {
10314                 fprintf(stderr, "%s: '%s' is not a regular file.\n",
10315                         progname, fname);
10316                 rc = -EINVAL;
10317                 goto error;
10318         }
10319
10320         if (stbuf.st_size == 0) {
10321                 if (verbose)
10322                         fprintf(stdout, "%s: '%s' file size is 0.\n",
10323                                 progname, fname);
10324                 rc = 0;
10325                 goto error;
10326         }
10327
10328         fd = open(fname, O_DIRECT | O_RDONLY);
10329         if (fd < 0) {
10330                 fprintf(stderr, "%s: cannot open '%s': %s.\n",
10331                         progname, fname, strerror(errno));
10332                 rc = -errno;
10333                 goto error;
10334         }
10335
10336         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
10337         if (rc < 0) {
10338                 fprintf(stderr, "%s: '%s' llapi_lease_acquire failed: %s.\n",
10339                         progname, fname, strerror(errno));
10340                 goto close_fd;
10341         }
10342
10343         layout = llapi_layout_get_by_fd(fd, 0);
10344         if (layout == NULL) {
10345                 fprintf(stderr, "%s: '%s' llapi_layout_get_by_fd failed: %s.\n",
10346                         progname, fname, strerror(errno));
10347                 rc = -errno;
10348                 llapi_lease_release(fd);
10349                 goto close_fd;
10350         }
10351
10352         rc = llapi_layout_flags_get(layout, &flr_state);
10353         if (rc < 0) {
10354                 fprintf(stderr, "%s: '%s' llapi_layout_flags_get failed: %s.\n",
10355                         progname, fname, strerror(errno));
10356                 rc = -errno;
10357                 goto free_layout;
10358         }
10359
10360         flr_state &= LCM_FL_FLR_MASK;
10361         switch (flr_state) {
10362         case LCM_FL_NONE:
10363                 rc = -EINVAL;
10364                 fprintf(stderr, "%s: '%s' file state error: %s.\n",
10365                         progname, fname, llapi_layout_flags_string(flr_state));
10366                 goto free_layout;
10367         default:
10368                 break;
10369         }
10370
10371         /* find out mirror chunks to be verified */
10372         chunk_count = lfs_mirror_prepare_chunk(layout, chunks_array,
10373                                                ARRAY_SIZE(chunks_array));
10374         if (chunk_count < 0) {
10375                 rc = chunk_count;
10376                 goto free_layout;
10377         }
10378
10379         if (ids_nr > 0)
10380                 /* filter specified mirror ids */
10381                 filter_mirror_id(chunks_array, chunk_count, mirror_ids, ids_nr);
10382
10383         if (verbose > 2)
10384                 print_chunks(fname, chunks_array, chunk_count);
10385
10386         for (idx = 0; idx < chunk_count; idx++) {
10387                 if (chunks_array[idx].chunk.e_start >= stbuf.st_size) {
10388                         if (verbose)
10389                                 fprintf(stdout,
10390                                         "%s: '%s' chunk "DEXT" exceeds file size %#llx: skipped\n",
10391                                         progname, fname,
10392                                         PEXT(&chunks_array[idx].chunk),
10393                                         (unsigned long long)stbuf.st_size);
10394                         break;
10395                 }
10396
10397                 if (chunks_array[idx].mirror_count == 0) {
10398                         fprintf(stderr,
10399                                 "%s: '%s' chunk "DEXT" is invalid in all of the mirrors: ",
10400                                 progname, fname,
10401                                 PEXT(&chunks_array[idx].chunk));
10402                         if (verbose) {
10403                                 fprintf(stderr, "skipped\n");
10404                                 continue;
10405                         }
10406                         rc = -EINVAL;
10407                         fprintf(stderr, "failed\n");
10408                         goto free_layout;
10409                 }
10410
10411                 if (chunks_array[idx].mirror_count == 1) {
10412                         if (verbose)
10413                                 fprintf(stdout,
10414                                         "%s: '%s' chunk "DEXT" is only valid in mirror %u: skipped\n",
10415                                         progname, fname,
10416                                         PEXT(&chunks_array[idx].chunk),
10417                                         chunks_array[idx].mirror_id[0]);
10418                         continue;
10419                 }
10420
10421                 rc = llapi_lease_check(fd);
10422                 if (rc != LL_LEASE_RDLCK) {
10423                         fprintf(stderr, "%s: '%s' lost lease lock.\n",
10424                                 progname, fname);
10425                         goto free_layout;
10426                 }
10427
10428                 /* verify one chunk */
10429                 rc1 = lfs_mirror_verify_chunk(fd, stbuf.st_size,
10430                                               &chunks_array[idx], verbose);
10431                 if (rc1 < 0) {
10432                         rc2 = rc1;
10433                         if (!verbose) {
10434                                 rc = rc1;
10435                                 goto free_layout;
10436                         }
10437                 }
10438         }
10439
10440         if (rc2 < 0)
10441                 rc = rc2;
10442
10443 free_layout:
10444         llapi_layout_free(layout);
10445         llapi_lease_release(fd);
10446 close_fd:
10447         close(fd);
10448 error:
10449         return rc;
10450 }
10451
10452 /**
10453  * lfs_mirror_verify() - Parse and execute lfs mirror verify command.
10454  * @argc: The count of lfs mirror verify command line arguments.
10455  * @argv: Array of strings for lfs mirror verify command line arguments.
10456  *
10457  * This function parses lfs mirror verify command and verifies the
10458  * specified mirrored file(s).
10459  *
10460  * Return: 0 on success or a negative error code on failure.
10461  */
10462 static inline int lfs_mirror_verify(int argc, char **argv)
10463 {
10464         __u16 mirror_ids[LUSTRE_MIRROR_COUNT_MAX] = { 0 };
10465         int ids_nr = 0;
10466         int c;
10467         int verbose = 0;
10468         int rc = 0;
10469         int rc1 = 0;
10470         char cmd[PATH_MAX];
10471
10472         struct option long_opts[] = {
10473         { .val = 'o',   .name = "only",         .has_arg = required_argument },
10474         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
10475         { .name = NULL } };
10476
10477         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
10478         progname = cmd;
10479         while ((c = getopt_long(argc, argv, "o:v", long_opts, NULL)) >= 0) {
10480                 switch (c) {
10481                 case 'o':
10482                         rc = parse_mirror_ids(mirror_ids,
10483                                               ARRAY_SIZE(mirror_ids),
10484                                               optarg);
10485                         if (rc < 0) {
10486                                 fprintf(stderr,
10487                                         "%s: bad mirror ids '%s'.\n",
10488                                         progname, optarg);
10489                                 goto error;
10490                         }
10491                         ids_nr = rc;
10492                         if (ids_nr < 2) {
10493                                 fprintf(stderr,
10494                                         "%s: at least 2 mirror ids needed with '--only' option.\n",
10495                                         progname);
10496                                 rc = CMD_HELP;
10497                                 goto error;
10498                         }
10499                         break;
10500                 case 'v':
10501                         verbose++;
10502                         break;
10503                 default:
10504                         fprintf(stderr, "%s: option '%s' unrecognized.\n",
10505                                 progname, argv[optind - 1]);
10506                         rc = -EINVAL;
10507                         goto error;
10508                 }
10509         }
10510
10511         if (argc == optind) {
10512                 fprintf(stderr, "%s: no file name given.\n", progname);
10513                 rc = CMD_HELP;
10514                 goto error;
10515         }
10516
10517         if (ids_nr > 0 && argc > optind + 1) {
10518                 fprintf(stderr,
10519                         "%s: '--only' cannot be used upon multiple files.\n",
10520                         progname);
10521                 rc = CMD_HELP;
10522                 goto error;
10523
10524         }
10525
10526         if (ids_nr > 0) {
10527                 rc = verify_mirror_ids(argv[optind], mirror_ids, ids_nr);
10528                 if (rc < 0)
10529                         goto error;
10530         }
10531
10532         rc = 0;
10533         for (; optind < argc; optind++) {
10534                 rc1 = lfs_mirror_verify_file(argv[optind], mirror_ids, ids_nr,
10535                                              verbose);
10536                 if (rc1 < 0)
10537                         rc = rc1;
10538         }
10539 error:
10540         return rc;
10541 }
10542
10543 /**
10544  * lfs_mirror() - Parse and execute lfs mirror commands.
10545  * @argc: The count of lfs mirror command line arguments.
10546  * @argv: Array of strings for lfs mirror command line arguments.
10547  *
10548  * This function parses lfs mirror commands and performs the
10549  * corresponding functions specified in mirror_cmdlist[].
10550  *
10551  * Return: 0 on success or an error code on failure.
10552  */
10553 static int lfs_mirror(int argc, char **argv)
10554 {
10555         char cmd[PATH_MAX];
10556         int rc = 0;
10557
10558         setlinebuf(stdout);
10559
10560         Parser_init("lfs-mirror > ", mirror_cmdlist);
10561
10562         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
10563         progname = cmd;
10564         program_invocation_short_name = cmd;
10565         if (argc > 1)
10566                 rc = Parser_execarg(argc - 1, argv + 1, mirror_cmdlist);
10567         else
10568                 rc = Parser_commands();
10569
10570         return rc < 0 ? -rc : rc;
10571 }
10572
10573 static void lustre_som_swab(struct lustre_som_attrs *attrs)
10574 {
10575 #if __BYTE_ORDER == __BIG_ENDIAN
10576         __swab16s(&attrs->lsa_valid);
10577         __swab64s(&attrs->lsa_size);
10578         __swab64s(&attrs->lsa_blocks);
10579 #endif
10580 }
10581
10582 enum lfs_som_type {
10583         LFS_SOM_SIZE = 0x1,
10584         LFS_SOM_BLOCKS = 0x2,
10585         LFS_SOM_FLAGS = 0x4,
10586         LFS_SOM_ATTR_ALL = LFS_SOM_SIZE | LFS_SOM_BLOCKS |
10587                            LFS_SOM_FLAGS,
10588 };
10589
10590 static int lfs_getsom(int argc, char **argv)
10591 {
10592         const char *path;
10593         struct lustre_som_attrs *attrs;
10594         char buf[sizeof(*attrs) + 64];
10595         enum lfs_som_type type = LFS_SOM_ATTR_ALL;
10596         int rc = 0, c;
10597
10598         while ((c = getopt(argc, argv, "sbf")) != -1) {
10599                 switch (c) {
10600                 case 's':
10601                         type = LFS_SOM_SIZE;
10602                         break;
10603                 case 'b':
10604                         type = LFS_SOM_BLOCKS;
10605                         break;
10606                 case 'f':
10607                         type = LFS_SOM_FLAGS;
10608                         break;
10609                 default:
10610                         fprintf(stderr, "%s: invalid option '%c'\n",
10611                                 progname, optopt);
10612                         return CMD_HELP;
10613                 }
10614         }
10615
10616         argc -= optind;
10617         argv += optind;
10618
10619         if (argc != 1) {
10620                 fprintf(stderr, "%s: %s\n",
10621                         progname, argc == 0 ? "miss file target" :
10622                         "input more than 2 files");
10623                 return CMD_HELP;
10624         }
10625
10626         path = argv[0];
10627         attrs = (void *)buf;
10628         rc = lgetxattr(path, "trusted.som", attrs, sizeof(buf));
10629         if (rc < 0) {
10630                 rc = -errno;
10631                 fprintf(stderr, "%s failed to get som xattr: %s (%d)\n",
10632                         argv[0], strerror(errno), errno);
10633                 return rc;
10634         }
10635
10636         lustre_som_swab(attrs);
10637
10638         switch (type) {
10639         case LFS_SOM_ATTR_ALL:
10640                 printf("file: %s size: %llu blocks: %llu flags: %x\n",
10641                        path, (unsigned long long)attrs->lsa_size,
10642                        (unsigned long long)attrs->lsa_blocks,
10643                        attrs->lsa_valid);
10644                 break;
10645         case LFS_SOM_SIZE:
10646                 printf("%llu\n", (unsigned long long)attrs->lsa_size);
10647                 break;
10648         case LFS_SOM_BLOCKS:
10649                 printf("%llu\n", (unsigned long long)attrs->lsa_blocks);
10650                 break;
10651         case LFS_SOM_FLAGS:
10652                 printf("%x\n", attrs->lsa_valid);
10653                 break;
10654         default:
10655                 fprintf(stderr, "%s: unknown option\n", progname);
10656                 return CMD_HELP;
10657         }
10658
10659         return 0;
10660 }
10661
10662 /**
10663  * lfs_mirror_list_commands() - List lfs mirror commands.
10664  * @argc: The count of command line arguments.
10665  * @argv: Array of strings for command line arguments.
10666  *
10667  * This function lists lfs mirror commands defined in mirror_cmdlist[].
10668  *
10669  * Return: 0 on success.
10670  */
10671 static int lfs_mirror_list_commands(int argc, char **argv)
10672 {
10673         char buffer[81] = "";
10674
10675         Parser_list_commands(mirror_cmdlist, buffer, sizeof(buffer),
10676                              NULL, 0, 4);
10677
10678         return 0;
10679 }
10680
10681 static int lfs_pcc_attach(int argc, char **argv)
10682 {
10683         struct option long_opts[] = {
10684         { .val = 'i',   .name = "id",   .has_arg = required_argument },
10685         { .name = NULL } };
10686         int c;
10687         int rc = 0;
10688         __u32 archive_id = 0;
10689         const char *path;
10690         char *end;
10691         char fullpath[PATH_MAX];
10692         enum lu_pcc_type type = LU_PCC_READWRITE;
10693
10694         optind = 0;
10695         while ((c = getopt_long(argc, argv, "i:",
10696                                 long_opts, NULL)) != -1) {
10697                 switch (c) {
10698                 case 'i':
10699                         archive_id = strtoul(optarg, &end, 0);
10700                         if (*end != '\0' || archive_id == 0) {
10701                                 fprintf(stderr, "error: %s: bad archive ID "
10702                                         "'%s'\n", argv[0], optarg);
10703                                 return CMD_HELP;
10704                         }
10705                         break;
10706                 case '?':
10707                         return CMD_HELP;
10708                 default:
10709                         fprintf(stderr, "%s: option '%s' unrecognized\n",
10710                                 argv[0], argv[optind - 1]);
10711                         return CMD_HELP;
10712                 }
10713         }
10714
10715         if (argc <= optind) {
10716                 fprintf(stderr, "%s: must specify one or more file names\n",
10717                         argv[0]);
10718                 return CMD_HELP;
10719         }
10720
10721         while (optind < argc) {
10722                 int rc2;
10723
10724                 path = argv[optind++];
10725                 if (realpath(path, fullpath) == NULL) {
10726                         fprintf(stderr, "%s: could not find path '%s': %s\n",
10727                                 argv[0], path, strerror(errno));
10728                         if (rc == 0)
10729                                 rc = -EINVAL;
10730                         continue;
10731                 }
10732
10733                 rc2 = llapi_pcc_attach(fullpath, archive_id, type);
10734                 if (rc2 < 0) {
10735                         fprintf(stderr, "%s: cannot attach '%s' to PCC "
10736                                 "with archive ID '%u': %s\n", argv[0],
10737                                 path, archive_id, strerror(-rc2));
10738                         if (rc == 0)
10739                                 rc = rc2;
10740                 }
10741         }
10742         return rc;
10743 }
10744
10745 static int lfs_pcc_attach_fid(int argc, char **argv)
10746 {
10747         struct option long_opts[] = {
10748         { .val = 'i',   .name = "id",   .has_arg = required_argument },
10749         { .val = 'm',   .name = "mnt",  .has_arg = required_argument },
10750         { .name = NULL } };
10751         char                     short_opts[] = "i:m:";
10752         int                      c;
10753         int                      rc = 0;
10754         __u32                    archive_id = 0;
10755         char                    *end;
10756         const char              *mntpath = NULL;
10757         const char              *fidstr;
10758         enum lu_pcc_type         type = LU_PCC_READWRITE;
10759
10760         optind = 0;
10761         while ((c = getopt_long(argc, argv, short_opts,
10762                                 long_opts, NULL)) != -1) {
10763                 switch (c) {
10764                 case 'i':
10765                         archive_id = strtoul(optarg, &end, 0);
10766                         if (*end != '\0') {
10767                                 fprintf(stderr, "error: %s: bad archive ID "
10768                                         "'%s'\n", argv[0], optarg);
10769                                 return CMD_HELP;
10770                         }
10771                         break;
10772                 case 'm':
10773                         mntpath = optarg;
10774                         break;
10775                 case '?':
10776                         return CMD_HELP;
10777                 default:
10778                         fprintf(stderr, "%s: option '%s' unrecognized\n",
10779                                 argv[0], argv[optind - 1]);
10780                         return CMD_HELP;
10781                 }
10782         }
10783
10784         if (archive_id == 0) {
10785                 fprintf(stderr, "%s: must specify an archive ID\n", argv[0]);
10786                 return CMD_HELP;
10787         }
10788
10789         if (mntpath == NULL) {
10790                 fprintf(stderr, "%s: must specify Lustre mount point\n",
10791                         argv[0]);
10792                 return CMD_HELP;
10793         }
10794
10795         if (argc <= optind) {
10796                 fprintf(stderr, "%s: must specify one or more fids\n", argv[0]);
10797                 return CMD_HELP;
10798         }
10799
10800         while (optind < argc) {
10801                 int rc2;
10802
10803                 fidstr = argv[optind++];
10804
10805                 rc2 = llapi_pcc_attach_fid_str(mntpath, fidstr,
10806                                                archive_id, type);
10807                 if (rc2 < 0) {
10808                         fprintf(stderr, "%s: cannot attach '%s' on '%s' to PCC "
10809                                 "with archive ID '%u': %s\n", argv[0],
10810                                 fidstr, mntpath, archive_id, strerror(rc2));
10811                 }
10812                 if (rc == 0 && rc2 < 0)
10813                         rc = rc2;
10814         }
10815         return rc;
10816 }
10817
10818 static int lfs_pcc_detach(int argc, char **argv)
10819 {
10820         struct option long_opts[] = {
10821         { .val = 'k',   .name = "keep", .has_arg = no_argument },
10822         { .name = NULL } };
10823         char                     short_opts[] = "k";
10824         int                      c;
10825         int                      rc = 0;
10826         const char              *path;
10827         char                     fullpath[PATH_MAX];
10828         __u32                    detach_opt = PCC_DETACH_OPT_UNCACHE;
10829
10830         optind = 0;
10831         while ((c = getopt_long(argc, argv, short_opts,
10832                                 long_opts, NULL)) != -1) {
10833                 switch (c) {
10834                 case 'k':
10835                         detach_opt = PCC_DETACH_OPT_NONE;
10836                         break;
10837                 case '?':
10838                         return CMD_HELP;
10839                 default:
10840                         fprintf(stderr, "%s: option '%s' unrecognized\n",
10841                                 argv[0], argv[optind - 1]);
10842                         return CMD_HELP;
10843                 }
10844         }
10845
10846         while (optind < argc) {
10847                 int rc2;
10848
10849                 path = argv[optind++];
10850                 if (realpath(path, fullpath) == NULL) {
10851                         fprintf(stderr, "%s: could not find path '%s': %s\n",
10852                                 argv[0], path, strerror(errno));
10853                         if (rc == 0)
10854                                 rc = -EINVAL;
10855                         continue;
10856                 }
10857
10858                 rc2 = llapi_pcc_detach_file(fullpath, detach_opt);
10859                 if (rc2 < 0) {
10860                         rc2 = -errno;
10861                         fprintf(stderr, "%s: cannot detach '%s' from PCC: "
10862                                 "%s\n", argv[0], path, strerror(errno));
10863                         if (rc == 0)
10864                                 rc = rc2;
10865                 }
10866         }
10867         return rc;
10868 }
10869
10870 static int lfs_pcc_detach_fid(int argc, char **argv)
10871 {
10872         struct option long_opts[] = {
10873         { .val = 'k',   .name = "keep", .has_arg = no_argument },
10874         { .name = NULL } };
10875         char             short_opts[] = "k";
10876         int              c;
10877         int              rc = 0;
10878         const char      *fid;
10879         const char      *mntpath;
10880         __u32            detach_opt = PCC_DETACH_OPT_UNCACHE;
10881
10882         optind = 0;
10883         while ((c = getopt_long(argc, argv, short_opts,
10884                                 long_opts, NULL)) != -1) {
10885                 switch (c) {
10886                 case 'k':
10887                         detach_opt = PCC_DETACH_OPT_NONE;
10888                         break;
10889                 case '?':
10890                         return CMD_HELP;
10891                 default:
10892                         fprintf(stderr, "%s: option '%s' unrecognized\n",
10893                                 argv[0], argv[optind - 1]);
10894                         return CMD_HELP;
10895                 }
10896         }
10897
10898         mntpath = argv[optind++];
10899
10900         while (optind < argc) {
10901                 int rc2;
10902
10903                 fid = argv[optind++];
10904
10905                 rc2 = llapi_pcc_detach_fid_str(mntpath, fid, detach_opt);
10906                 if (rc2 < 0) {
10907                         fprintf(stderr, "%s: cannot detach '%s' on '%s' "
10908                                 "from PCC: %s\n", argv[0], fid, mntpath,
10909                                 strerror(-rc2));
10910                         if (rc == 0)
10911                                 rc = rc2;
10912                 }
10913         }
10914         return rc;
10915 }
10916
10917 static int lfs_pcc_state(int argc, char **argv)
10918 {
10919         int                      rc = 0;
10920         const char              *path;
10921         char                     fullpath[PATH_MAX];
10922         struct lu_pcc_state      state;
10923
10924         optind = 1;
10925
10926         if (argc <= 1) {
10927                 fprintf(stderr, "%s: must specify one or more file names\n",
10928                         argv[0]);
10929                 return CMD_HELP;
10930         }
10931
10932         while (optind < argc) {
10933                 int rc2;
10934
10935                 path = argv[optind++];
10936                 if (realpath(path, fullpath) == NULL) {
10937                         fprintf(stderr, "%s: could not find path '%s': %s\n",
10938                                 argv[0], path, strerror(errno));
10939                         if (rc == 0)
10940                                 rc = -EINVAL;
10941                         continue;
10942                 }
10943
10944                 rc2 = llapi_pcc_state_get(fullpath, &state);
10945                 if (rc2 < 0) {
10946                         if (rc == 0)
10947                                 rc = rc2;
10948                         fprintf(stderr, "%s: cannot get PCC state of '%s': "
10949                                 "%s\n", argv[0], path, strerror(-rc2));
10950                         continue;
10951                 }
10952
10953                 printf("file: %s", path);
10954                 printf(", type: %s", pcc_type2string(state.pccs_type));
10955                 if (state.pccs_type == LU_PCC_NONE &&
10956                     state.pccs_open_count == 0) {
10957                         printf("\n");
10958                         continue;
10959                 }
10960
10961                 printf(", PCC file: %s", state.pccs_path);
10962                 printf(", user number: %u", state.pccs_open_count);
10963                 printf(", flags: %x", state.pccs_flags);
10964                 printf("\n");
10965         }
10966         return rc;
10967 }
10968
10969 /**
10970  * lfs_pcc_list_commands() - List lfs pcc commands.
10971  * @argc: The count of command line arguments.
10972  * @argv: Array of strings for command line arguments.
10973  *
10974  * This function lists lfs pcc commands defined in pcc_cmdlist[].
10975  *
10976  * Return: 0 on success.
10977  */
10978 static int lfs_pcc_list_commands(int argc, char **argv)
10979 {
10980         char buffer[81] = "";
10981
10982         Parser_list_commands(pcc_cmdlist, buffer, sizeof(buffer),
10983                              NULL, 0, 4);
10984
10985         return 0;
10986 }
10987
10988 /**
10989  * lfs_pcc() - Parse and execute lfs pcc commands.
10990  * @argc: The count of lfs pcc command line arguments.
10991  * @argv: Array of strings for lfs pcc command line arguments.
10992  *
10993  * This function parses lfs pcc commands and performs the
10994  * corresponding functions specified in pcc_cmdlist[].
10995  *
10996  * Return: 0 on success or an error code on failure.
10997  */
10998 static int lfs_pcc(int argc, char **argv)
10999 {
11000         char cmd[PATH_MAX];
11001         int rc = 0;
11002
11003         setlinebuf(stdout);
11004
11005         Parser_init("lfs-pcc > ", pcc_cmdlist);
11006
11007         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
11008         progname = cmd;
11009         program_invocation_short_name = cmd;
11010         if (argc > 1)
11011                 rc = Parser_execarg(argc - 1, argv + 1, pcc_cmdlist);
11012         else
11013                 rc = Parser_commands();
11014
11015         return rc < 0 ? -rc : rc;
11016 }
11017
11018 static int lfs_list_commands(int argc, char **argv)
11019 {
11020         char buffer[81] = ""; /* 80 printable chars + terminating NUL */
11021
11022         Parser_list_commands(cmdlist, buffer, sizeof(buffer), NULL, 0, 4);
11023
11024         return 0;
11025 }
11026
11027 int main(int argc, char **argv)
11028 {
11029         int rc;
11030
11031         /* Ensure that liblustreapi constructor has run */
11032         if (!llapi_liblustreapi_initialized())
11033                 fprintf(stderr, "liblustreapi was not properly initialized\n");
11034
11035         setlinebuf(stdout);
11036         opterr = 0;
11037
11038         Parser_init("lfs > ", cmdlist);
11039
11040         progname = program_invocation_short_name; /* Used in error messages */
11041         if (argc > 1) {
11042                 llapi_set_command_name(argv[1]);
11043                 rc = Parser_execarg(argc - 1, argv + 1, cmdlist);
11044                 llapi_clear_command_name();
11045         } else {
11046                 rc = Parser_commands();
11047         }
11048
11049         return rc < 0 ? -rc : rc;
11050 }
11051
11052 #ifdef _LUSTRE_IDL_H_
11053 /* Everything we need here should be included by lustreapi.h. */
11054 # error "lfs should not depend on lustre_idl.h"
11055 #endif /* _LUSTRE_IDL_H_ */