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