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