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