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