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