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