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