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