Whamcloud - gitweb
LU-11380 llapi: separate FID man pages
[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                                 (long long)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                                 (unsigned long long)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                                 (long long)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                                 (unsigned long long)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                                 (unsigned long long)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                         (long long)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                                 (long long)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,
3767                                         (long long)lsa.lsa_stripe_count,
3768                                         lsa.lsa_nr_tgts);
3769                                 free(lmu);
3770                                 goto usage_error;
3771                         }
3772
3773                         lmu->lum_magic = LMV_USER_MAGIC_SPECIFIC;
3774                         lmu->lum_stripe_count = lsa.lsa_nr_tgts;
3775                         for (i = 0; i < lsa.lsa_nr_tgts; i++)
3776                                 lmu->lum_objects[i].lum_mds = lsa.lsa_tgts[i];
3777                 } else {
3778                         lmu->lum_magic = LMV_USER_MAGIC;
3779                 }
3780
3781                 migrate_mdt_param.fp_lmv_md = lmu;
3782                 migrate_mdt_param.fp_migrate = 1;
3783         } else if (layout == NULL) {
3784                 /* initialize stripe parameters */
3785                 param = calloc(1, offsetof(typeof(*param),
3786                                lsp_osts[lsa.lsa_nr_tgts]));
3787                 if (param == NULL) {
3788                         fprintf(stderr,
3789                                 "%s %s: cannot allocate memory for parameters: %s\n",
3790                                 progname, argv[0], strerror(ENOMEM));
3791                         result = -ENOMEM;
3792                         goto error;
3793                 }
3794
3795                 if (lsa.lsa_stripe_size != LLAPI_LAYOUT_DEFAULT)
3796                         param->lsp_stripe_size = lsa.lsa_stripe_size;
3797                 if (lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT) {
3798                         if (lsa.lsa_stripe_count == LLAPI_LAYOUT_WIDE)
3799                                 param->lsp_stripe_count = -1;
3800                         else
3801                                 param->lsp_stripe_count = lsa.lsa_stripe_count;
3802                 }
3803                 if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
3804                         param->lsp_stripe_offset = -1;
3805                 else
3806                         param->lsp_stripe_offset = lsa.lsa_stripe_off;
3807                 param->lsp_stripe_pattern =
3808                                 llapi_pattern_to_lov(lsa.lsa_pattern);
3809                 if (param->lsp_stripe_pattern == EINVAL) {
3810                         fprintf(stderr, "error: %s: invalid stripe pattern\n",
3811                                 argv[0]);
3812                         free(param);
3813                         goto usage_error;
3814                 }
3815                 param->lsp_pool = lsa.lsa_pool_name;
3816                 param->lsp_is_specific = false;
3817                 if (lsa.lsa_nr_tgts > 0) {
3818                         if (lsa.lsa_stripe_count > 0 &&
3819                             lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT &&
3820                             lsa.lsa_stripe_count != LLAPI_LAYOUT_WIDE &&
3821                             lsa.lsa_nr_tgts != lsa.lsa_stripe_count) {
3822                                 fprintf(stderr,
3823                                         "error: %s: stripe count %lld doesn't match the number of OSTs: %d\n",
3824                                         argv[0],
3825                                         (long long)lsa.lsa_stripe_count,
3826                                         lsa.lsa_nr_tgts);
3827                                 free(param);
3828                                 goto usage_error;
3829                         }
3830
3831                         param->lsp_is_specific = true;
3832                         param->lsp_stripe_count = lsa.lsa_nr_tgts;
3833                         memcpy(param->lsp_osts, tgts,
3834                                sizeof(*tgts) * lsa.lsa_nr_tgts);
3835                 }
3836         }
3837
3838         if (from_yaml) {
3839                 /* generate a layout from a YAML template */
3840                 result = lfs_comp_create_from_yaml(template, &layout,
3841                                                    &lsa, tgts);
3842                 if (result) {
3843                         fprintf(stderr, "error: %s: can't create composite "
3844                                 "layout from template file %s\n",
3845                                 argv[0], template);
3846                         goto error;
3847                 }
3848         } else if (from_copy) {
3849                 layout = llapi_layout_get_by_path(template, 0);
3850                 if (layout == NULL) {
3851                         fprintf(stderr,
3852                             "%s: can't create composite layout from file %s.\n",
3853                                 progname, template);
3854                         goto error;
3855                 }
3856         }
3857
3858         for (fname = argv[optind]; fname != NULL; fname = argv[++optind]) {
3859                 if (migrate_mdt_mode) {
3860                         result = llapi_migrate_mdt(fname, &migrate_mdt_param);
3861                 } else if (migrate_mode) {
3862                         result = lfs_migrate(fname, migration_flags, param,
3863                                              layout);
3864                 } else if (comp_set != 0) {
3865                         result = lfs_component_set(fname, comp_id,
3866                                                    lsa.lsa_comp_flags,
3867                                                    lsa.lsa_comp_neg_flags);
3868                 } else if (comp_del != 0) {
3869                         result = lfs_component_del(fname, comp_id,
3870                                                    lsa.lsa_comp_flags,
3871                                                    lsa.lsa_comp_neg_flags);
3872                 } else if (comp_add != 0) {
3873                         result = lfs_component_add(fname, layout);
3874                 } else if (opc == SO_MIRROR_CREATE) {
3875                         result = mirror_create(fname, mirror_list);
3876                 } else if (opc == SO_MIRROR_EXTEND) {
3877                         result = mirror_extend(fname, mirror_list,
3878                                                mirror_flags);
3879                 } else if (opc == SO_MIRROR_SPLIT) {
3880                         if (!mirror_id && !comp_id && !lsa.lsa_pool_name) {
3881                                 fprintf(stderr,
3882                         "%s %s: no mirror id or component id or pool name"
3883                         " is specified\n", progname, argv[0]);
3884                                 goto usage_error;
3885                         }
3886                         if (lsa.lsa_pool_name)
3887                                 mirror_flags |= MF_COMP_POOL;
3888                         else if (mirror_id != 0)
3889                                 comp_id = mirror_id;
3890                         else
3891                                 mirror_flags |= MF_COMP_ID;
3892                         result = mirror_split(fname, comp_id, lsa.lsa_pool_name,
3893                                               mirror_flags,
3894                                               has_m_file ? mirror_list->m_file :
3895                                               NULL);
3896                 } else if (layout != NULL) {
3897                         result = lfs_component_create(fname, O_CREAT | O_WRONLY,
3898                                                       mode, layout);
3899                         if (result >= 0) {
3900                                 close(result);
3901                                 result = 0;
3902                         }
3903                 } else if (foreign_mode) {
3904                         result = llapi_file_create_foreign(fname, mode, type,
3905                                                            flags, xattr);
3906                         if (result >= 0) {
3907                                 close(result);
3908                                 result = 0;
3909                         }
3910                 } else {
3911                         result = llapi_file_open_param(fname,
3912                                                        O_CREAT | O_WRONLY,
3913                                                        mode, param);
3914                         if (result >= 0) {
3915                                 close(result);
3916                                 result = 0;
3917                         }
3918                 }
3919                 if (result) {
3920                         /* Save the first error encountered. */
3921                         if (result2 == 0)
3922                                 result2 = result;
3923                         continue;
3924                 }
3925         }
3926
3927         if (mode_opt != NULL)
3928                 umask(previous_umask);
3929
3930         free(param);
3931         free(migrate_mdt_param.fp_lmv_md);
3932         llapi_layout_free(layout);
3933         lfs_mirror_list_free(mirror_list);
3934         return result2;
3935 usage_error:
3936         result = CMD_HELP;
3937 error:
3938         llapi_layout_free(layout);
3939         lfs_mirror_list_free(mirror_list);
3940         return result;
3941 }
3942
3943 static int lfs_poollist(int argc, char **argv)
3944 {
3945         if (argc != 2)
3946                 return CMD_HELP;
3947
3948         return llapi_poollist(argv[1]);
3949 }
3950
3951 static time_t set_time(struct find_param *param, time_t *time, time_t *set,
3952                        char *str)
3953 {
3954         long long t = 0;
3955         int res = 0;
3956         char *endptr = "AD";
3957         char *timebuf;
3958
3959         if (str[0] == '+')
3960                 res = 1;
3961         else if (str[0] == '-')
3962                 res = -1;
3963
3964         if (res)
3965                 str++;
3966
3967         for (timebuf = str; *endptr && *(endptr + 1); timebuf = endptr + 1) {
3968                 long long val = strtoll(timebuf, &endptr, 0);
3969                 int unit = 1;
3970
3971                 switch (*endptr) {
3972                 case  'y':
3973                         unit *= 52; /* 52 weeks + 1 day below */
3974                 case  'w':      /* fallthrough */
3975                         unit *= 7;
3976                 case '\0': /* days are default unit if none used */
3977                 case  'd':      /* fallthrough */
3978                         unit = (unit + (*endptr == 'y')) * 24;
3979                 case  'h':      /* fallthrough */
3980                         unit *= 60;
3981                 case  'm':      /* fallthrough */
3982                         unit *= 60;
3983                 case  's':      /* fallthrough */
3984                         break;
3985                         /* don't need to multiply by 1 for seconds */
3986                 default:
3987                         fprintf(stderr,
3988                                 "%s find: bad time string '%s': %s\n",
3989                                 progname, timebuf, strerror(EINVAL));
3990                         return LONG_MAX;
3991                 }
3992
3993                 if (param->fp_time_margin == 0 ||
3994                     (*endptr && unit < param->fp_time_margin))
3995                         param->fp_time_margin = unit;
3996
3997                 t += val * unit;
3998         }
3999         if (*time < t) {
4000                 if (res != 0)
4001                         str--;
4002                 fprintf(stderr, "%s find: bad time '%s': too large\n",
4003                         progname, str);
4004                 return LONG_MAX;
4005         }
4006
4007         *set = *time - t;
4008
4009         return res;
4010 }
4011
4012 static int name2uid(unsigned int *id, const char *name)
4013 {
4014         struct passwd *passwd;
4015
4016         passwd = getpwnam(name);
4017         if (passwd == NULL)
4018                 return -ENOENT;
4019         *id = passwd->pw_uid;
4020
4021         return 0;
4022 }
4023
4024 static int name2gid(unsigned int *id, const char *name)
4025 {
4026         struct group *group;
4027
4028         group = getgrnam(name);
4029         if (group == NULL)
4030                 return -ENOENT;
4031         *id = group->gr_gid;
4032
4033         return 0;
4034 }
4035
4036 static inline int name2projid(unsigned int *id, const char *name)
4037 {
4038         return -ENOTSUP;
4039 }
4040
4041 static int uid2name(char **name, unsigned int id)
4042 {
4043         struct passwd *passwd;
4044
4045         passwd = getpwuid(id);
4046         if (passwd == NULL)
4047                 return -ENOENT;
4048         *name = passwd->pw_name;
4049
4050         return 0;
4051 }
4052
4053 static inline int gid2name(char **name, unsigned int id)
4054 {
4055         struct group *group;
4056
4057         group = getgrgid(id);
4058         if (group == NULL)
4059                 return -ENOENT;
4060         *name = group->gr_name;
4061
4062         return 0;
4063 }
4064
4065 static int name2layout(__u32 *layout, char *name)
4066 {
4067         char *ptr, *layout_name;
4068
4069         *layout = 0;
4070         for (ptr = name; ; ptr = NULL) {
4071                 layout_name = strtok(ptr, ",");
4072                 if (layout_name == NULL)
4073                         break;
4074                 if (strcmp(layout_name, "released") == 0)
4075                         *layout |= LOV_PATTERN_F_RELEASED;
4076                 else if (strcmp(layout_name, "raid0") == 0)
4077                         *layout |= LOV_PATTERN_RAID0;
4078                 else if (strcmp(layout_name, "mdt") == 0)
4079                         *layout |= LOV_PATTERN_MDT;
4080                 else if (strcmp(layout_name, "overstriping") == 0)
4081                         *layout |= LOV_PATTERN_OVERSTRIPING;
4082                 else
4083                         return -1;
4084         }
4085         return 0;
4086 }
4087
4088 static int lfs_find(int argc, char **argv)
4089 {
4090         int c, rc;
4091         int ret = 0;
4092         time_t t;
4093         struct find_param param = {
4094                 .fp_max_depth = -1,
4095                 .fp_quiet = 1,
4096                 .fp_time_margin = 24 * 60 * 60,
4097         };
4098         struct option long_opts[] = {
4099         { .val = 'A',   .name = "atime",        .has_arg = required_argument },
4100         { .val = 'b',   .name = "blocks",       .has_arg = required_argument },
4101         { .val = LFS_COMP_COUNT_OPT,
4102                         .name = "comp-count",   .has_arg = required_argument },
4103         { .val = LFS_COMP_COUNT_OPT,
4104                         .name = "component-count",
4105                                                 .has_arg = required_argument },
4106         { .val = LFS_COMP_FLAGS_OPT,
4107                         .name = "comp-flags",   .has_arg = required_argument },
4108         { .val = LFS_COMP_FLAGS_OPT,
4109                         .name = "component-flags",
4110                                                 .has_arg = required_argument },
4111         { .val = LFS_COMP_START_OPT,
4112                         .name = "comp-start",   .has_arg = required_argument },
4113         { .val = LFS_COMP_START_OPT,
4114                         .name = "component-start",
4115                                                 .has_arg = required_argument },
4116         { .val = LFS_MIRROR_STATE_OPT,
4117                         .name = "mirror-state", .has_arg = required_argument },
4118         { .val = LFS_LAYOUT_FOREIGN_OPT,
4119                         .name = "foreign",      .has_arg = optional_argument},
4120         { .val = 'c',   .name = "stripe-count", .has_arg = required_argument },
4121         { .val = 'c',   .name = "stripe_count", .has_arg = required_argument },
4122         { .val = 'C',   .name = "ctime",        .has_arg = required_argument },
4123 /* getstripe { .val = 'd', .name = "directory", .has_arg = no_argument }, */
4124         { .val = 'D',   .name = "maxdepth",     .has_arg = required_argument },
4125         { .val = 'E',   .name = "comp-end",     .has_arg = required_argument },
4126         { .val = 'E',   .name = "component-end",
4127                                                 .has_arg = required_argument },
4128 /* find { .val = 'F',   .name = "fid",          .has_arg = no_argument }, */
4129         { .val = LFS_LAYOUT_FOREIGN_OPT,
4130                         .name = "foreign",      .has_arg = optional_argument},
4131         { .val = 'g',   .name = "gid",          .has_arg = required_argument },
4132         { .val = 'G',   .name = "group",        .has_arg = required_argument },
4133         { .val = 'H',   .name = "mdt-hash",     .has_arg = required_argument },
4134         { .val = 'i',   .name = "stripe-index", .has_arg = required_argument },
4135         { .val = 'i',   .name = "stripe_index", .has_arg = required_argument },
4136 /* getstripe { .val = 'I', .name = "comp-id",   .has_arg = required_argument }*/
4137         { .val = 'l',   .name = "lazy",         .has_arg = no_argument },
4138         { .val = 'L',   .name = "layout",       .has_arg = required_argument },
4139         { .val = 'm',   .name = "mdt",          .has_arg = required_argument },
4140         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument },
4141         { .val = 'm',   .name = "mdt_index",    .has_arg = required_argument },
4142         { .val = 'M',   .name = "mtime",        .has_arg = required_argument },
4143         { .val = 'n',   .name = "name",         .has_arg = required_argument },
4144         { .val = 'N',   .name = "mirror-count", .has_arg = required_argument },
4145 /* find { .val = 'o'    .name = "or", .has_arg = no_argument }, like find(1) */
4146         { .val = 'O',   .name = "obd",          .has_arg = required_argument },
4147         { .val = 'O',   .name = "ost",          .has_arg = required_argument },
4148         /* no short option for pool yet, can be 'p' after 2.18 */
4149         { .val = LFS_POOL_OPT,
4150                         .name = "pool",         .has_arg = required_argument },
4151         { .val = '0',   .name = "print0",       .has_arg = no_argument },
4152         { .val = 'P',   .name = "print",        .has_arg = no_argument },
4153         { .val = LFS_PROJID_OPT,
4154                         .name = "projid",       .has_arg = required_argument },
4155 /* getstripe { .val = 'q', .name = "quiet",     .has_arg = no_argument }, */
4156 /* getstripe { .val = 'r', .name = "recursive", .has_arg = no_argument }, */
4157 /* getstripe { .val = 'R', .name = "raw",       .has_arg = no_argument }, */
4158         { .val = 's',   .name = "size",         .has_arg = required_argument },
4159         { .val = 'S',   .name = "stripe-size",  .has_arg = required_argument },
4160         { .val = 'S',   .name = "stripe_size",  .has_arg = required_argument },
4161         { .val = 't',   .name = "type",         .has_arg = required_argument },
4162         { .val = 'T',   .name = "mdt-count",    .has_arg = required_argument },
4163         { .val = 'u',   .name = "uid",          .has_arg = required_argument },
4164         { .val = 'U',   .name = "user",         .has_arg = required_argument },
4165         { .val = 'z',   .name = "extension-size",
4166                                                 .has_arg = required_argument },
4167         { .val = 'z',   .name = "ext-size",     .has_arg = required_argument },
4168 /* getstripe { .val = 'v', .name = "verbose",   .has_arg = no_argument }, */
4169 /* getstripe { .val = 'y', .name = "yaml",      .has_arg = no_argument }, */
4170         { .name = NULL } };
4171         int pathstart = -1;
4172         int pathend = -1;
4173         int pathbad = -1;
4174         int neg_opt = 0;
4175         time_t *xtime;
4176         int *xsign;
4177         int isoption;
4178         char *endptr;
4179
4180         time(&t);
4181
4182         /* when getopt_long_only() hits '!' it returns 1, puts "!" in optarg */
4183         while ((c = getopt_long_only(argc, argv,
4184                         "-0A:b:c:C:D:E:g:G:H:i:L:m:M:n:N:O:Ppqrs:S:t:T:u:U:vz:",
4185                         long_opts, NULL)) >= 0) {
4186                 xtime = NULL;
4187                 xsign = NULL;
4188                 if (neg_opt)
4189                         --neg_opt;
4190                 /* '!' is part of option */
4191                 /* when getopt_long_only() finds a string which is not
4192                  * an option nor a known option argument it returns 1
4193                  * in that case if we already have found pathstart and pathend
4194                  * (i.e. we have the list of pathnames),
4195                  * the only supported value is "!"
4196                  */
4197                 isoption = (c != 1) || (strcmp(optarg, "!") == 0);
4198                 if (!isoption && pathend != -1) {
4199                         fprintf(stderr, "err: %s: filename|dirname must either "
4200                                         "precede options or follow options\n",
4201                                         argv[0]);
4202                         ret = CMD_HELP;
4203                         goto err;
4204                 }
4205                 if (!isoption && pathstart == -1)
4206                         pathstart = optind - 1;
4207                 if (isoption && pathstart != -1 && pathend == -1)
4208                         pathend = optind - 2;
4209                 switch (c) {
4210                 case 0:
4211                         /* Long options. */
4212                         break;
4213                 case 1:
4214                         /* unknown; opt is "!" or path component,
4215                          * checking done above.
4216                          */
4217                         if (strcmp(optarg, "!") == 0)
4218                                 neg_opt = 2;
4219                         break;
4220                 case 'A':
4221                         xtime = &param.fp_atime;
4222                         xsign = &param.fp_asign;
4223                         param.fp_exclude_atime = !!neg_opt;
4224                         /* no break, this falls through to 'C' for ctime */
4225                 case 'C':
4226                         if (c == 'C') {
4227                                 xtime = &param.fp_ctime;
4228                                 xsign = &param.fp_csign;
4229                                 param.fp_exclude_ctime = !!neg_opt;
4230                         }
4231                         /* no break, this falls through to 'M' for mtime */
4232                 case 'M':
4233                         if (c == 'M') {
4234                                 xtime = &param.fp_mtime;
4235                                 xsign = &param.fp_msign;
4236                                 param.fp_exclude_mtime = !!neg_opt;
4237                         }
4238                         rc = set_time(&param, &t, xtime, optarg);
4239                         if (rc == LONG_MAX) {
4240                                 ret = -1;
4241                                 goto err;
4242                         }
4243                         if (rc)
4244                                 *xsign = rc;
4245                         break;
4246                 case 'b':
4247                         if (optarg[0] == '+') {
4248                                 param.fp_blocks_sign = -1;
4249                                 optarg++;
4250                         } else if (optarg[0] == '-') {
4251                                 param.fp_blocks_sign =  1;
4252                                 optarg++;
4253                         }
4254
4255                         param.fp_blocks_units = 1024;
4256                         ret = llapi_parse_size(optarg, &param.fp_blocks,
4257                                                &param.fp_blocks_units, 0);
4258                         if (ret) {
4259                                 fprintf(stderr, "error: bad blocks '%s'\n",
4260                                         optarg);
4261                                 goto err;
4262                         }
4263                         param.fp_check_blocks = 1;
4264                         param.fp_exclude_blocks = !!neg_opt;
4265                         break;
4266                 case LFS_COMP_COUNT_OPT:
4267                         if (optarg[0] == '+') {
4268                                 param.fp_comp_count_sign = -1;
4269                                 optarg++;
4270                         } else if (optarg[0] == '-') {
4271                                 param.fp_comp_count_sign =  1;
4272                                 optarg++;
4273                         }
4274
4275                         param.fp_comp_count = strtoul(optarg, &endptr, 0);
4276                         if (*endptr != '\0') {
4277                                 fprintf(stderr, "error: bad component count "
4278                                         "'%s'\n", optarg);
4279                                 goto err;
4280                         }
4281                         param.fp_check_comp_count = 1;
4282                         param.fp_exclude_comp_count = !!neg_opt;
4283                         break;
4284                 case LFS_COMP_FLAGS_OPT:
4285                         rc = comp_str2flags(optarg, &param.fp_comp_flags,
4286                                             &param.fp_comp_neg_flags);
4287                         if (rc) {
4288                                 fprintf(stderr, "error: bad component flags "
4289                                         "'%s'\n", optarg);
4290                                 goto err;
4291                         }
4292                         param.fp_check_comp_flags = 1;
4293                         if (neg_opt) {
4294                                 __u32 flags = param.fp_comp_neg_flags;
4295                                 param.fp_comp_neg_flags = param.fp_comp_flags;
4296                                 param.fp_comp_flags = flags;
4297                         }
4298                         break;
4299                 case LFS_COMP_START_OPT:
4300                         if (optarg[0] == '+') {
4301                                 param.fp_comp_start_sign = -1;
4302                                 optarg++;
4303                         } else if (optarg[0] == '-') {
4304                                 param.fp_comp_start_sign =  1;
4305                                 optarg++;
4306                         }
4307
4308                         rc = llapi_parse_size(optarg, &param.fp_comp_start,
4309                                               &param.fp_comp_start_units, 0);
4310                         if (rc) {
4311                                 fprintf(stderr, "error: bad component start "
4312                                         "'%s'\n", optarg);
4313                                 goto err;
4314                         }
4315                         param.fp_check_comp_start = 1;
4316                         param.fp_exclude_comp_start = !!neg_opt;
4317                         break;
4318                 case LFS_MIRROR_STATE_OPT:
4319                         rc = mirror_str2state(optarg, &param.fp_mirror_state,
4320                                               &param.fp_mirror_neg_state);
4321                         if (rc) {
4322                                 fprintf(stderr,
4323                                         "error: bad mirrored file state '%s'\n",
4324                                         optarg);
4325                                 goto err;
4326                         }
4327                         param.fp_check_mirror_state = 1;
4328                         if (neg_opt) {
4329                                 __u16 state = param.fp_mirror_neg_state;
4330                                 param.fp_mirror_neg_state =
4331                                         param.fp_mirror_state;
4332                                 param.fp_mirror_state = state;
4333                         }
4334                         break;
4335                 case 'c':
4336                         if (optarg[0] == '+') {
4337                                 param.fp_stripe_count_sign = -1;
4338                                 optarg++;
4339                         } else if (optarg[0] == '-') {
4340                                 param.fp_stripe_count_sign =  1;
4341                                 optarg++;
4342                         }
4343
4344                         param.fp_stripe_count = strtoul(optarg, &endptr, 0);
4345                         if (*endptr != '\0') {
4346                                 fprintf(stderr,"error: bad stripe_count '%s'\n",
4347                                         optarg);
4348                                 ret = -1;
4349                                 goto err;
4350                         }
4351                         param.fp_check_stripe_count = 1;
4352                         param.fp_exclude_stripe_count = !!neg_opt;
4353                         break;
4354                 case 'D':
4355                         param.fp_max_depth = strtol(optarg, 0, 0);
4356                         break;
4357                 case 'E':
4358                         if (optarg[0] == '+') {
4359                                 param.fp_comp_end_sign = -1;
4360                                 optarg++;
4361                         } else if (optarg[0] == '-') {
4362                                 param.fp_comp_end_sign =  1;
4363                                 optarg++;
4364                         }
4365
4366                         if (arg_is_eof(optarg)) {
4367                                 param.fp_comp_end = LUSTRE_EOF;
4368                                 param.fp_comp_end_units = 1;
4369                                 rc = 0;
4370                         } else {
4371                                 rc = llapi_parse_size(optarg,
4372                                                 &param.fp_comp_end,
4373                                                 &param.fp_comp_end_units, 0);
4374                         }
4375                         if (rc) {
4376                                 fprintf(stderr, "error: bad component end "
4377                                         "'%s'\n", optarg);
4378                                 goto err;
4379                         }
4380                         param.fp_check_comp_end = 1;
4381                         param.fp_exclude_comp_end = !!neg_opt;
4382                         break;
4383                 case LFS_LAYOUT_FOREIGN_OPT: {
4384                         /* all types by default */
4385                         uint32_t type = LU_FOREIGN_TYPE_UNKNOWN;
4386
4387                         if (optarg != NULL) {
4388                                 /* check pure numeric */
4389                                 type = strtoul(optarg, &endptr, 0);
4390                                 if (*endptr) {
4391                                         /* check name */
4392                                         type = check_foreign_type_name(optarg);
4393                                         if (type == LU_FOREIGN_TYPE_UNKNOWN) {
4394                                                 fprintf(stderr,
4395                                                         "%s %s: unknown foreign type '%s'\n",
4396                                                         progname, argv[0],
4397                                                         optarg);
4398                                                 return CMD_HELP;
4399                                         }
4400                                 }
4401                         }
4402                         param.fp_foreign_type = type;
4403                         param.fp_check_foreign = 1;
4404                         param.fp_exclude_foreign = !!neg_opt;
4405                         break;
4406                 }
4407                 case 'g':
4408                 case 'G':
4409                         rc = name2gid(&param.fp_gid, optarg);
4410                         if (rc) {
4411                                 param.fp_gid = strtoul(optarg, &endptr, 10);
4412                                 if (*endptr != '\0') {
4413                                         fprintf(stderr, "Group/GID: %s cannot "
4414                                                 "be found.\n", optarg);
4415                                         ret = -1;
4416                                         goto err;
4417                                 }
4418                         }
4419                         param.fp_exclude_gid = !!neg_opt;
4420                         param.fp_check_gid = 1;
4421                         break;
4422                 case 'H':
4423                         param.fp_hash_type = check_hashtype(optarg);
4424                         if (param.fp_hash_type == 0) {
4425                                 fprintf(stderr, "error: bad hash_type '%s'\n",
4426                                         optarg);
4427                                 ret = -1;
4428                                 goto err;
4429                         }
4430                         param.fp_check_hash_type = 1;
4431                         param.fp_exclude_hash_type = !!neg_opt;
4432                         break;
4433                 case 'l':
4434                         param.fp_lazy = 1;
4435                         break;
4436                 case 'L':
4437                         ret = name2layout(&param.fp_layout, optarg);
4438                         if (ret)
4439                                 goto err;
4440                         param.fp_exclude_layout = !!neg_opt;
4441                         param.fp_check_layout = 1;
4442                         break;
4443                 case 'u':
4444                 case 'U':
4445                         rc = name2uid(&param.fp_uid, optarg);
4446                         if (rc) {
4447                                 param.fp_uid = strtoul(optarg, &endptr, 10);
4448                                 if (*endptr != '\0') {
4449                                         fprintf(stderr, "User/UID: %s cannot "
4450                                                 "be found.\n", optarg);
4451                                         ret = -1;
4452                                         goto err;
4453                                 }
4454                         }
4455                         param.fp_exclude_uid = !!neg_opt;
4456                         param.fp_check_uid = 1;
4457                         break;
4458                 case 'n':
4459                         param.fp_pattern = (char *)optarg;
4460                         param.fp_exclude_pattern = !!neg_opt;
4461                         break;
4462                 case 'N':
4463                         if (optarg[0] == '+') {
4464                                 param.fp_mirror_count_sign = -1;
4465                                 optarg++;
4466                         } else if (optarg[0] == '-') {
4467                                 param.fp_mirror_count_sign =  1;
4468                                 optarg++;
4469                         }
4470
4471                         param.fp_mirror_count = strtoul(optarg, &endptr, 0);
4472                         if (*endptr != '\0') {
4473                                 fprintf(stderr,
4474                                         "error: bad mirror count '%s'\n",
4475                                         optarg);
4476                                 goto err;
4477                         }
4478                         param.fp_check_mirror_count = 1;
4479                         param.fp_exclude_mirror_count = !!neg_opt;
4480                         break;
4481                 case 'm':
4482                 case 'i':
4483                 case 'O': {
4484                         char *buf, *token, *next, *p;
4485                         int len = 1;
4486                         void *tmp;
4487
4488                         buf = strdup(optarg);
4489                         if (buf == NULL) {
4490                                 ret = -ENOMEM;
4491                                 goto err;
4492                         }
4493
4494                         param.fp_exclude_obd = !!neg_opt;
4495
4496                         token = buf;
4497                         while (token && *token) {
4498                                 token = strchr(token, ',');
4499                                 if (token) {
4500                                         len++;
4501                                         token++;
4502                                 }
4503                         }
4504                         if (c == 'm') {
4505                                 param.fp_exclude_mdt = !!neg_opt;
4506                                 param.fp_num_alloc_mdts += len;
4507                                 tmp = realloc(param.fp_mdt_uuid,
4508                                               param.fp_num_alloc_mdts *
4509                                               sizeof(*param.fp_mdt_uuid));
4510                                 if (tmp == NULL) {
4511                                         ret = -ENOMEM;
4512                                         goto err_free;
4513                                 }
4514
4515                                 param.fp_mdt_uuid = tmp;
4516                         } else {
4517                                 param.fp_exclude_obd = !!neg_opt;
4518                                 param.fp_num_alloc_obds += len;
4519                                 tmp = realloc(param.fp_obd_uuid,
4520                                               param.fp_num_alloc_obds *
4521                                               sizeof(*param.fp_obd_uuid));
4522                                 if (tmp == NULL) {
4523                                         ret = -ENOMEM;
4524                                         goto err_free;
4525                                 }
4526
4527                                 param.fp_obd_uuid = tmp;
4528                         }
4529                         for (token = buf; token && *token; token = next) {
4530                                 struct obd_uuid *puuid;
4531                                 if (c == 'm') {
4532                                         puuid =
4533                                         &param.fp_mdt_uuid[param.fp_num_mdts++];
4534                                 } else {
4535                                         puuid =
4536                                         &param.fp_obd_uuid[param.fp_num_obds++];
4537                                 }
4538                                 p = strchr(token, ',');
4539                                 next = 0;
4540                                 if (p) {
4541                                         *p = 0;
4542                                         next = p+1;
4543                                 }
4544
4545                                 if (strlen(token) > sizeof(puuid->uuid) - 1) {
4546                                         ret = -E2BIG;
4547                                         goto err_free;
4548                                 }
4549
4550                                 strncpy(puuid->uuid, token,
4551                                         sizeof(puuid->uuid));
4552                         }
4553 err_free:
4554                         if (buf)
4555                                 free(buf);
4556                         break;
4557                 }
4558 #if LUSTRE_VERSION_CODE >= OBD_OCD_VERSION(2, 18, 53, 0)
4559                 case 'p':
4560 #endif
4561                 case LFS_POOL_OPT:
4562                         if (strlen(optarg) > LOV_MAXPOOLNAME) {
4563                                 fprintf(stderr,
4564                                         "Pool name %s is too long (max %d)\n",
4565                                         optarg, LOV_MAXPOOLNAME);
4566                                 ret = -1;
4567                                 goto err;
4568                         }
4569                         /*
4570                          * We do check for empty pool because empty pool
4571                          * is used to find V1 LOV attributes
4572                          */
4573                         strncpy(param.fp_poolname, optarg, LOV_MAXPOOLNAME);
4574                         param.fp_poolname[LOV_MAXPOOLNAME] = '\0';
4575                         param.fp_exclude_pool = !!neg_opt;
4576                         param.fp_check_pool = 1;
4577                         break;
4578 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 14, 53, 0)
4579                 case 'p': /* want this for --pool, to match getstripe/find */
4580                         fprintf(stderr,
4581                                 "warning: -p deprecated, use --print0 or -0\n");
4582 #endif
4583                 case '0':
4584                         param.fp_zero_end = 1;
4585                         break;
4586                 case 'P': /* we always print, this option is a no-op */
4587                         break;
4588                 case LFS_PROJID_OPT:
4589                         rc = name2projid(&param.fp_projid, optarg);
4590                         if (rc) {
4591                                 param.fp_projid = strtoul(optarg, &endptr, 10);
4592                                 if (*endptr != '\0') {
4593                                         fprintf(stderr,
4594                                                 "Invalid project ID: %s",
4595                                                 optarg);
4596                                         ret = -1;
4597                                         goto err;
4598                                 }
4599                         }
4600                         param.fp_exclude_projid = !!neg_opt;
4601                         param.fp_check_projid = 1;
4602                         break;
4603                 case 's':
4604                         if (optarg[0] == '+') {
4605                                 param.fp_size_sign = -1;
4606                                 optarg++;
4607                         } else if (optarg[0] == '-') {
4608                                 param.fp_size_sign =  1;
4609                                 optarg++;
4610                         }
4611
4612                         ret = llapi_parse_size(optarg, &param.fp_size,
4613                                                &param.fp_size_units, 0);
4614                         if (ret) {
4615                                 fprintf(stderr, "error: bad file size '%s'\n",
4616                                         optarg);
4617                                 goto err;
4618                         }
4619                         param.fp_check_size = 1;
4620                         param.fp_exclude_size = !!neg_opt;
4621                         break;
4622                 case 'S':
4623                         if (optarg[0] == '+') {
4624                                 param.fp_stripe_size_sign = -1;
4625                                 optarg++;
4626                         } else if (optarg[0] == '-') {
4627                                 param.fp_stripe_size_sign =  1;
4628                                 optarg++;
4629                         }
4630
4631                         ret = llapi_parse_size(optarg, &param.fp_stripe_size,
4632                                                &param.fp_stripe_size_units, 0);
4633                         if (ret) {
4634                                 fprintf(stderr, "error: bad stripe_size '%s'\n",
4635                                         optarg);
4636                                 goto err;
4637                         }
4638                         param.fp_check_stripe_size = 1;
4639                         param.fp_exclude_stripe_size = !!neg_opt;
4640                         break;
4641                 case 't':
4642                         param.fp_exclude_type = !!neg_opt;
4643                         switch (optarg[0]) {
4644                         case 'b':
4645                                 param.fp_type = S_IFBLK;
4646                                 break;
4647                         case 'c':
4648                                 param.fp_type = S_IFCHR;
4649                                 break;
4650                         case 'd':
4651                                 param.fp_type = S_IFDIR;
4652                                 break;
4653                         case 'f':
4654                                 param.fp_type = S_IFREG;
4655                                 break;
4656                         case 'l':
4657                                 param.fp_type = S_IFLNK;
4658                                 break;
4659                         case 'p':
4660                                 param.fp_type = S_IFIFO;
4661                                 break;
4662                         case 's':
4663                                 param.fp_type = S_IFSOCK;
4664                                 break;
4665                         default:
4666                                 fprintf(stderr, "error: %s: bad type '%s'\n",
4667                                         argv[0], optarg);
4668                                 ret = CMD_HELP;
4669                                 goto err;
4670                         };
4671                         break;
4672                 case 'T':
4673                         if (optarg[0] == '+') {
4674                                 param.fp_mdt_count_sign = -1;
4675                                 optarg++;
4676                         } else if (optarg[0] == '-') {
4677                                 param.fp_mdt_count_sign =  1;
4678                                 optarg++;
4679                         }
4680
4681                         param.fp_mdt_count = strtoul(optarg, &endptr, 0);
4682                         if (*endptr != '\0') {
4683                                 fprintf(stderr, "error: bad mdt_count '%s'\n",
4684                                         optarg);
4685                                 ret = -1;
4686                                 goto err;
4687                         }
4688                         param.fp_check_mdt_count = 1;
4689                         param.fp_exclude_mdt_count = !!neg_opt;
4690                         break;
4691                 case 'z':
4692                         if (optarg[0] == '+') {
4693                                 param.fp_ext_size_sign = -1;
4694                                 optarg++;
4695                         } else if (optarg[0] == '-') {
4696                                 param.fp_ext_size_sign =  1;
4697                                 optarg++;
4698                         }
4699
4700                         ret = llapi_parse_size(optarg, &param.fp_ext_size,
4701                                                &param.fp_ext_size_units, 0);
4702                         if (ret) {
4703                                 fprintf(stderr, "error: bad ext-size '%s'\n",
4704                                         optarg);
4705                                 goto err;
4706                         }
4707                         param.fp_ext_size /= SEL_UNIT_SIZE;
4708                         param.fp_ext_size_units /= SEL_UNIT_SIZE;
4709                         param.fp_check_ext_size = 1;
4710                         param.fp_exclude_ext_size = !!neg_opt;
4711                         break;
4712                 default:
4713                         ret = CMD_HELP;
4714                         goto err;
4715                 };
4716         }
4717
4718         if (pathstart == -1) {
4719                 fprintf(stderr, "error: %s: no filename|pathname\n",
4720                         argv[0]);
4721                 ret = CMD_HELP;
4722                 goto err;
4723         } else if (pathend == -1) {
4724                 /* no options */
4725                 pathend = argc;
4726         }
4727
4728         do {
4729                 rc = llapi_find(argv[pathstart], &param);
4730                 if (rc && !ret) {
4731                         ret = rc;
4732                         pathbad = pathstart;
4733                 }
4734         } while (++pathstart < pathend);
4735
4736         if (ret)
4737                 fprintf(stderr, "%s: failed for '%s': %s\n",
4738                         progname, argv[pathbad], strerror(-rc));
4739
4740 err:
4741         if (param.fp_obd_uuid && param.fp_num_alloc_obds)
4742                 free(param.fp_obd_uuid);
4743
4744         if (param.fp_mdt_uuid && param.fp_num_alloc_mdts)
4745                 free(param.fp_mdt_uuid);
4746
4747         return ret;
4748 }
4749
4750 static int lfs_getstripe_internal(int argc, char **argv,
4751                                   struct find_param *param)
4752 {
4753         struct option long_opts[] = {
4754 /* find { .val = 'A',   .name = "atime",        .has_arg = required_argument }*/
4755 /* find { .val = 'b',   .name = "blocks",       .has_arg = required_argument }*/
4756         { .val = LFS_COMP_COUNT_OPT,
4757                         .name = "comp-count",   .has_arg = no_argument },
4758         { .val = LFS_COMP_COUNT_OPT,
4759                 .name = "component-count",      .has_arg = no_argument },
4760         { .val = LFS_COMP_FLAGS_OPT,
4761                         .name = "comp-flags",   .has_arg = optional_argument },
4762         { .val = LFS_COMP_FLAGS_OPT,
4763                 .name = "component-flags",      .has_arg = optional_argument },
4764         { .val = LFS_COMP_START_OPT,
4765                         .name = "comp-start",   .has_arg = optional_argument },
4766         { .val = LFS_COMP_START_OPT,
4767                 .name = "component-start",      .has_arg = optional_argument },
4768         { .val = LFS_MIRROR_INDEX_OPT,
4769                 .name = "mirror-index",         .has_arg = required_argument },
4770         { .val = LFS_MIRROR_ID_OPT,
4771                 .name = "mirror-id",            .has_arg = required_argument },
4772         { .val = 'c',   .name = "stripe-count", .has_arg = no_argument },
4773         { .val = 'c',   .name = "stripe_count", .has_arg = no_argument },
4774 /* find { .val = 'C',   .name = "ctime",        .has_arg = required_argument }*/
4775         { .val = 'd',   .name = "directory",    .has_arg = no_argument },
4776         { .val = 'D',   .name = "default",      .has_arg = no_argument },
4777         { .val = 'E',   .name = "comp-end",     .has_arg = optional_argument },
4778         { .val = 'E',   .name = "component-end", .has_arg = optional_argument },
4779         { .val = 'F',   .name = "fid",          .has_arg = no_argument },
4780         { .val = 'g',   .name = "generation",   .has_arg = no_argument },
4781 /* find { .val = 'G',   .name = "group",        .has_arg = required_argument }*/
4782 /* dirstripe { .val = 'H', .name = "mdt-hash",  .has_arg = required_argument }*/
4783         { .val = 'i',   .name = "stripe-index", .has_arg = no_argument },
4784         { .val = 'i',   .name = "stripe_index", .has_arg = no_argument },
4785         { .val = 'I',   .name = "comp-id",      .has_arg = optional_argument },
4786         { .val = 'I',   .name = "component-id", .has_arg = optional_argument },
4787 /* find { .val = 'l',   .name = "lazy",         .has_arg = no_argument }, */
4788         { .val = 'L',   .name = "layout",       .has_arg = no_argument },
4789         { .val = 'm',   .name = "mdt",          .has_arg = no_argument },
4790         { .val = 'm',   .name = "mdt-index",    .has_arg = no_argument },
4791         { .val = 'm',   .name = "mdt_index",    .has_arg = no_argument },
4792 /* find { .val = 'M',   .name = "mtime",        .has_arg = required_argument }*/
4793 /* find { .val = 'n',   .name = "name",         .has_arg = required_argument }*/
4794         { .val = 'N',   .name = "mirror-count", .has_arg = no_argument },
4795         { .val = 'O',   .name = "obd",          .has_arg = required_argument },
4796         { .val = 'O',   .name = "ost",          .has_arg = required_argument },
4797         { .val = 'p',   .name = "pool",         .has_arg = no_argument },
4798 /* find { .val = 'P',   .name = "print",        .has_arg = no_argument }, */
4799         { .val = 'q',   .name = "quiet",        .has_arg = no_argument },
4800         { .val = 'r',   .name = "recursive",    .has_arg = no_argument },
4801         { .val = 'R',   .name = "raw",          .has_arg = no_argument },
4802         { .val = 'S',   .name = "stripe-size",  .has_arg = no_argument },
4803         { .val = 'S',   .name = "stripe_size",  .has_arg = no_argument },
4804 /* find { .val = 't',   .name = "type",         .has_arg = required_argument }*/
4805 /* dirstripe { .val = 'T', .name = "mdt-count", .has_arg = required_argument }*/
4806 /* find { .val = 'u',   .name = "uid",          .has_arg = required_argument }*/
4807 /* find { .val = 'U',   .name = "user",         .has_arg = required_argument }*/
4808         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
4809         { .val = 'y',   .name = "yaml",         .has_arg = no_argument },
4810         { .val = 'z',   .name = "extension-size", .has_arg = no_argument },
4811         { .val = 'z',   .name = "ext-size",     .has_arg = no_argument },
4812         { .name = NULL } };
4813         int c, rc;
4814         int neg_opt = 0;
4815         int pathstart = -1, pathend = -1;
4816         int isoption;
4817         char *end, *tmp;
4818
4819         while ((c = getopt_long(argc, argv,
4820                         "-cdDE::FghiI::LmMNoO:pqrRsSvyz",
4821                         long_opts, NULL)) != -1) {
4822                 if (neg_opt)
4823                         --neg_opt;
4824
4825                 /* '!' is part of option */
4826                 isoption = (c != 1) || (strcmp(optarg, "!") == 0);
4827                 if (!isoption && pathend != -1) {
4828                         fprintf(stderr,
4829                                 "error: %s: filename|dirname must either precede options or follow options\n",
4830                                 argv[0]);
4831                         return CMD_HELP;
4832                 }
4833                 if (!isoption && pathstart == -1)
4834                         pathstart = optind - 1;
4835                 if (isoption && pathstart != -1 && pathend == -1)
4836                         pathend = optind - 2;
4837
4838                 switch (c) {
4839                 case 1:
4840                         /* unknown: opt is "!" */
4841                         if (strcmp(optarg, "!") == 0)
4842                                 neg_opt = 2;
4843                         break;
4844                 case 'c':
4845                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
4846                                 param->fp_verbose |= VERBOSE_COUNT;
4847                                 param->fp_max_depth = 0;
4848                         }
4849                         break;
4850                 case LFS_COMP_COUNT_OPT:
4851                         param->fp_verbose |= VERBOSE_COMP_COUNT;
4852                         param->fp_max_depth = 0;
4853                         break;
4854                 case LFS_COMP_FLAGS_OPT:
4855                         if (optarg != NULL) {
4856                                 rc = comp_str2flags(optarg,
4857                                                     &param->fp_comp_flags,
4858                                                     &param->fp_comp_neg_flags);
4859                                 if (rc != 0) {
4860                                         fprintf(stderr, "error: %s bad "
4861                                                 "component flags '%s'.\n",
4862                                                 argv[0], optarg);
4863                                         return CMD_HELP;
4864                                 }
4865                                 param->fp_check_comp_flags = 1;
4866                         } else {
4867                                 param->fp_verbose |= VERBOSE_COMP_FLAGS;
4868                                 param->fp_max_depth = 0;
4869                         }
4870                         break;
4871                 case LFS_COMP_START_OPT:
4872                         if (optarg != NULL) {
4873                                 tmp = optarg;
4874                                 if (tmp[0] == '+') {
4875                                         param->fp_comp_start_sign = -1;
4876                                         tmp++;
4877                                 } else if (tmp[0] == '-') {
4878                                         param->fp_comp_start_sign = 1;
4879                                         tmp++;
4880                                 }
4881                                 rc = llapi_parse_size(tmp,
4882                                                 &param->fp_comp_start,
4883                                                 &param->fp_comp_start_units, 0);
4884                                 if (rc != 0) {
4885                                         fprintf(stderr, "error: %s bad "
4886                                                 "component start '%s'.\n",
4887                                                 argv[0], tmp);
4888                                         return CMD_HELP;
4889                                 } else {
4890                                         param->fp_check_comp_start = 1;
4891                                 }
4892                         } else {
4893                                 param->fp_verbose |= VERBOSE_COMP_START;
4894                                 param->fp_max_depth = 0;
4895                         }
4896                         break;
4897                 case LFS_MIRROR_INDEX_OPT:
4898                         if (optarg[0] == '+') {
4899                                 param->fp_mirror_index_sign = -1;
4900                                 optarg++;
4901                         } else if (optarg[0] == '-') {
4902                                 param->fp_mirror_index_sign = 1;
4903                                 optarg++;
4904                         }
4905
4906                         param->fp_mirror_index = strtoul(optarg, &end, 0);
4907                         if (*end != '\0' || (param->fp_mirror_index == 0 &&
4908                             param->fp_mirror_index_sign == 0 && neg_opt == 0)) {
4909                                 fprintf(stderr,
4910                                         "%s %s: invalid mirror index '%s'\n",
4911                                         progname, argv[0], optarg);
4912                                 return CMD_HELP;
4913                         }
4914                         if (param->fp_mirror_id != 0) {
4915                                 fprintf(stderr,
4916                                         "%s %s: can't specify both mirror index and mirror ID\n",
4917                                         progname, argv[0]);
4918                                 return CMD_HELP;
4919                         }
4920                         param->fp_check_mirror_index = 1;
4921                         param->fp_exclude_mirror_index = !!neg_opt;
4922                         break;
4923                 case LFS_MIRROR_ID_OPT:
4924                         if (optarg[0] == '+') {
4925                                 param->fp_mirror_id_sign = -1;
4926                                 optarg++;
4927                         } else if (optarg[0] == '-') {
4928                                 param->fp_mirror_id_sign = 1;
4929                                 optarg++;
4930                         }
4931
4932                         param->fp_mirror_id = strtoul(optarg, &end, 0);
4933                         if (*end != '\0' || (param->fp_mirror_id == 0 &&
4934                             param->fp_mirror_id_sign == 0 && neg_opt == 0)) {
4935                                 fprintf(stderr,
4936                                         "%s %s: invalid mirror ID '%s'\n",
4937                                         progname, argv[0], optarg);
4938                                 return CMD_HELP;
4939                         }
4940                         if (param->fp_mirror_index != 0) {
4941                                 fprintf(stderr,
4942                                         "%s %s: can't specify both mirror index and mirror ID\n",
4943                                         progname, argv[0]);
4944                                 return CMD_HELP;
4945                         }
4946                         param->fp_check_mirror_id = 1;
4947                         param->fp_exclude_mirror_id = !!neg_opt;
4948                         break;
4949                 case 'd':
4950                         param->fp_max_depth = 0;
4951                         break;
4952                 case 'D':
4953                         param->fp_get_default_lmv = 1;
4954                         break;
4955                 case 'E':
4956                         if (optarg != NULL) {
4957                                 tmp = optarg;
4958                                 if (tmp[0] == '+') {
4959                                         param->fp_comp_end_sign = -1;
4960                                         tmp++;
4961                                 } else if (tmp[0] == '-') {
4962                                         param->fp_comp_end_sign = 1;
4963                                         tmp++;
4964                                 }
4965
4966                                 if (arg_is_eof(tmp)) {
4967                                         param->fp_comp_end = LUSTRE_EOF;
4968                                         param->fp_comp_end_units = 1;
4969                                         rc = 0;
4970                                 } else {
4971                                         rc = llapi_parse_size(tmp,
4972                                                 &param->fp_comp_end,
4973                                                 &param->fp_comp_end_units, 0);
4974                                 }
4975                                 if (rc != 0) {
4976                                         fprintf(stderr, "error: %s bad "
4977                                                 "component end '%s'.\n",
4978                                                 argv[0], tmp);
4979                                         return CMD_HELP;
4980                                 }
4981                                 param->fp_check_comp_end = 1;
4982                         } else {
4983                                 param->fp_verbose |= VERBOSE_COMP_END;
4984                                 param->fp_max_depth = 0;
4985                         }
4986                         break;
4987                 case 'F':
4988                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
4989                                 param->fp_verbose |= VERBOSE_DFID;
4990                                 param->fp_max_depth = 0;
4991                         }
4992                         break;
4993                 case 'g':
4994                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
4995                                 param->fp_verbose |= VERBOSE_GENERATION;
4996                                 param->fp_max_depth = 0;
4997                         }
4998                         break;
4999                 case 'i':
5000                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
5001                                 param->fp_verbose |= VERBOSE_STRIPE_OFFSET;
5002                                 param->fp_max_depth = 0;
5003                         }
5004                         break;
5005                 case 'I':
5006                         if (optarg != NULL) {
5007                                 param->fp_comp_id = strtoul(optarg, &end, 0);
5008                                 if (*end != '\0' || param->fp_comp_id == 0 ||
5009                                     param->fp_comp_id > LCME_ID_MAX) {
5010                                         fprintf(stderr, "error: %s bad "
5011                                                 "component id '%s'\n",
5012                                                 argv[0], optarg);
5013                                         return CMD_HELP;
5014                                 } else {
5015                                         param->fp_check_comp_id = 1;
5016                                 }
5017                         } else {
5018                                 param->fp_max_depth = 0;
5019                                 param->fp_verbose |= VERBOSE_COMP_ID;
5020                         }
5021                         break;
5022                 case 'L':
5023                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
5024                                 param->fp_verbose |= VERBOSE_PATTERN;
5025                                 param->fp_max_depth = 0;
5026                         }
5027                         break;
5028 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
5029                 case 'M':
5030                         fprintf(stderr, "warning: '-M' deprecated"
5031                                 ", use '--mdt-index' or '-m' instead\n");
5032 #endif
5033                 case 'm':
5034                         if (!(param->fp_verbose & VERBOSE_DETAIL))
5035                                 param->fp_max_depth = 0;
5036                         param->fp_verbose |= VERBOSE_MDTINDEX;
5037                         break;
5038                 case 'N':
5039                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
5040                                 param->fp_verbose |= VERBOSE_MIRROR_COUNT;
5041                                 param->fp_max_depth = 0;
5042                         }
5043                         break;
5044                 case 'O':
5045                         if (param->fp_obd_uuid) {
5046                                 fprintf(stderr,
5047                                         "error: %s: only one obduuid allowed",
5048                                         argv[0]);
5049                                 return CMD_HELP;
5050                         }
5051                         param->fp_obd_uuid = (struct obd_uuid *)optarg;
5052                         break;
5053                 case 'p':
5054                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
5055                                 param->fp_verbose |= VERBOSE_POOL;
5056                                 param->fp_max_depth = 0;
5057                         }
5058                         break;
5059                 case 'q':
5060                         param->fp_quiet++;
5061                         break;
5062                 case 'r':
5063                         param->fp_recursive = 1;
5064                         break;
5065                 case 'R':
5066                         param->fp_raw = 1;
5067                         break;
5068                 case 'S':
5069                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
5070                                 param->fp_verbose |= VERBOSE_STRIPE_SIZE;
5071                                 param->fp_max_depth = 0;
5072                         }
5073                         break;
5074                 case 'v':
5075                         param->fp_verbose = VERBOSE_DEFAULT | VERBOSE_DETAIL;
5076                         break;
5077                 case 'y':
5078                         param->fp_yaml = 1;
5079                         break;
5080                 case 'z':
5081                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
5082                                 param->fp_verbose |= VERBOSE_EXT_SIZE;
5083                                 param->fp_max_depth = 0;
5084                         }
5085                         break;
5086                 default:
5087                         return CMD_HELP;
5088                 }
5089         }
5090
5091         if (pathstart == -1) {
5092                 fprintf(stderr, "error: %s: no filename|pathname\n",
5093                                 argv[0]);
5094                 return CMD_HELP;
5095         } else if (pathend == -1) {
5096                 /* no options */
5097                 pathend = argc;
5098         }
5099
5100         if (pathend > argc)
5101                 return CMD_HELP;
5102
5103         if (param->fp_recursive)
5104                 param->fp_max_depth = -1;
5105         else if (param->fp_verbose & VERBOSE_DETAIL)
5106                 param->fp_max_depth = 1;
5107
5108         if (!param->fp_verbose)
5109                 param->fp_verbose = VERBOSE_DEFAULT;
5110         if (param->fp_quiet)
5111                 param->fp_verbose = VERBOSE_OBJID;
5112
5113         do {
5114                 rc = llapi_getstripe(argv[pathstart], param);
5115         } while (++pathstart < pathend && !rc);
5116
5117         if (rc)
5118                 fprintf(stderr, "error: %s failed for %s.\n",
5119                         argv[0], argv[optind - 1]);
5120         return rc;
5121 }
5122
5123 static int lfs_tgts(int argc, char **argv)
5124 {
5125         char mntdir[PATH_MAX] = {'\0'}, path[PATH_MAX] = {'\0'};
5126         struct find_param param;
5127         int index = 0, rc=0;
5128
5129         if (argc > 2)
5130                 return CMD_HELP;
5131
5132         if (argc == 2 && !realpath(argv[1], path)) {
5133                 rc = -errno;
5134                 fprintf(stderr, "error: invalid path '%s': %s\n",
5135                         argv[1], strerror(-rc));
5136                 return rc;
5137         }
5138
5139         while (!llapi_search_mounts(path, index++, mntdir, NULL)) {
5140                 /* Check if we have a mount point */
5141                 if (mntdir[0] == '\0')
5142                         continue;
5143
5144                 memset(&param, 0, sizeof(param));
5145                 if (!strcmp(argv[0], "mdts"))
5146                         param.fp_get_lmv = 1;
5147
5148                 rc = llapi_ostlist(mntdir, &param);
5149                 if (rc) {
5150                         fprintf(stderr, "error: %s: failed on %s\n",
5151                                 argv[0], mntdir);
5152                 }
5153                 if (path[0] != '\0')
5154                         break;
5155                 memset(mntdir, 0, PATH_MAX);
5156         }
5157
5158         return rc;
5159 }
5160
5161 static int lfs_getstripe(int argc, char **argv)
5162 {
5163         struct find_param param = { 0 };
5164
5165         param.fp_max_depth = 1;
5166         return lfs_getstripe_internal(argc, argv, &param);
5167 }
5168
5169 /* functions */
5170 static int lfs_getdirstripe(int argc, char **argv)
5171 {
5172         struct find_param param = { 0 };
5173         struct option long_opts[] = {
5174         { .val = 'c',   .name = "mdt-count",    .has_arg = no_argument },
5175         { .val = 'D',   .name = "default",      .has_arg = no_argument },
5176         { .val = 'H',   .name = "mdt-hash",     .has_arg = no_argument },
5177         { .val = 'i',   .name = "mdt-index",    .has_arg = no_argument },
5178         { .val = 'm',   .name = "mdt-index",    .has_arg = no_argument },
5179         { .val = 'O',   .name = "obd",          .has_arg = required_argument },
5180         { .val = 'r',   .name = "recursive",    .has_arg = no_argument },
5181         { .val = 'T',   .name = "mdt-count",    .has_arg = no_argument },
5182         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
5183         { .val = 'y',   .name = "yaml",         .has_arg = no_argument },
5184         { .name = NULL } };
5185         int c, rc;
5186
5187         param.fp_get_lmv = 1;
5188
5189         while ((c = getopt_long(argc, argv,
5190                                 "cDHimO:rtTvy", long_opts, NULL)) != -1)
5191         {
5192                 switch (c) {
5193                 case 'c':
5194                 case 'T':
5195                         param.fp_verbose |= VERBOSE_COUNT;
5196                         break;
5197                 case 'D':
5198                         param.fp_get_default_lmv = 1;
5199                         break;
5200                 case 'i':
5201                 case 'm':
5202                         param.fp_verbose |= VERBOSE_STRIPE_OFFSET;
5203                         break;
5204 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
5205                 case 't':
5206                         fprintf(stderr, "warning: '-t' deprecated, "
5207                                 "use '--mdt-hash' or '-H' instead\n");
5208 #endif
5209                 case 'H':
5210                         param.fp_verbose |= VERBOSE_HASH_TYPE;
5211                         break;
5212                 case 'O':
5213                         if (param.fp_obd_uuid) {
5214                                 fprintf(stderr,
5215                                         "error: %s: only one obduuid allowed",
5216                                         argv[0]);
5217                                 return CMD_HELP;
5218                         }
5219                         param.fp_obd_uuid = (struct obd_uuid *)optarg;
5220                         break;
5221                 case 'r':
5222                         param.fp_recursive = 1;
5223                         break;
5224                 case 'v':
5225                         param.fp_verbose |= VERBOSE_DETAIL;
5226                         break;
5227                 case 'y':
5228                         param.fp_yaml = 1;
5229                         break;
5230                 default:
5231                         fprintf(stderr, "%s %s: unrecognized option '%s'\n",
5232                                 progname, argv[0], argv[optind - 1]);
5233                         return CMD_HELP;
5234                 }
5235         }
5236
5237         if (optind >= argc)
5238                 return CMD_HELP;
5239
5240         if (param.fp_recursive)
5241                 param.fp_max_depth = -1;
5242
5243         if (!param.fp_verbose)
5244                 param.fp_verbose = VERBOSE_DEFAULT;
5245
5246         do {
5247                 rc = llapi_getstripe(argv[optind], &param);
5248         } while (++optind < argc && !rc);
5249
5250         if (rc)
5251                 fprintf(stderr, "error: %s failed for %s.\n",
5252                         argv[0], argv[optind - 1]);
5253         return rc;
5254 }
5255
5256 enum mntdf_flags {
5257         MNTDF_INODES    = 0x0001,
5258         MNTDF_COOKED    = 0x0002,
5259         MNTDF_LAZY      = 0x0004,
5260         MNTDF_VERBOSE   = 0x0008,
5261         MNTDF_SHOW      = 0x0010,
5262 };
5263
5264 #define COOK(value)                                             \
5265 ({                                                              \
5266         int radix = 0;                                          \
5267         while (value > 1024) {                                  \
5268                 value /= 1024;                                  \
5269                 radix++;                                        \
5270         }                                                       \
5271         radix;                                                  \
5272 })
5273 #define UUF     "%-20s"
5274 #define CSF     "%11s"
5275 #define CDF     "%11llu"
5276 #define HDF     "%8.1f%c"
5277 #define RSF     "%4s"
5278 #define RDF     "%3d%%"
5279
5280 static inline int obd_statfs_ratio(const struct obd_statfs *st, bool inodes)
5281 {
5282         double avail, used, ratio = 0;
5283
5284         if (inodes) {
5285                 avail = st->os_ffree;
5286                 used = st->os_files - st->os_ffree;
5287         } else {
5288                 avail = st->os_bavail;
5289                 used = st->os_blocks - st->os_bfree;
5290         }
5291         if (avail + used > 0)
5292                 ratio = used / (used + avail) * 100;
5293
5294         /* Round up to match df(1) usage percentage */
5295         return (ratio - (int)ratio) > 0 ? (int)(ratio + 1) : (int)ratio;
5296 }
5297
5298 /* This is to identify various problem states for "lfs df" if .osn_err = true,
5299  * so only show flags reflecting those states by default. Informational states
5300  * are only shown with "-v" and use lower-case names to distinguish them.
5301  * UNUSED[12] were for "EROFS = 30" until 1.6 but are now available for use.
5302  */
5303 static struct obd_statfs_state_names {
5304         enum obd_statfs_state   osn_state;
5305         const char              osn_name;
5306         bool                    osn_err;
5307 } oss_names[] = {
5308         { .osn_state = OS_STATE_DEGRADED,    .osn_name = 'D', .osn_err = true },
5309         { .osn_state = OS_STATE_READONLY,    .osn_name = 'R', .osn_err = true },
5310         { .osn_state = OS_STATE_NOPRECREATE, .osn_name = 'N', .osn_err = true },
5311         { .osn_state = OS_STATE_UNUSED1,     .osn_name = '?', .osn_err = true },
5312         { .osn_state = OS_STATE_UNUSED2,     .osn_name = '?', .osn_err = true },
5313         { .osn_state = OS_STATE_ENOSPC,      .osn_name = 'S', .osn_err = true },
5314         { .osn_state = OS_STATE_ENOINO,      .osn_name = 'I', .osn_err = true },
5315         { .osn_state = OS_STATE_SUM,         .osn_name = 'a', /* aggregate */ },
5316         { .osn_state = OS_STATE_NONROT,      .osn_name = 'f', /* flash */     },
5317 };
5318
5319 static int showdf(char *mntdir, struct obd_statfs *stat,
5320                   char *uuid, enum mntdf_flags flags,
5321                   char *type, int index, int rc)
5322 {
5323         long long avail, used, total;
5324         int ratio = 0;
5325         char *suffix = "KMGTPEZY";
5326         /* Note if we have >2^64 bytes/fs these buffers will need to be grown */
5327         char tbuf[3 * sizeof(__u64)];
5328         char ubuf[3 * sizeof(__u64)];
5329         char abuf[3 * sizeof(__u64)];
5330         char rbuf[3 * sizeof(__u64)];
5331
5332         if (!uuid || !stat)
5333                 return -EINVAL;
5334
5335         switch (rc) {
5336         case 0:
5337                 if (flags & MNTDF_INODES) {
5338                         avail = stat->os_ffree;
5339                         used = stat->os_files - stat->os_ffree;
5340                         total = stat->os_files;
5341                 } else {
5342                         int shift = flags & MNTDF_COOKED ? 0 : 10;
5343
5344                         avail = (stat->os_bavail * stat->os_bsize) >> shift;
5345                         used  = ((stat->os_blocks - stat->os_bfree) *
5346                                  stat->os_bsize) >> shift;
5347                         total = (stat->os_blocks * stat->os_bsize) >> shift;
5348                 }
5349
5350                 ratio = obd_statfs_ratio(stat, flags & MNTDF_INODES);
5351
5352                 if (flags & MNTDF_COOKED) {
5353                         int i;
5354                         double cook_val;
5355
5356                         cook_val = (double)total;
5357                         i = COOK(cook_val);
5358                         if (i > 0)
5359                                 snprintf(tbuf, sizeof(tbuf), HDF, cook_val,
5360                                          suffix[i - 1]);
5361                         else
5362                                 snprintf(tbuf, sizeof(tbuf), CDF, total);
5363
5364                         cook_val = (double)used;
5365                         i = COOK(cook_val);
5366                         if (i > 0)
5367                                 snprintf(ubuf, sizeof(ubuf), HDF, cook_val,
5368                                          suffix[i - 1]);
5369                         else
5370                                 snprintf(ubuf, sizeof(ubuf), CDF, used);
5371
5372                         cook_val = (double)avail;
5373                         i = COOK(cook_val);
5374                         if (i > 0)
5375                                 snprintf(abuf, sizeof(abuf), HDF, cook_val,
5376                                          suffix[i - 1]);
5377                         else
5378                                 snprintf(abuf, sizeof(abuf), CDF, avail);
5379                 } else {
5380                         snprintf(tbuf, sizeof(tbuf), CDF, total);
5381                         snprintf(ubuf, sizeof(tbuf), CDF, used);
5382                         snprintf(abuf, sizeof(tbuf), CDF, avail);
5383                 }
5384
5385                 sprintf(rbuf, RDF, ratio);
5386                 printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s",
5387                        uuid, tbuf, ubuf, abuf, rbuf, mntdir);
5388                 if (type)
5389                         printf("[%s:%d]", type, index);
5390
5391                 if (stat->os_state) {
5392                         uint32_t i;
5393
5394                         printf(" ");
5395                         for (i = 0; i < ARRAY_SIZE(oss_names); i++) {
5396                                 if (oss_names[i].osn_state & stat->os_state &&
5397                                     (oss_names[i].osn_err ||
5398                                      flags & MNTDF_VERBOSE))
5399                                         printf("%c", oss_names[i].osn_name);
5400                         }
5401                 }
5402
5403                 printf("\n");
5404                 break;
5405         case -ENODATA:
5406                 printf(UUF": inactive device\n", uuid);
5407                 break;
5408         default:
5409                 printf(UUF": %s\n", uuid, strerror(-rc));
5410                 break;
5411         }
5412
5413         return 0;
5414 }
5415
5416 struct ll_stat_type {
5417         int   st_op;
5418         char *st_name;
5419 };
5420
5421 #define LL_STATFS_MAX   LOV_MAX_STRIPE_COUNT
5422
5423 struct ll_statfs_data {
5424         int                     sd_index;
5425         struct obd_statfs       sd_st;
5426 };
5427
5428 struct ll_statfs_buf {
5429         int                     sb_count;
5430         struct ll_statfs_data   sb_buf[LL_STATFS_MAX];
5431 };
5432
5433 static int mntdf(char *mntdir, char *fsname, char *pool, enum mntdf_flags flags,
5434                  int ops, struct ll_statfs_buf *lsb)
5435 {
5436         struct obd_statfs stat_buf, sum = { .os_bsize = 1 };
5437         struct obd_uuid uuid_buf;
5438         char *poolname = NULL;
5439         struct ll_stat_type types[] = {
5440                 { .st_op = LL_STATFS_LMV,       .st_name = "MDT" },
5441                 { .st_op = LL_STATFS_LOV,       .st_name = "OST" },
5442                 { .st_name = NULL } };
5443         struct ll_stat_type *tp;
5444         __u64 ost_files = 0;
5445         __u64 ost_ffree = 0;
5446         __u32 index;
5447         __u32 type;
5448         int fd;
5449         int rc = 0;
5450         int rc2;
5451
5452         if (pool) {
5453                 poolname = strchr(pool, '.');
5454                 if (poolname != NULL) {
5455                         if (strncmp(fsname, pool, strlen(fsname))) {
5456                                 fprintf(stderr, "filesystem name incorrect\n");
5457                                 return -ENODEV;
5458                         }
5459                         poolname++;
5460                 } else
5461                         poolname = pool;
5462         }
5463
5464         fd = open(mntdir, O_RDONLY);
5465         if (fd < 0) {
5466                 rc = -errno;
5467                 fprintf(stderr, "%s: cannot open '%s': %s\n", progname, mntdir,
5468                         strerror(errno));
5469                 return rc;
5470         }
5471
5472         if (flags & MNTDF_SHOW) {
5473                 if (flags & MNTDF_INODES)
5474                         printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s\n",
5475                                "UUID", "Inodes", "IUsed", "IFree",
5476                                "IUse%", "Mounted on");
5477                 else
5478                         printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s\n",
5479                                "UUID",
5480                                flags & MNTDF_COOKED ? "bytes" : "1K-blocks",
5481                                "Used", "Available", "Use%", "Mounted on");
5482         }
5483
5484         for (tp = types; tp->st_name != NULL; tp++) {
5485                 bool have_ost = false;
5486
5487                 if (!(tp->st_op & ops))
5488                         continue;
5489
5490                 for (index = 0; ; index++) {
5491                         memset(&stat_buf, 0, sizeof(struct obd_statfs));
5492                         memset(&uuid_buf, 0, sizeof(struct obd_uuid));
5493                         type = flags & MNTDF_LAZY ?
5494                                 tp->st_op | LL_STATFS_NODELAY : tp->st_op;
5495                         rc2 = llapi_obd_fstatfs(fd, type, index,
5496                                                &stat_buf, &uuid_buf);
5497                         if (rc2 == -ENODEV)
5498                                 break;
5499                         if (rc2 == -EAGAIN)
5500                                 continue;
5501                         if (rc2 == -ENODATA) { /* Inactive device, OK. */
5502                                 if (!(flags & MNTDF_VERBOSE))
5503                                         continue;
5504                         } else if (rc2 < 0 && rc == 0) {
5505                                 rc = rc2;
5506                         }
5507
5508                         /* If we have OSTs then don't report MDT block counts.
5509                          * For MDT-only filesystems the expectation is that all
5510                          * layouts have a DoM component.  For filesystems with
5511                          * OSTs, files are not necessarily going to store data
5512                          * on MDTs, and MDT space is limited to a fraction of
5513                          * OST space, so don't include it in the summary.
5514                          */
5515                         if (tp->st_op == LL_STATFS_LOV && !have_ost) {
5516                                 have_ost = true;
5517                                 sum.os_blocks = 0;
5518                                 sum.os_bfree = 0;
5519                                 sum.os_bavail = 0;
5520                         }
5521
5522                         if (poolname && tp->st_op == LL_STATFS_LOV &&
5523                             llapi_search_ost(fsname, poolname,
5524                                              obd_uuid2str(&uuid_buf)) != 1)
5525                                 continue;
5526
5527                         /* the llapi_obd_statfs() call may have returned with
5528                          * an error, but if it filled in uuid_buf we will at
5529                          * lease use that to print out a message for that OBD.
5530                          * If we didn't get anything in the uuid_buf, then fill
5531                          * it in so that we can print an error message. */
5532                         if (uuid_buf.uuid[0] == '\0')
5533                                 snprintf(uuid_buf.uuid, sizeof(uuid_buf.uuid),
5534                                          "%s%04x", tp->st_name, index);
5535                         if (!rc && lsb) {
5536                                 lsb->sb_buf[lsb->sb_count].sd_index = index;
5537                                 lsb->sb_buf[lsb->sb_count].sd_st = stat_buf;
5538                                 lsb->sb_count++;
5539                         }
5540                         if (flags & MNTDF_SHOW)
5541                                 showdf(mntdir, &stat_buf,
5542                                        obd_uuid2str(&uuid_buf), flags,
5543                                        tp->st_name, index, rc2);
5544
5545                         if (rc2)
5546                                 continue;
5547
5548                         if (tp->st_op == LL_STATFS_LMV) {
5549                                 sum.os_ffree += stat_buf.os_ffree;
5550                                 sum.os_files += stat_buf.os_files;
5551                         } else /* if (tp->st_op == LL_STATFS_LOV) */ {
5552                                 ost_files += stat_buf.os_files;
5553                                 ost_ffree += stat_buf.os_ffree;
5554                         }
5555                         sum.os_blocks += stat_buf.os_blocks *
5556                                          stat_buf.os_bsize;
5557                         sum.os_bfree  += stat_buf.os_bfree *
5558                                          stat_buf.os_bsize;
5559                         sum.os_bavail += stat_buf.os_bavail *
5560                                          stat_buf.os_bsize;
5561                 }
5562         }
5563
5564         close(fd);
5565
5566         /* If we have _some_ OSTs, but don't have as many free objects on the
5567          * OST as inodes on the MDTs, reduce the reported number of inodes
5568          * to compensate, so that the "inodes in use" number is correct.
5569          * This should be kept in sync with ll_statfs_internal().
5570          */
5571         if (ost_files && ost_ffree < sum.os_ffree) {
5572                 sum.os_files = (sum.os_files - sum.os_ffree) + ost_ffree;
5573                 sum.os_ffree = ost_ffree;
5574         }
5575         if (flags & MNTDF_SHOW) {
5576                 printf("\n");
5577                 showdf(mntdir, &sum, "filesystem_summary:", flags, NULL, 0, 0);
5578                 printf("\n");
5579         }
5580
5581         return rc;
5582 }
5583
5584 static int ll_statfs_data_comp(const void *sd1, const void *sd2)
5585 {
5586         const struct obd_statfs *st1 = &((const struct ll_statfs_data *)sd1)->
5587                                                 sd_st;
5588         const struct obd_statfs *st2 = &((const struct ll_statfs_data *)sd2)->
5589                                                 sd_st;
5590         int r1 = obd_statfs_ratio(st1, false);
5591         int r2 = obd_statfs_ratio(st2, false);
5592         int64_t result = r1 - r2;
5593
5594         /* if both space usage are above 90, compare free inodes */
5595         if (r1 > 90 && r2 > 90)
5596                 result = st2->os_ffree - st1->os_ffree;
5597
5598         if (result < 0)
5599                 return -1;
5600         else if (result == 0)
5601                 return 0;
5602         else
5603                 return 1;
5604 }
5605
5606 /* functions */
5607 static int lfs_setdirstripe(int argc, char **argv)
5608 {
5609         char *dname;
5610         struct lfs_setstripe_args lsa = { 0 };
5611         struct llapi_stripe_param *param = NULL;
5612         __u32 mdts[LMV_MAX_STRIPE_COUNT] = { 0 };
5613         char *end;
5614         int c;
5615         char *mode_opt = NULL;
5616         bool default_stripe = false;
5617         bool delete = false;
5618         bool auto_distributed = false;
5619         bool foreign_mode = false;
5620         mode_t mode = S_IRWXU | S_IRWXG | S_IRWXO;
5621         mode_t previous_mode = 0;
5622         struct ll_statfs_buf *lsb = NULL;
5623         char mntdir[PATH_MAX] = "";
5624         char *xattr = NULL;
5625         __u32 type = LU_FOREIGN_TYPE_DAOS, flags = 0;
5626         struct option long_opts[] = {
5627         { .val = 'c',   .name = "count",        .has_arg = required_argument },
5628         { .val = 'c',   .name = "mdt-count",    .has_arg = required_argument },
5629         { .val = 'd',   .name = "delete",       .has_arg = no_argument },
5630         { .val = 'D',   .name = "default",      .has_arg = no_argument },
5631         { .val = 'D',   .name = "default_stripe", .has_arg = no_argument },
5632         { .val = LFS_LAYOUT_FLAGS_OPT,
5633                         .name = "flags",        .has_arg = required_argument },
5634         { .val = LFS_LAYOUT_FOREIGN_OPT,
5635                         .name = "foreign",      .has_arg = optional_argument},
5636         { .val = 'H',   .name = "mdt-hash",     .has_arg = required_argument },
5637 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 17, 53, 0)
5638         { .val = 'i',   .name = "mdt-index",    .has_arg = required_argument },
5639         { .val = 'i',   .name = "mdt",          .has_arg = required_argument },
5640 #else
5641 /* find { .val = 'l',   .name = "lazy",         .has_arg = no_argument }, */
5642         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument },
5643         { .val = 'm',   .name = "mdt",          .has_arg = required_argument },
5644 #endif
5645 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
5646         { .val = 'i',   .name = "index",        .has_arg = required_argument },
5647 #endif
5648         { .val = 'o',   .name = "mode",         .has_arg = required_argument },
5649 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
5650         { .val = 't',   .name = "hash-type",    .has_arg = required_argument },
5651 #endif
5652         { .val = 'T',   .name = "mdt-count",    .has_arg = required_argument },
5653 /* setstripe { .val = 'y', .name = "yaml",      .has_arg = no_argument }, */
5654         { .val = 'x',   .name = "xattr",        .has_arg = required_argument },
5655         { .name = NULL } };
5656         int result = 0;
5657
5658         setstripe_args_init(&lsa);
5659
5660         while ((c = getopt_long(argc, argv, "c:dDi:H:m:o:t:T:x:",
5661                                 long_opts, NULL)) >= 0) {
5662                 switch (c) {
5663                 case 0:
5664                         /* Long options. */
5665                         break;
5666                 case 'c':
5667                 case 'T':
5668                         lsa.lsa_stripe_count = strtoul(optarg, &end, 0);
5669                         if (*end != '\0') {
5670                                 fprintf(stderr,
5671                                         "%s %s: invalid stripe count '%s'\n",
5672                                         progname, argv[0], optarg);
5673                                 return CMD_HELP;
5674                         }
5675                         break;
5676                 case 'd':
5677                         delete = true;
5678                         default_stripe = true;
5679                         break;
5680                 case 'D':
5681                         default_stripe = true;
5682                         break;
5683                 case LFS_LAYOUT_FOREIGN_OPT:
5684                         if (optarg != NULL) {
5685                                 /* check pure numeric */
5686                                 type = strtoul(optarg, &end, 0);
5687                                 if (*end) {
5688                                         /* check name */
5689                                         type = check_foreign_type_name(optarg);
5690                                         if (type == LU_FOREIGN_TYPE_UNKNOWN) {
5691                                                 fprintf(stderr,
5692                                                         "%s %s: unknown foreign type '%s'\n",
5693                                                         progname, argv[0],
5694                                                         optarg);
5695                                                 return CMD_HELP;
5696                                         }
5697                                 }
5698                         }
5699                         foreign_mode = true;
5700                         break;
5701                 case LFS_LAYOUT_FLAGS_OPT:
5702                         flags = strtoul(optarg, &end, 16);
5703                         if (*end != '\0') {
5704                                 fprintf(stderr,
5705                                         "%s %s: bad flags '%s'\n",
5706                                         progname, argv[0], optarg);
5707                                 return CMD_HELP;
5708                         }
5709                         break;
5710 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
5711                 case 't':
5712                         fprintf(stderr, "warning: '--hash-type' and '-t' "
5713                               "deprecated, use '--mdt-hash' or '-H' instead\n");
5714 #endif
5715                 case 'H':
5716                         lsa.lsa_pattern = check_hashtype(optarg);
5717                         if (lsa.lsa_pattern == 0) {
5718                                 fprintf(stderr,
5719                                         "%s %s: bad stripe hash type '%s'\n",
5720                                         progname, argv[0], optarg);
5721                                 return CMD_HELP;
5722                         }
5723                         break;
5724                 case 'i':
5725 #if LUSTRE_VERSION_CODE >= OBD_OCD_VERSION(2, 17, 53, 0)
5726                 case 'm':
5727 #endif
5728 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
5729                         if (strcmp(argv[optind - 1], "--index") == 0)
5730                                 fprintf(stderr,
5731                                         "%s %s: warning: '--index' deprecated, use '--mdt-index' instead\n",
5732                                         progname, argv[0]);
5733 #endif
5734                         lsa.lsa_nr_tgts = parse_targets(mdts,
5735                                                 sizeof(mdts) / sizeof(__u32),
5736                                                 lsa.lsa_nr_tgts, optarg, NULL);
5737                         if (lsa.lsa_nr_tgts < 0) {
5738                                 fprintf(stderr,
5739                                         "%s %s: invalid MDT target(s) '%s'\n",
5740                                         progname, argv[0], optarg);
5741                                 return CMD_HELP;
5742                         }
5743
5744                         lsa.lsa_tgts = mdts;
5745                         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
5746                                 lsa.lsa_stripe_off = mdts[0];
5747                         break;
5748 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 15, 53, 0)
5749                 case 'm':
5750                         fprintf(stderr, "warning: '-m' is deprecated, "
5751                                 "use '--mode' or '-o' instead\n");
5752 #endif
5753                 case 'o':
5754                         mode_opt = optarg;
5755                         break;
5756                 case 'x':
5757                         xattr = optarg;
5758                         break;
5759                 default:
5760                         fprintf(stderr, "%s %s: unrecognized option '%s'\n",
5761                                 progname, argv[0], argv[optind - 1]);
5762                         return CMD_HELP;
5763                 }
5764         }
5765
5766         if (optind == argc) {
5767                 fprintf(stderr, "%s %s: DIR must be specified\n",
5768                         progname, argv[0]);
5769                 return CMD_HELP;
5770         }
5771
5772         if (xattr && !foreign_mode) {
5773                 /* only print a warning as this is armless and will be
5774                  * ignored
5775                  */
5776                 fprintf(stderr,
5777                         "%s %s: xattr has been specified for non-foreign layout\n",
5778                         progname, argv[0]);
5779         } else if (foreign_mode && !xattr) {
5780                 fprintf(stderr,
5781                         "%s %s: xattr must be provided in foreign mode\n",
5782                         progname, argv[0]);
5783                 return CMD_HELP;
5784         }
5785
5786         if (foreign_mode && (delete || default_stripe || lsa.lsa_nr_tgts ||
5787             lsa.lsa_tgts || setstripe_args_specified(&lsa))) {
5788                 fprintf(stderr,
5789                         "%s %s: only --xattr/--flags/--mode options are valid with --foreign\n",
5790                         progname, argv[0]);
5791                 return CMD_HELP;
5792         }
5793
5794         if (!delete && lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT &&
5795             lsa.lsa_stripe_count == LLAPI_LAYOUT_DEFAULT && !foreign_mode) {
5796                 fprintf(stderr,
5797                         "%s %s: stripe offset and count must be specified\n",
5798                         progname, argv[0]);
5799                 return CMD_HELP;
5800         }
5801
5802         if (delete &&
5803             (lsa.lsa_stripe_off != LLAPI_LAYOUT_DEFAULT ||
5804              lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT)) {
5805                 fprintf(stderr,
5806                         "%s %s: cannot specify -d with -c or -i options\n",
5807                         progname, argv[0]);
5808                 return CMD_HELP;
5809         }
5810
5811         if (mode_opt != NULL) {
5812                 mode = strtoul(mode_opt, &end, 8);
5813                 if (*end != '\0') {
5814                         fprintf(stderr,
5815                                 "%s %s: bad MODE '%s'\n",
5816                                 progname, argv[0], mode_opt);
5817                         return CMD_HELP;
5818                 }
5819                 previous_mode = umask(0);
5820         }
5821
5822         /* foreign LMV/dir case */
5823         if (foreign_mode) {
5824                 if (argc > optind + 1) {
5825                         fprintf(stderr,
5826                                 "%s %s: cannot specify multiple foreign dirs\n",
5827                                 progname, argv[0]);
5828                         return CMD_HELP;
5829                 }
5830
5831                 dname = argv[optind];
5832                 result = llapi_dir_create_foreign(dname, mode, type, flags,
5833                                                   xattr);
5834                 if (result != 0)
5835                         fprintf(stderr,
5836                                 "%s mkdir: can't create foreign dir '%s': %s\n",
5837                                 progname, dname, strerror(-result));
5838                 return result;
5839         }
5840
5841         /*
5842          * initialize stripe parameters, in case param is converted to specific,
5843          * i.e, 'lfs mkdir -i -1 -c N', always allocate space for lsp_tgts.
5844          */
5845         param = calloc(1, offsetof(typeof(*param),
5846                        lsp_tgts[lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT ?
5847                                 lsa.lsa_stripe_count : lsa.lsa_nr_tgts]));
5848         if (param == NULL) {
5849                 fprintf(stderr,
5850                         "%s %s: cannot allocate memory for parameters: %s\n",
5851                         progname, argv[0], strerror(ENOMEM));
5852                 return CMD_HELP;
5853         }
5854
5855         if (lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT)
5856                 param->lsp_stripe_count = lsa.lsa_stripe_count;
5857         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
5858                 param->lsp_stripe_offset = -1;
5859         else
5860                 param->lsp_stripe_offset = lsa.lsa_stripe_off;
5861         if (lsa.lsa_pattern != LLAPI_LAYOUT_RAID0)
5862                 param->lsp_stripe_pattern = lsa.lsa_pattern;
5863         else
5864                 param->lsp_stripe_pattern = LMV_HASH_TYPE_DEFAULT;
5865         param->lsp_pool = lsa.lsa_pool_name;
5866         param->lsp_is_specific = false;
5867         if (lsa.lsa_nr_tgts > 1) {
5868                 if (lsa.lsa_stripe_count > 0 &&
5869                     lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT &&
5870                     lsa.lsa_stripe_count != lsa.lsa_nr_tgts) {
5871                         fprintf(stderr,
5872                                 "error: %s: stripe count %lld doesn't match the number of MDTs: %d\n",
5873                                 argv[0], (long long)lsa.lsa_stripe_count,
5874                                 lsa.lsa_nr_tgts);
5875                         free(param);
5876                         return CMD_HELP;
5877                 }
5878
5879                 param->lsp_is_specific = true;
5880                 param->lsp_stripe_count = lsa.lsa_nr_tgts;
5881                 memcpy(param->lsp_tgts, mdts, sizeof(*mdts) * lsa.lsa_nr_tgts);
5882         }
5883
5884         if (!default_stripe && (lsa.lsa_pattern & LMV_HASH_FLAG_SPACE)) {
5885                 fprintf(stderr, "%s %s: can only specify -H space with -D\n",
5886                         progname, argv[0]);
5887                 free(param);
5888                 return CMD_HELP;
5889         }
5890
5891         if (param->lsp_stripe_offset != -1 &&
5892             lsa.lsa_pattern & LMV_HASH_FLAG_SPACE) {
5893                 fprintf(stderr, "%s %s: can only specify -H space with -i -1\n",
5894                         progname, argv[0]);
5895                 free(param);
5896                 return CMD_HELP;
5897         }
5898
5899         dname = argv[optind];
5900         do {
5901                 if (default_stripe) {
5902                         result = llapi_dir_set_default_lmv(dname, param);
5903                         if (result)
5904                                 fprintf(stderr,
5905                                         "%s setdirstripe: cannot set default stripe on dir '%s': %s\n",
5906                                         progname, dname, strerror(-result));
5907                         continue;
5908                 }
5909
5910                 /*
5911                  * if current \a dname isn't under the same \a mntdir as the
5912                  * last one, and the last one was auto-distributed, restore
5913                  * \a param.
5914                  */
5915                 if (mntdir[0] != '\0' &&
5916                     strncmp(dname, mntdir, strlen(mntdir)) &&
5917                     auto_distributed) {
5918                         param->lsp_is_specific = false;
5919                         param->lsp_stripe_offset = -1;
5920                         auto_distributed = false;
5921                 }
5922
5923                 /*
5924                  * TODO: when MDT can allocate object with QoS (LU-9435), below
5925                  * code should be removed, instead we should let LMV to allocate
5926                  * the starting MDT object, and then let LOD allocate other MDT
5927                  * objects.
5928                  */
5929                 if (!param->lsp_is_specific && param->lsp_stripe_offset == -1) {
5930                         char path[PATH_MAX] = "";
5931
5932                         if (!lsb) {
5933                                 lsb = malloc(sizeof(*lsb));
5934                                 if (!lsb) {
5935                                         result = -ENOMEM;
5936                                         break;
5937                                 }
5938                         }
5939                         lsb->sb_count = 0;
5940
5941                         /* use mntdir for dirname() temporarily */
5942                         strncpy(mntdir, dname, sizeof(mntdir) - 1);
5943                         if (!realpath(dirname(mntdir), path)) {
5944                                 result = -errno;
5945                                 fprintf(stderr,
5946                                         "error: invalid path '%s': %s\n",
5947                                         argv[optind], strerror(errno));
5948                                 break;
5949                         }
5950                         mntdir[0] = '\0';
5951
5952                         result = llapi_search_mounts(path, 0, mntdir, NULL);
5953                         if (result < 0 || mntdir[0] == '\0') {
5954                                 fprintf(stderr,
5955                                         "No suitable Lustre mount found\n");
5956                                 break;
5957                         }
5958
5959                         result = mntdf(mntdir, NULL, NULL, 0, LL_STATFS_LMV,
5960                                        lsb);
5961                         if (result < 0)
5962                                 break;
5963
5964                         if (param->lsp_stripe_count > lsb->sb_count) {
5965                                 fprintf(stderr,
5966                                         "error: stripe count %d is too big\n",
5967                                         param->lsp_stripe_count);
5968                                 result = -ERANGE;
5969                                 break;
5970                         }
5971
5972                         qsort(lsb->sb_buf, lsb->sb_count,
5973                               sizeof(struct ll_statfs_data),
5974                               ll_statfs_data_comp);
5975
5976                         auto_distributed = true;
5977                 }
5978
5979                 if (auto_distributed) {
5980                         int r;
5981                         int nr = MAX(param->lsp_stripe_count,
5982                                      lsb->sb_count / 2);
5983
5984                         /* don't use server whose usage is above 90% */
5985                         while (nr != param->lsp_stripe_count &&
5986                                obd_statfs_ratio(&lsb->sb_buf[nr].sd_st, false) >
5987                                90)
5988                                 nr = MAX(param->lsp_stripe_count, nr / 2);
5989
5990                         /* get \a r between [0, nr) */
5991                         r = rand() % nr;
5992
5993                         param->lsp_stripe_offset = lsb->sb_buf[r].sd_index;
5994                         if (param->lsp_stripe_count > 1) {
5995                                 int i = 0;
5996
5997                                 param->lsp_is_specific = true;
5998                                 for (; i < param->lsp_stripe_count; i++)
5999                                         param->lsp_tgts[(i + r) % nr] =
6000                                                 lsb->sb_buf[i].sd_index;
6001                         }
6002                 }
6003
6004                 result = llapi_dir_create(dname, mode, param);
6005                 if (result)
6006                         fprintf(stderr,
6007                                 "%s setdirstripe: cannot create dir '%s': %s\n",
6008                                 progname, dname, strerror(-result));
6009         } while (!result && (dname = argv[++optind]));
6010
6011         if (mode_opt != NULL)
6012                 umask(previous_mode);
6013
6014         free(lsb);
6015         free(param);
6016         return result;
6017 }
6018
6019 /* functions */
6020 static int lfs_rmentry(int argc, char **argv)
6021 {
6022         char *dname;
6023         int   index;
6024         int   result = 0;
6025
6026         if (argc <= 1) {
6027                 fprintf(stderr, "error: %s: missing dirname\n",
6028                         argv[0]);
6029                 return CMD_HELP;
6030         }
6031
6032         index = 1;
6033         dname = argv[index];
6034         while (dname != NULL) {
6035                 result = llapi_direntry_remove(dname);
6036                 if (result) {
6037                         fprintf(stderr, "error: %s: remove dir entry '%s' "
6038                                 "failed\n", argv[0], dname);
6039                         break;
6040                 }
6041                 dname = argv[++index];
6042         }
6043         return result;
6044 }
6045
6046 static int lfs_mv(int argc, char **argv)
6047 {
6048         struct lmv_user_md lmu = { LMV_USER_MAGIC };
6049         struct find_param param = {
6050                 .fp_max_depth = -1,
6051                 .fp_mdt_index = -1,
6052         };
6053         char *end;
6054         int c;
6055         int rc = 0;
6056         struct option long_opts[] = {
6057         { .val = 'm',   .name = "mdt",          .has_arg = required_argument },
6058         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument },
6059         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
6060         { .name = NULL } };
6061
6062         while ((c = getopt_long(argc, argv, "m:M:v", long_opts, NULL)) != -1) {
6063                 switch (c) {
6064 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
6065                 case 'M':
6066                         fprintf(stderr, "warning: '-M' deprecated"
6067                                 ", use '--mdt-index' or '-m' instead\n");
6068 #endif
6069                 case 'm':
6070                         lmu.lum_stripe_offset = strtoul(optarg, &end, 0);
6071                         if (*end != '\0') {
6072                                 fprintf(stderr, "%s mv: bad MDT index '%s'\n",
6073                                         progname, optarg);
6074                                 return CMD_HELP;
6075                         }
6076                         break;
6077                 case 'v':
6078                         param.fp_verbose = VERBOSE_DETAIL;
6079                         break;
6080                 default:
6081                         fprintf(stderr, "%s mv: unrecognized option '%s'\n",
6082                                 progname, argv[optind - 1]);
6083                         return CMD_HELP;
6084                 }
6085         }
6086
6087         if (lmu.lum_stripe_offset == -1) {
6088                 fprintf(stderr, "%s mv: MDT index must be specified\n",
6089                         progname);
6090                 return CMD_HELP;
6091         }
6092
6093         if (optind >= argc) {
6094                 fprintf(stderr, "%s mv: DIR must be specified\n", progname);
6095                 return CMD_HELP;
6096         }
6097
6098
6099         /* initialize migrate mdt parameters */
6100         param.fp_lmv_md = &lmu;
6101         param.fp_migrate = 1;
6102         rc = llapi_migrate_mdt(argv[optind], &param);
6103         if (rc != 0)
6104                 fprintf(stderr, "%s mv: cannot migrate '%s' to MDT%04x: %s\n",
6105                         progname, argv[optind], param.fp_mdt_index,
6106                         strerror(-rc));
6107         return rc;
6108 }
6109
6110 static int lfs_osts(int argc, char **argv)
6111 {
6112         return lfs_tgts(argc, argv);
6113 }
6114
6115 static int lfs_mdts(int argc, char **argv)
6116 {
6117         return lfs_tgts(argc, argv);
6118 }
6119
6120 static int lfs_df(int argc, char **argv)
6121 {
6122         char mntdir[PATH_MAX] = {'\0'}, path[PATH_MAX] = {'\0'};
6123         enum mntdf_flags flags = MNTDF_SHOW;
6124         int ops = LL_STATFS_LMV | LL_STATFS_LOV;
6125         int c, rc = 0, index = 0;
6126         char fsname[PATH_MAX] = "", *pool_name = NULL;
6127         struct option long_opts[] = {
6128         { .val = 'h',   .name = "human-readable",
6129                                                 .has_arg = no_argument },
6130         { .val = 'i',   .name = "inodes",       .has_arg = no_argument },
6131         { .val = 'l',   .name = "lazy",         .has_arg = no_argument },
6132         { .val = 'p',   .name = "pool",         .has_arg = required_argument },
6133         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
6134         { .name = NULL} };
6135
6136         while ((c = getopt_long(argc, argv, "hilp:v", long_opts, NULL)) != -1) {
6137                 switch (c) {
6138                 case 'h':
6139                         flags |= MNTDF_COOKED;
6140                         break;
6141                 case 'i':
6142                         flags |= MNTDF_INODES;
6143                         break;
6144                 case 'l':
6145                         flags |= MNTDF_LAZY;
6146                         break;
6147                 case 'p':
6148                         pool_name = optarg;
6149                         break;
6150                 case 'v':
6151                         flags |= MNTDF_VERBOSE;
6152                         break;
6153                 default:
6154                         return CMD_HELP;
6155                 }
6156         }
6157         if (optind < argc && !realpath(argv[optind], path)) {
6158                 rc = -errno;
6159                 fprintf(stderr, "error: invalid path '%s': %s\n",
6160                         argv[optind], strerror(-rc));
6161                 return rc;
6162         }
6163
6164         while (!llapi_search_mounts(path, index++, mntdir, fsname)) {
6165                 /* Check if we have a mount point */
6166                 if (mntdir[0] == '\0')
6167                         continue;
6168
6169                 rc = mntdf(mntdir, fsname, pool_name, flags, ops, NULL);
6170                 if (rc || path[0] != '\0')
6171                         break;
6172                 fsname[0] = '\0'; /* avoid matching in next loop */
6173                 mntdir[0] = '\0'; /* avoid matching in next loop */
6174         }
6175
6176         return rc;
6177 }
6178
6179 static int print_instance(const char *mntdir, char *fsname, size_t fsnamelen,
6180                           bool opt_instance, bool opt_fsname, bool opt_mntdir)
6181 {
6182         char *buf = fsname;
6183
6184         /* llapi_search_mounts() fills "fsname", but that is not called if
6185          * explicit paths are specified on the command-line
6186          */
6187         if (opt_instance || (opt_fsname && fsname[0] == '\0')) {
6188                 int rc = llapi_getname(mntdir, fsname, fsnamelen);
6189
6190                 if (rc < 0) {
6191                         fprintf(stderr, "cannot get instance for '%s': %s\n",
6192                                 mntdir, strerror(-rc));
6193                         return rc;
6194                 }
6195                 buf = fsname;
6196                 if (!opt_instance) {
6197                         /* print only the fsname name */
6198                         buf = strchr(fsname, '-');
6199                         if (buf)
6200                                 *buf = '\0';
6201                         buf = fsname;
6202                 } else if (!opt_fsname) {
6203                         /* print only the instance name */
6204                         buf = strchr(fsname, '-');
6205                         if (buf)
6206                                 buf++;
6207                         else
6208                                 buf = fsname;
6209                 }
6210         } else if (opt_fsname) {
6211                 /* print only the fsname */
6212                 buf = fsname;
6213         }
6214
6215         printf("%s %s\n", buf, opt_mntdir ? mntdir : "");
6216
6217         return 0;
6218 }
6219
6220 static int lfs_getname(int argc, char **argv)
6221 {
6222         struct option long_opts[] = {
6223         { .val = 'h',   .name = "help",         .has_arg = no_argument },
6224         { .val = 'i',   .name = "instance",     .has_arg = no_argument },
6225         { .val = 'n',   .name = "fsname",       .has_arg = no_argument },
6226         { .name = NULL} };
6227         bool opt_instance = false, opt_fsname = false;
6228         char fsname[PATH_MAX] = "";
6229         int rc = 0, rc2, c;
6230
6231         while ((c = getopt_long(argc, argv, "hin", long_opts, NULL)) != -1) {
6232                 switch (c) {
6233                 case 'i':
6234                         opt_instance = true;
6235                         break;
6236                 case 'n':
6237                         opt_fsname = true;
6238                         break;
6239                 case 'h':
6240                 default:
6241                         return CMD_HELP;
6242                 }
6243         }
6244
6245         /* If neither option is given, print both instance and fsname */
6246         if (!opt_instance && !opt_fsname)
6247                 opt_instance = opt_fsname = true;
6248
6249         if (optind == argc) { /* no paths specified, get all paths. */
6250                 char mntdir[PATH_MAX] = "", path[PATH_MAX] = "";
6251                 int index = 0;
6252
6253                 while (!llapi_search_mounts(path, index++, mntdir, fsname)) {
6254                         rc2 = print_instance(mntdir, fsname, sizeof(fsname),
6255                                              opt_instance, opt_fsname, true);
6256                         if (!rc)
6257                                 rc = rc2;
6258                         path[0] = fsname[0] = mntdir[0] = '\0';
6259                 }
6260         } else { /* paths specified, only attempt to search these. */
6261                 bool opt_mntdir;
6262
6263                 /* if only one path is given, print only requested info */
6264                 opt_mntdir = argc - optind > 1 || (opt_instance == opt_fsname);
6265
6266                 for (; optind < argc; optind++) {
6267                         rc2 = print_instance(argv[optind], fsname,
6268                                              sizeof(fsname), opt_instance,
6269                                              opt_fsname, opt_mntdir);
6270                         if (!rc)
6271                                 rc = rc2;
6272                         fsname[0] = '\0';
6273                 }
6274         }
6275
6276         return rc;
6277 }
6278
6279 static int lfs_check(int argc, char **argv)
6280 {
6281         char mntdir[PATH_MAX] = {'\0'};
6282         int num_types = 1;
6283         char *obd_types[3];
6284         char obd_type1[4];
6285         char obd_type2[4];
6286         char obd_type3[4];
6287         int rc;
6288
6289         if (argc != 2) {
6290                 fprintf(stderr, "%s check: server type must be specified\n",
6291                         progname);
6292                 return CMD_HELP;
6293         }
6294
6295         obd_types[0] = obd_type1;
6296         obd_types[1] = obd_type2;
6297         obd_types[2] = obd_type3;
6298
6299         if (strcmp(argv[1], "osts") == 0) {
6300                 strcpy(obd_types[0], "osc");
6301         } else if (strcmp(argv[1], "mdts") == 0 ||
6302                    strcmp(argv[1], "mds") == 0) {
6303                 strcpy(obd_types[0], "mdc");
6304         } else if (strcmp(argv[1], "mgts") == 0) {
6305                 strcpy(obd_types[0], "mgc");
6306         } else if (strcmp(argv[1], "all") == 0 ||
6307                    strcmp(argv[1], "servers") == 0) {
6308                 num_types = 3;
6309                 strcpy(obd_types[0], "osc");
6310                 strcpy(obd_types[1], "mdc");
6311                 strcpy(obd_types[2], "mgc");
6312         } else {
6313                 fprintf(stderr, "%s check: unrecognized option '%s'\n",
6314                         progname, argv[1]);
6315                 return CMD_HELP;
6316         }
6317
6318         rc = llapi_search_mounts(NULL, 0, mntdir, NULL);
6319         if (rc < 0 || mntdir[0] == '\0') {
6320                 fprintf(stderr,
6321                         "%s check: cannot find mounted Lustre filesystem: %s\n",
6322                         progname, (rc < 0) ? strerror(-rc) : strerror(ENODEV));
6323                 return rc;
6324         }
6325
6326         rc = llapi_target_check(num_types, obd_types, mntdir);
6327         if (rc)
6328                 fprintf(stderr, "%s check: cannot check target '%s': %s\n",
6329                         progname, argv[1], strerror(-rc));
6330
6331         return rc;
6332
6333 }
6334
6335 #ifdef HAVE_SYS_QUOTA_H
6336 #define ARG2INT(nr, str, msg)                                           \
6337 do {                                                                    \
6338         char *endp;                                                     \
6339         nr = strtol(str, &endp, 0);                                     \
6340         if (*endp != '\0') {                                            \
6341                 fprintf(stderr, "%s: bad %s '%s'\n",                    \
6342                         progname, msg, str);                            \
6343                 return CMD_HELP;                                        \
6344         }                                                               \
6345 } while (0)
6346
6347 #define ADD_OVERFLOW(a,b) ((a + b) < a) ? (a = ULONG_MAX) : (a = a + b)
6348
6349 /* Convert format time string "XXwXXdXXhXXmXXs" into seconds value
6350  * returns the value or ULONG_MAX on integer overflow or incorrect format
6351  * Notes:
6352  *        1. the order of specifiers is arbitrary (may be: 5w3s or 3s5w)
6353  *        2. specifiers may be encountered multiple times (2s3s is 5 seconds)
6354  *        3. empty integer value is interpreted as 0
6355  */
6356 static unsigned long str2sec(const char* timestr)
6357 {
6358         const char spec[] = "smhdw";
6359         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
6360         unsigned long val = 0;
6361         char *tail;
6362
6363         if (strpbrk(timestr, spec) == NULL) {
6364                 /* no specifiers inside the time string,
6365                    should treat it as an integer value */
6366                 val = strtoul(timestr, &tail, 10);
6367                 return *tail ? ULONG_MAX : val;
6368         }
6369
6370         /* format string is XXwXXdXXhXXmXXs */
6371         while (*timestr) {
6372                 unsigned long v;
6373                 int ind;
6374                 char* ptr;
6375
6376                 v = strtoul(timestr, &tail, 10);
6377                 if (v == ULONG_MAX || *tail == '\0')
6378                         /* value too large (ULONG_MAX or more)
6379                            or missing specifier */
6380                         goto error;
6381
6382                 ptr = strchr(spec, *tail);
6383                 if (ptr == NULL)
6384                         /* unknown specifier */
6385                         goto error;
6386
6387                 ind = ptr - spec;
6388
6389                 /* check if product will overflow the type */
6390                 if (!(v < ULONG_MAX / mult[ind]))
6391                         goto error;
6392
6393                 ADD_OVERFLOW(val, mult[ind] * v);
6394                 if (val == ULONG_MAX)
6395                         goto error;
6396
6397                 timestr = tail + 1;
6398         }
6399
6400         return val;
6401
6402 error:
6403         return ULONG_MAX;
6404 }
6405
6406 #define ARG2ULL(nr, str, def_units)                                     \
6407 do {                                                                    \
6408         unsigned long long limit, units = def_units;                    \
6409         int rc;                                                         \
6410                                                                         \
6411         rc = llapi_parse_size(str, &limit, &units, 1);                  \
6412         if (rc < 0) {                                                   \
6413                 fprintf(stderr, "%s: invalid limit '%s'\n",             \
6414                         progname, str);                                 \
6415                 return CMD_HELP;                                        \
6416         }                                                               \
6417         nr = limit;                                                     \
6418 } while (0)
6419
6420 static inline int has_times_option(int argc, char **argv)
6421 {
6422         int i;
6423
6424         for (i = 1; i < argc; i++)
6425                 if (!strcmp(argv[i], "-t"))
6426                         return 1;
6427
6428         return 0;
6429 }
6430
6431 int lfs_setquota_times(int argc, char **argv)
6432 {
6433         int c, rc;
6434         struct if_quotactl qctl;
6435         char *mnt, *obd_type = (char *)qctl.obd_type;
6436         struct obd_dqblk *dqb = &qctl.qc_dqblk;
6437         struct obd_dqinfo *dqi = &qctl.qc_dqinfo;
6438         struct option long_opts[] = {
6439         { .val = 'b',   .name = "block-grace",  .has_arg = required_argument },
6440         { .val = 'g',   .name = "group",        .has_arg = no_argument },
6441         { .val = 'i',   .name = "inode-grace",  .has_arg = required_argument },
6442         { .val = 'p',   .name = "projid",       .has_arg = no_argument },
6443         { .val = 't',   .name = "times",        .has_arg = no_argument },
6444         { .val = 'u',   .name = "user",         .has_arg = no_argument },
6445         { .name = NULL } };
6446         int qtype;
6447
6448         memset(&qctl, 0, sizeof(qctl));
6449         qctl.qc_cmd  = LUSTRE_Q_SETINFO;
6450         qctl.qc_type = ALLQUOTA;
6451
6452         while ((c = getopt_long(argc, argv, "b:gi:ptu",
6453                                 long_opts, NULL)) != -1) {
6454                 switch (c) {
6455                 case 'u':
6456                         qtype = USRQUOTA;
6457                         goto quota_type;
6458                 case 'g':
6459                         qtype = GRPQUOTA;
6460                         goto quota_type;
6461                 case 'p':
6462                         qtype = PRJQUOTA;
6463 quota_type:
6464                         if (qctl.qc_type != ALLQUOTA) {
6465                                 fprintf(stderr, "error: -u/g/p can't be used "
6466                                                 "more than once\n");
6467                                 return CMD_HELP;
6468                         }
6469                         qctl.qc_type = qtype;
6470                         break;
6471                 case 'b':
6472                         if ((dqi->dqi_bgrace = str2sec(optarg)) == ULONG_MAX) {
6473                                 fprintf(stderr, "error: bad block-grace: %s\n",
6474                                         optarg);
6475                                 return CMD_HELP;
6476                         }
6477                         dqb->dqb_valid |= QIF_BTIME;
6478                         break;
6479                 case 'i':
6480                         if ((dqi->dqi_igrace = str2sec(optarg)) == ULONG_MAX) {
6481                                 fprintf(stderr, "error: bad inode-grace: %s\n",
6482                                         optarg);
6483                                 return CMD_HELP;
6484                         }
6485                         dqb->dqb_valid |= QIF_ITIME;
6486                         break;
6487                 case 't': /* Yes, of course! */
6488                         break;
6489                 default: /* getopt prints error message for us when opterr != 0 */
6490                         return CMD_HELP;
6491                 }
6492         }
6493
6494         if (qctl.qc_type == ALLQUOTA) {
6495                 fprintf(stderr, "error: neither -u, -g nor -p specified\n");
6496                 return CMD_HELP;
6497         }
6498
6499         if (optind != argc - 1) {
6500                 fprintf(stderr, "error: unexpected parameters encountered\n");
6501                 return CMD_HELP;
6502         }
6503
6504         if ((dqb->dqb_valid | QIF_BTIME && dqi->dqi_bgrace >= UINT_MAX) ||
6505             (dqb->dqb_valid | QIF_ITIME && dqi->dqi_igrace >= UINT_MAX)) {
6506                 fprintf(stderr, "error: grace time is too large\n");
6507                 return CMD_HELP;
6508         }
6509
6510         mnt = argv[optind];
6511         rc = llapi_quotactl(mnt, &qctl);
6512         if (rc) {
6513                 if (*obd_type)
6514                         fprintf(stderr, "%s %s ", obd_type,
6515                                 obd_uuid2str(&qctl.obd_uuid));
6516                 fprintf(stderr, "setquota failed: %s\n", strerror(-rc));
6517                 return rc;
6518         }
6519
6520         return 0;
6521 }
6522
6523 #define BSLIMIT (1 << 0)
6524 #define BHLIMIT (1 << 1)
6525 #define ISLIMIT (1 << 2)
6526 #define IHLIMIT (1 << 3)
6527
6528 int lfs_setquota(int argc, char **argv)
6529 {
6530         int c, rc = 0;
6531         struct if_quotactl qctl;
6532         char *mnt, *obd_type = (char *)qctl.obd_type;
6533         struct obd_dqblk *dqb = &qctl.qc_dqblk;
6534         struct option long_opts[] = {
6535         { .val = 'b',   .name = "block-softlimit",
6536                                                 .has_arg = required_argument },
6537         { .val = 'B',   .name = "block-hardlimit",
6538                                                 .has_arg = required_argument },
6539         { .val = 'd',   .name = "default",      .has_arg = no_argument },
6540         { .val = 'g',   .name = "group",        .has_arg = required_argument },
6541         { .val = 'G',   .name = "default-grp",  .has_arg = no_argument },
6542         { .val = 'i',   .name = "inode-softlimit",
6543                                                 .has_arg = required_argument },
6544         { .val = 'I',   .name = "inode-hardlimit",
6545                                                 .has_arg = required_argument },
6546         { .val = 'p',   .name = "projid",       .has_arg = required_argument },
6547         { .val = 'P',   .name = "default-prj",  .has_arg = no_argument },
6548         { .val = 'u',   .name = "user",         .has_arg = required_argument },
6549         { .val = 'U',   .name = "default-usr",  .has_arg = no_argument },
6550         { .name = NULL } };
6551         unsigned limit_mask = 0;
6552         char *endptr;
6553         bool use_default = false;
6554         int qtype;
6555
6556         if (has_times_option(argc, argv))
6557                 return lfs_setquota_times(argc, argv);
6558
6559         memset(&qctl, 0, sizeof(qctl));
6560         qctl.qc_cmd  = LUSTRE_Q_SETQUOTA;
6561         qctl.qc_type = ALLQUOTA; /* ALLQUOTA makes no sense for setquota,
6562                                   * so it can be used as a marker that qc_type
6563                                   * isn't reinitialized from command line */
6564
6565         while ((c = getopt_long(argc, argv, "b:B:dg:Gi:I:p:Pu:U",
6566                 long_opts, NULL)) != -1) {
6567                 switch (c) {
6568                 case 'U':
6569                         qctl.qc_cmd = LUSTRE_Q_SETDEFAULT;
6570                         qtype = USRQUOTA;
6571                         qctl.qc_id = 0;
6572                         goto quota_type_def;
6573                 case 'u':
6574                         qtype = USRQUOTA;
6575                         rc = name2uid(&qctl.qc_id, optarg);
6576                         goto quota_type;
6577                 case 'G':
6578                         qctl.qc_cmd = LUSTRE_Q_SETDEFAULT;
6579                         qtype = GRPQUOTA;
6580                         qctl.qc_id = 0;
6581                         goto quota_type_def;
6582                 case 'g':
6583                         qtype = GRPQUOTA;
6584                         rc = name2gid(&qctl.qc_id, optarg);
6585                         goto quota_type;
6586                 case 'P':
6587                         qctl.qc_cmd = LUSTRE_Q_SETDEFAULT;
6588                         qtype = PRJQUOTA;
6589                         qctl.qc_id = 0;
6590                         goto quota_type_def;
6591                 case 'p':
6592                         qtype = PRJQUOTA;
6593                         rc = name2projid(&qctl.qc_id, optarg);
6594 quota_type:
6595                         if (rc) {
6596                                 qctl.qc_id = strtoul(optarg, &endptr, 10);
6597                                 if (*endptr != '\0') {
6598                                         fprintf(stderr, "%s setquota: invalid"
6599                                                 " id '%s'\n", progname, optarg);
6600                                         return -1;
6601                                 }
6602                         }
6603
6604                         if (qctl.qc_id == 0) {
6605                                 fprintf(stderr, "%s setquota: can't set quota"
6606                                         " for root usr/group/project.\n",
6607                                         progname);
6608                                 return -1;
6609                         }
6610
6611 quota_type_def:
6612                         if (qctl.qc_type != ALLQUOTA) {
6613                                 fprintf(stderr,
6614                                         "%s setquota: only one of -u, -U, -g,"
6615                                         " -G, -p or -P may be specified\n",
6616                                         progname);
6617                                 return CMD_HELP;
6618                         }
6619                         qctl.qc_type = qtype;
6620                         break;
6621                 case 'd':
6622                         qctl.qc_cmd = LUSTRE_Q_SETDEFAULT;
6623                         use_default = true;
6624                         break;
6625                 case 'b':
6626                         ARG2ULL(dqb->dqb_bsoftlimit, optarg, 1024);
6627                         dqb->dqb_bsoftlimit >>= 10;
6628                         limit_mask |= BSLIMIT;
6629                         if (dqb->dqb_bsoftlimit &&
6630                             dqb->dqb_bsoftlimit <= 1024) /* <= 1M? */
6631                                 fprintf(stderr,
6632                                         "%s setquota: warning: block softlimit '%llu' smaller than minimum qunit size\n"
6633                                         "See '%s help setquota' or Lustre manual for details\n",
6634                                         progname,
6635                                         (unsigned long long)dqb->dqb_bsoftlimit,
6636                                         progname);
6637                         break;
6638                 case 'B':
6639                         ARG2ULL(dqb->dqb_bhardlimit, optarg, 1024);
6640                         dqb->dqb_bhardlimit >>= 10;
6641                         limit_mask |= BHLIMIT;
6642                         if (dqb->dqb_bhardlimit &&
6643                             dqb->dqb_bhardlimit <= 1024) /* <= 1M? */
6644                                 fprintf(stderr,
6645                                         "%s setquota: warning: block hardlimit '%llu' smaller than minimum qunit size\n"
6646                                         "See '%s help setquota' or Lustre manual for details\n",
6647                                         progname,
6648                                         (unsigned long long)dqb->dqb_bhardlimit,
6649                                         progname);
6650                         break;
6651                 case 'i':
6652                         ARG2ULL(dqb->dqb_isoftlimit, optarg, 1);
6653                         limit_mask |= ISLIMIT;
6654                         if (dqb->dqb_isoftlimit &&
6655                             dqb->dqb_isoftlimit <= 1024) /* <= 1K inodes? */
6656                                 fprintf(stderr,
6657                                         "%s setquota: warning: inode softlimit '%llu' smaller than minimum qunit size\n"
6658                                         "See '%s help setquota' or Lustre manual for details\n",
6659                                         progname,
6660                                         (unsigned long long)dqb->dqb_isoftlimit,
6661                                         progname);
6662                         break;
6663                 case 'I':
6664                         ARG2ULL(dqb->dqb_ihardlimit, optarg, 1);
6665                         limit_mask |= IHLIMIT;
6666                         if (dqb->dqb_ihardlimit &&
6667                             dqb->dqb_ihardlimit <= 1024) /* <= 1K inodes? */
6668                                 fprintf(stderr,
6669                                         "%s setquota: warning: inode hardlimit '%llu' smaller than minimum qunit size\n"
6670                                         "See '%s help setquota' or Lustre manual for details\n",
6671                                         progname,
6672                                         (unsigned long long)dqb->dqb_ihardlimit,
6673                                         progname);
6674                         break;
6675                 default:
6676                         fprintf(stderr,
6677                                 "%s setquota: unrecognized option '%s'\n",
6678                                 progname, argv[optind - 1]);
6679                         return CMD_HELP;
6680                 }
6681         }
6682
6683         if (qctl.qc_type == ALLQUOTA) {
6684                 fprintf(stderr,
6685                         "%s setquota: either -u or -g must be specified\n",
6686                         progname);
6687                 return CMD_HELP;
6688         }
6689
6690         if (!use_default && limit_mask == 0) {
6691                 fprintf(stderr,
6692                         "%s setquota: at least one limit must be specified\n",
6693                         progname);
6694                 return CMD_HELP;
6695         }
6696
6697         if (use_default && limit_mask != 0) {
6698                 fprintf(stderr,
6699                         "%s setquota: limits should not be specified when"
6700                         " using default quota\n",
6701                         progname);
6702                 return CMD_HELP;
6703         }
6704
6705         if (use_default && qctl.qc_id == 0) {
6706                 fprintf(stderr,
6707                         "%s setquota: can not set default quota for root"
6708                         " user/group/project\n",
6709                         progname);
6710                 return CMD_HELP;
6711         }
6712
6713         if (optind != argc - 1) {
6714                 fprintf(stderr,
6715                         "%s setquota: filesystem not specified or unexpected argument '%s'\n",
6716                         progname, argv[optind]);
6717                 return CMD_HELP;
6718         }
6719
6720         mnt = argv[optind];
6721
6722         if (use_default) {
6723                 dqb->dqb_bhardlimit = 0;
6724                 dqb->dqb_bsoftlimit = 0;
6725                 dqb->dqb_ihardlimit = 0;
6726                 dqb->dqb_isoftlimit = 0;
6727                 dqb->dqb_itime = 0;
6728                 dqb->dqb_btime = 0;
6729                 dqb->dqb_valid |= QIF_LIMITS | QIF_TIMES;
6730         } else if ((!(limit_mask & BHLIMIT) ^ !(limit_mask & BSLIMIT)) ||
6731                    (!(limit_mask & IHLIMIT) ^ !(limit_mask & ISLIMIT))) {
6732                 /* sigh, we can't just set blimits/ilimits */
6733                 struct if_quotactl tmp_qctl = {.qc_cmd  = LUSTRE_Q_GETQUOTA,
6734                                                .qc_type = qctl.qc_type,
6735                                                .qc_id   = qctl.qc_id};
6736
6737                 rc = llapi_quotactl(mnt, &tmp_qctl);
6738                 if (rc < 0)
6739                         return rc;
6740
6741                 if (!(limit_mask & BHLIMIT))
6742                         dqb->dqb_bhardlimit = tmp_qctl.qc_dqblk.dqb_bhardlimit;
6743                 if (!(limit_mask & BSLIMIT))
6744                         dqb->dqb_bsoftlimit = tmp_qctl.qc_dqblk.dqb_bsoftlimit;
6745                 if (!(limit_mask & IHLIMIT))
6746                         dqb->dqb_ihardlimit = tmp_qctl.qc_dqblk.dqb_ihardlimit;
6747                 if (!(limit_mask & ISLIMIT))
6748                         dqb->dqb_isoftlimit = tmp_qctl.qc_dqblk.dqb_isoftlimit;
6749
6750                 /* Keep grace times if we have got no softlimit arguments */
6751                 if ((limit_mask & BHLIMIT) && !(limit_mask & BSLIMIT)) {
6752                         dqb->dqb_valid |= QIF_BTIME;
6753                         dqb->dqb_btime = tmp_qctl.qc_dqblk.dqb_btime;
6754                 }
6755
6756                 if ((limit_mask & IHLIMIT) && !(limit_mask & ISLIMIT)) {
6757                         dqb->dqb_valid |= QIF_ITIME;
6758                         dqb->dqb_itime = tmp_qctl.qc_dqblk.dqb_itime;
6759                 }
6760         }
6761
6762         dqb->dqb_valid |= (limit_mask & (BHLIMIT | BSLIMIT)) ? QIF_BLIMITS : 0;
6763         dqb->dqb_valid |= (limit_mask & (IHLIMIT | ISLIMIT)) ? QIF_ILIMITS : 0;
6764
6765         rc = llapi_quotactl(mnt, &qctl);
6766         if (rc) {
6767                 if (*obd_type)
6768                         fprintf(stderr,
6769                                 "%s setquota: cannot quotactl '%s' '%s': %s",
6770                                 progname, obd_type,
6771                                 obd_uuid2str(&qctl.obd_uuid), strerror(-rc));
6772                 return rc;
6773         }
6774
6775         return 0;
6776 }
6777
6778 /* Converts seconds value into format string
6779  * result is returned in buf
6780  * Notes:
6781  *        1. result is in descenting order: 1w2d3h4m5s
6782  *        2. zero fields are not filled (except for p. 3): 5d1s
6783  *        3. zero seconds value is presented as "0s"
6784  */
6785 static char * __sec2str(time_t seconds, char *buf)
6786 {
6787         const char spec[] = "smhdw";
6788         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
6789         unsigned long c;
6790         char *tail = buf;
6791         int i;
6792
6793         for (i = sizeof(mult) / sizeof(mult[0]) - 1 ; i >= 0; i--) {
6794                 c = seconds / mult[i];
6795
6796                 if (c > 0 || (i == 0 && buf == tail))
6797                         tail += snprintf(tail, 40-(tail-buf), "%lu%c", c, spec[i]);
6798
6799                 seconds %= mult[i];
6800         }
6801
6802         return tail;
6803 }
6804
6805 static void sec2str(time_t seconds, char *buf, int rc)
6806 {
6807         char *tail = buf;
6808
6809         if (rc)
6810                 *tail++ = '[';
6811
6812         tail = __sec2str(seconds, tail);
6813
6814         if (rc && tail - buf < 39) {
6815                 *tail++ = ']';
6816                 *tail++ = 0;
6817         }
6818 }
6819
6820 static void diff2str(time_t seconds, char *buf, time_t now)
6821 {
6822
6823         buf[0] = 0;
6824         if (!seconds)
6825                 return;
6826         if (seconds <= now) {
6827                 strcpy(buf, "none");
6828                 return;
6829         }
6830         __sec2str(seconds - now, buf);
6831 }
6832
6833 static void print_quota_title(char *name, struct if_quotactl *qctl,
6834                               bool human_readable, bool show_default)
6835 {
6836         if (show_default) {
6837                 printf("Disk default %s quota:\n", qtype_name(qctl->qc_type));
6838                 printf("%15s %8s%8s%8s %8s%8s%8s\n",
6839                        "Filesystem", "bquota", "blimit", "bgrace",
6840                        "iquota", "ilimit", "igrace");
6841         } else {
6842                 printf("Disk quotas for %s %s (%cid %u):\n",
6843                        qtype_name(qctl->qc_type), name,
6844                        *qtype_name(qctl->qc_type), qctl->qc_id);
6845                 printf("%15s%8s %7s%8s%8s%8s %7s%8s%8s\n",
6846                        "Filesystem", human_readable ? "used" : "kbytes",
6847                        "quota", "limit", "grace",
6848                        "files", "quota", "limit", "grace");
6849         }
6850 }
6851
6852 static void kbytes2str(__u64 num, char *buf, int buflen, bool h)
6853 {
6854         if (!h) {
6855                 snprintf(buf, buflen, "%ju", (uintmax_t)num);
6856         } else {
6857                 if (num >> 40)
6858                         snprintf(buf, buflen, "%5.4gP",
6859                                  (double)num / ((__u64)1 << 40));
6860                 else if (num >> 30)
6861                         snprintf(buf, buflen, "%5.4gT",
6862                                  (double)num / (1 << 30));
6863                 else if (num >> 20)
6864                         snprintf(buf, buflen, "%5.4gG",
6865                                  (double)num / (1 << 20));
6866                 else if (num >> 10)
6867                         snprintf(buf, buflen, "%5.4gM",
6868                                  (double)num / (1 << 10));
6869                 else
6870                         snprintf(buf, buflen, "%ju%s", (uintmax_t)num, "k");
6871         }
6872 }
6873
6874 #define STRBUF_LEN      32
6875 static void print_quota(char *mnt, struct if_quotactl *qctl, int type,
6876                         int rc, bool h, bool show_default)
6877 {
6878         time_t now;
6879
6880         time(&now);
6881
6882         if (qctl->qc_cmd == LUSTRE_Q_GETQUOTA || qctl->qc_cmd == Q_GETOQUOTA ||
6883             qctl->qc_cmd == LUSTRE_Q_GETDEFAULT) {
6884                 int bover = 0, iover = 0;
6885                 struct obd_dqblk *dqb = &qctl->qc_dqblk;
6886                 char numbuf[3][STRBUF_LEN];
6887                 char timebuf[40];
6888                 char strbuf[STRBUF_LEN];
6889
6890                 if (dqb->dqb_bhardlimit &&
6891                     lustre_stoqb(dqb->dqb_curspace) >= dqb->dqb_bhardlimit) {
6892                         bover = 1;
6893                 } else if (dqb->dqb_bsoftlimit && dqb->dqb_btime) {
6894                         if (dqb->dqb_btime > now) {
6895                                 bover = 2;
6896                         } else {
6897                                 bover = 3;
6898                         }
6899                 }
6900
6901                 if (dqb->dqb_ihardlimit &&
6902                     dqb->dqb_curinodes >= dqb->dqb_ihardlimit) {
6903                         iover = 1;
6904                 } else if (dqb->dqb_isoftlimit && dqb->dqb_itime) {
6905                         if (dqb->dqb_itime > now) {
6906                                 iover = 2;
6907                         } else {
6908                                 iover = 3;
6909                         }
6910                 }
6911
6912
6913                 if (strlen(mnt) > 15)
6914                         printf("%s\n%15s", mnt, "");
6915                 else
6916                         printf("%15s", mnt);
6917
6918                 if (bover)
6919                         diff2str(dqb->dqb_btime, timebuf, now);
6920                 else if (show_default)
6921                         snprintf(timebuf, sizeof(timebuf), "%llu",
6922                                  (unsigned long long)dqb->dqb_btime);
6923
6924                 kbytes2str(lustre_stoqb(dqb->dqb_curspace),
6925                            strbuf, sizeof(strbuf), h);
6926                 if (rc == -EREMOTEIO)
6927                         sprintf(numbuf[0], "%s*", strbuf);
6928                 else
6929                         sprintf(numbuf[0], (dqb->dqb_valid & QIF_SPACE) ?
6930                                 "%s" : "[%s]", strbuf);
6931
6932                 kbytes2str(dqb->dqb_bsoftlimit, strbuf, sizeof(strbuf), h);
6933                 if (type == QC_GENERAL)
6934                         sprintf(numbuf[1], (dqb->dqb_valid & QIF_BLIMITS) ?
6935                                 "%s" : "[%s]", strbuf);
6936                 else
6937                         sprintf(numbuf[1], "%s", "-");
6938
6939                 kbytes2str(dqb->dqb_bhardlimit, strbuf, sizeof(strbuf), h);
6940                 sprintf(numbuf[2], (dqb->dqb_valid & QIF_BLIMITS) ?
6941                         "%s" : "[%s]", strbuf);
6942
6943                 if (show_default)
6944                         printf(" %6s %7s %7s", numbuf[1], numbuf[2], timebuf);
6945                 else
6946                         printf(" %7s%c %6s %7s %7s",
6947                                numbuf[0], bover ? '*' : ' ', numbuf[1],
6948                                numbuf[2], bover > 1 ? timebuf : "-");
6949
6950
6951                 if (iover)
6952                         diff2str(dqb->dqb_itime, timebuf, now);
6953                 else if (show_default)
6954                         snprintf(timebuf, sizeof(timebuf), "%llu",
6955                                  (unsigned long long)dqb->dqb_itime);
6956
6957                 snprintf(numbuf[0], sizeof(numbuf),
6958                          (dqb->dqb_valid & QIF_INODES) ? "%ju" : "[%ju]",
6959                          (uintmax_t)dqb->dqb_curinodes);
6960
6961                 if (type == QC_GENERAL)
6962                         sprintf(numbuf[1], (dqb->dqb_valid & QIF_ILIMITS) ?
6963                                 "%ju" : "[%ju]",
6964                                 (uintmax_t)dqb->dqb_isoftlimit);
6965                 else
6966                         sprintf(numbuf[1], "%s", "-");
6967
6968                 sprintf(numbuf[2], (dqb->dqb_valid & QIF_ILIMITS) ?
6969                         "%ju" : "[%ju]", (uintmax_t)dqb->dqb_ihardlimit);
6970
6971                 if (show_default)
6972                         printf(" %6s %7s %7s", numbuf[1], numbuf[2], timebuf);
6973                 else if (type != QC_OSTIDX)
6974                         printf(" %7s%c %6s %7s %7s",
6975                                numbuf[0], iover ? '*' : ' ', numbuf[1],
6976                                numbuf[2], iover > 1 ? timebuf : "-");
6977                 else
6978                         printf(" %7s %7s %7s %7s", "-", "-", "-", "-");
6979                 printf("\n");
6980
6981         } else if (qctl->qc_cmd == LUSTRE_Q_GETINFO ||
6982                    qctl->qc_cmd == Q_GETOINFO) {
6983                 char bgtimebuf[40];
6984                 char igtimebuf[40];
6985
6986                 sec2str(qctl->qc_dqinfo.dqi_bgrace, bgtimebuf, rc);
6987                 sec2str(qctl->qc_dqinfo.dqi_igrace, igtimebuf, rc);
6988                 printf("Block grace time: %s; Inode grace time: %s\n",
6989                        bgtimebuf, igtimebuf);
6990         }
6991 }
6992
6993 static int print_obd_quota(char *mnt, struct if_quotactl *qctl, int is_mdt,
6994                            bool h, __u64 *total)
6995 {
6996         int rc = 0, rc1 = 0, count = 0;
6997         __u32 valid = qctl->qc_valid;
6998
6999         rc = llapi_get_obd_count(mnt, &count, is_mdt);
7000         if (rc) {
7001                 fprintf(stderr, "can not get %s count: %s\n",
7002                         is_mdt ? "mdt": "ost", strerror(-rc));
7003                 return rc;
7004         }
7005
7006         for (qctl->qc_idx = 0; qctl->qc_idx < count; qctl->qc_idx++) {
7007                 qctl->qc_valid = is_mdt ? QC_MDTIDX : QC_OSTIDX;
7008                 rc = llapi_quotactl(mnt, qctl);
7009                 if (rc) {
7010                         /* It is remote client case. */
7011                         if (rc == -EOPNOTSUPP) {
7012                                 rc = 0;
7013                                 goto out;
7014                         }
7015
7016                         if (!rc1)
7017                                 rc1 = rc;
7018                         fprintf(stderr, "quotactl %s%d failed.\n",
7019                                 is_mdt ? "mdt": "ost", qctl->qc_idx);
7020                         continue;
7021                 }
7022
7023                 print_quota(obd_uuid2str(&qctl->obd_uuid), qctl,
7024                             qctl->qc_valid, 0, h, false);
7025                 *total += is_mdt ? qctl->qc_dqblk.dqb_ihardlimit :
7026                                    qctl->qc_dqblk.dqb_bhardlimit;
7027         }
7028 out:
7029         qctl->qc_valid = valid;
7030         return rc ? : rc1;
7031 }
7032
7033 static int get_print_quota(char *mnt, char *name, struct if_quotactl *qctl,
7034                            int verbose, int quiet, bool human_readable,
7035                            bool show_default)
7036 {
7037         int rc1 = 0, rc2 = 0, rc3 = 0;
7038         char *obd_type = (char *)qctl->obd_type;
7039         char *obd_uuid = (char *)qctl->obd_uuid.uuid;
7040         __u64 total_ialloc = 0, total_balloc = 0;
7041         bool use_default_for_blk = false;
7042         bool use_default_for_file = false;
7043         int inacc;
7044
7045         rc1 = llapi_quotactl(mnt, qctl);
7046         if (rc1 < 0) {
7047                 switch (rc1) {
7048                 case -ESRCH:
7049                         fprintf(stderr, "%s quotas are not enabled.\n",
7050                                 qtype_name(qctl->qc_type));
7051                         goto out;
7052                 case -EPERM:
7053                         fprintf(stderr, "Permission denied.\n");
7054                 case -ENODEV:
7055                 case -ENOENT:
7056                         /* We already got error message. */
7057                         goto out;
7058                 default:
7059                         fprintf(stderr, "Unexpected quotactl error: %s\n",
7060                                 strerror(-rc1));
7061                 }
7062         }
7063
7064         if (!show_default && qctl->qc_id == 0) {
7065                 qctl->qc_dqblk.dqb_bhardlimit = 0;
7066                 qctl->qc_dqblk.dqb_bsoftlimit = 0;
7067                 qctl->qc_dqblk.dqb_ihardlimit = 0;
7068                 qctl->qc_dqblk.dqb_isoftlimit = 0;
7069                 qctl->qc_dqblk.dqb_btime = 0;
7070                 qctl->qc_dqblk.dqb_itime = 0;
7071                 qctl->qc_dqblk.dqb_valid |= QIF_LIMITS | QIF_TIMES;
7072         }
7073
7074         if (qctl->qc_dqblk.dqb_valid & QIF_BTIME &&
7075             LQUOTA_FLAG(qctl->qc_dqblk.dqb_btime) & LQUOTA_FLAG_DEFAULT) {
7076                 use_default_for_blk = true;
7077                 qctl->qc_dqblk.dqb_btime &= LQUOTA_GRACE_MASK;
7078         }
7079
7080         if (qctl->qc_dqblk.dqb_valid & QIF_ITIME &&
7081             LQUOTA_FLAG(qctl->qc_dqblk.dqb_itime) & LQUOTA_FLAG_DEFAULT) {
7082                 use_default_for_file = true;
7083                 qctl->qc_dqblk.dqb_itime &= LQUOTA_GRACE_MASK;
7084         }
7085
7086         if ((qctl->qc_cmd == LUSTRE_Q_GETQUOTA ||
7087              qctl->qc_cmd == LUSTRE_Q_GETDEFAULT) && !quiet)
7088                 print_quota_title(name, qctl, human_readable, show_default);
7089
7090         if (rc1 && *obd_type)
7091                 fprintf(stderr, "%s %s ", obd_type, obd_uuid);
7092
7093         if (qctl->qc_valid != QC_GENERAL)
7094                 mnt = "";
7095
7096         inacc = (qctl->qc_cmd == LUSTRE_Q_GETQUOTA) &&
7097                 ((qctl->qc_dqblk.dqb_valid & (QIF_LIMITS|QIF_USAGE)) !=
7098                  (QIF_LIMITS|QIF_USAGE));
7099
7100         print_quota(mnt, qctl, QC_GENERAL, rc1, human_readable, show_default);
7101
7102         if (!show_default && verbose &&
7103             qctl->qc_valid == QC_GENERAL && qctl->qc_cmd != LUSTRE_Q_GETINFO) {
7104                 char strbuf[STRBUF_LEN];
7105
7106                 rc2 = print_obd_quota(mnt, qctl, 1, human_readable,
7107                                       &total_ialloc);
7108                 rc3 = print_obd_quota(mnt, qctl, 0, human_readable,
7109                                       &total_balloc);
7110                 kbytes2str(total_balloc, strbuf, sizeof(strbuf),
7111                            human_readable);
7112                 printf("Total allocated inode limit: %ju, total "
7113                        "allocated block limit: %s\n", (uintmax_t)total_ialloc,
7114                        strbuf);
7115         }
7116
7117         if (use_default_for_blk)
7118                 printf("%cid %u is using default block quota setting\n",
7119                        *qtype_name(qctl->qc_type), qctl->qc_id);
7120
7121         if (use_default_for_file)
7122                 printf("%cid %u is using default file quota setting\n",
7123                        *qtype_name(qctl->qc_type), qctl->qc_id);
7124
7125         if (rc1 || rc2 || rc3 || inacc)
7126                 printf("Some errors happened when getting quota info. "
7127                        "Some devices may be not working or deactivated. "
7128                        "The data in \"[]\" is inaccurate.\n");
7129 out:
7130         return rc1;
7131
7132 }
7133
7134 static int lfs_project(int argc, char **argv)
7135 {
7136         int ret = 0, err = 0, c, i;
7137         struct project_handle_control phc = { 0 };
7138         enum lfs_project_ops_t op;
7139
7140         phc.newline = true;
7141         phc.assign_projid = false;
7142         /* default action */
7143         op = LFS_PROJECT_LIST;
7144
7145         while ((c = getopt(argc, argv, "p:cCsdkr0")) != -1) {
7146                 switch (c) {
7147                 case 'c':
7148                         if (op != LFS_PROJECT_LIST) {
7149                                 fprintf(stderr,
7150                                         "%s: cannot specify '-c' '-C' '-s' together\n",
7151                                         progname);
7152                                 return CMD_HELP;
7153                         }
7154
7155                         op = LFS_PROJECT_CHECK;
7156                         break;
7157                 case 'C':
7158                         if (op != LFS_PROJECT_LIST) {
7159                                 fprintf(stderr,
7160                                         "%s: cannot specify '-c' '-C' '-s' together\n",
7161                                         progname);
7162                                 return CMD_HELP;
7163                         }
7164
7165                         op = LFS_PROJECT_CLEAR;
7166                         break;
7167                 case 's':
7168                         if (op != LFS_PROJECT_LIST) {
7169                                 fprintf(stderr,
7170                                         "%s: cannot specify '-c' '-C' '-s' together\n",
7171                                         progname);
7172                                 return CMD_HELP;
7173                         }
7174
7175                         phc.set_inherit = true;
7176                         op = LFS_PROJECT_SET;
7177                         break;
7178                 case 'd':
7179                         phc.dironly = true;
7180                         break;
7181                 case 'k':
7182                         phc.keep_projid = true;
7183                         break;
7184                 case 'r':
7185                         phc.recursive = true;
7186                         break;
7187                 case 'p':
7188                         phc.projid = strtoul(optarg, NULL, 0);
7189                         phc.assign_projid = true;
7190
7191                         break;
7192                 case '0':
7193                         phc.newline = false;
7194                         break;
7195                 default:
7196                         fprintf(stderr, "%s: invalid option '%c'\n",
7197                                 progname, optopt);
7198                         return CMD_HELP;
7199                 }
7200         }
7201
7202         if (phc.assign_projid && op == LFS_PROJECT_LIST) {
7203                 op = LFS_PROJECT_SET;
7204                 phc.set_projid = true;
7205         } else if (phc.assign_projid && op == LFS_PROJECT_SET) {
7206                 phc.set_projid = true;
7207         }
7208
7209         switch (op) {
7210         case LFS_PROJECT_CHECK:
7211                 if (phc.keep_projid) {
7212                         fprintf(stderr,
7213                                 "%s: '-k' is useless together with '-c'\n",
7214                                 progname);
7215                         return CMD_HELP;
7216                 }
7217                 break;
7218         case LFS_PROJECT_CLEAR:
7219                 if (!phc.newline) {
7220                         fprintf(stderr,
7221                                 "%s: '-0' is useless together with '-C'\n",
7222                                 progname);
7223                         return CMD_HELP;
7224                 }
7225                 if (phc.assign_projid) {
7226                         fprintf(stderr,
7227                                 "%s: '-p' is useless together with '-C'\n",
7228                                 progname);
7229                         return CMD_HELP;
7230                 }
7231                 break;
7232         case LFS_PROJECT_SET:
7233                 if (!phc.newline) {
7234                         fprintf(stderr,
7235                                 "%s: '-0' is useless together with '-s'\n",
7236                                 progname);
7237                         return CMD_HELP;
7238                 }
7239                 if (phc.keep_projid) {
7240                         fprintf(stderr,
7241                                 "%s: '-k' is useless together with '-s'\n",
7242                                 progname);
7243                         return CMD_HELP;
7244                 }
7245                 break;
7246         default:
7247                 if (!phc.newline) {
7248                         fprintf(stderr,
7249                                 "%s: '-0' is useless for list operations\n",
7250                                 progname);
7251                         return CMD_HELP;
7252                 }
7253                 break;
7254         }
7255
7256         argv += optind;
7257         argc -= optind;
7258         if (argc == 0) {
7259                 fprintf(stderr, "%s: missing file or directory target(s)\n",
7260                         progname);
7261                 return CMD_HELP;
7262         }
7263
7264         for (i = 0; i < argc; i++) {
7265                 switch (op) {
7266                 case LFS_PROJECT_CHECK:
7267                         err = lfs_project_check(argv[i], &phc);
7268                         break;
7269                 case LFS_PROJECT_LIST:
7270                         err = lfs_project_list(argv[i], &phc);
7271                         break;
7272                 case LFS_PROJECT_CLEAR:
7273                         err = lfs_project_clear(argv[i], &phc);
7274                         break;
7275                 case LFS_PROJECT_SET:
7276                         err = lfs_project_set(argv[i], &phc);
7277                         break;
7278                 default:
7279                         break;
7280                 }
7281                 if (err && !ret)
7282                         ret = err;
7283         }
7284
7285         return ret;
7286 }
7287
7288 static int lfs_quota(int argc, char **argv)
7289 {
7290         int c;
7291         char *mnt, *name = NULL;
7292         struct if_quotactl qctl = { .qc_cmd = LUSTRE_Q_GETQUOTA,
7293                                     .qc_type = ALLQUOTA };
7294         char *obd_uuid = (char *)qctl.obd_uuid.uuid;
7295         int rc = 0, rc1 = 0, verbose = 0, quiet = 0;
7296         char *endptr;
7297         __u32 valid = QC_GENERAL, idx = 0;
7298         bool human_readable = false;
7299         bool show_default = false;
7300         int qtype;
7301
7302         while ((c = getopt(argc, argv, "gGi:I:o:pPqtuUvh")) != -1) {
7303                 switch (c) {
7304                 case 'U':
7305                         show_default = true;
7306                 case 'u':
7307                         qtype = USRQUOTA;
7308                         goto quota_type;
7309                 case 'G':
7310                         show_default = true;
7311                 case 'g':
7312                         qtype = GRPQUOTA;
7313                         goto quota_type;
7314                 case 'P':
7315                         show_default = true;
7316                 case 'p':
7317                         qtype = PRJQUOTA;
7318 quota_type:
7319                         if (qctl.qc_type != ALLQUOTA) {
7320                                 fprintf(stderr,
7321                                         "%s quota: only one of -u, -g, or -p may be specified\n",
7322                                         progname);
7323                                 return CMD_HELP;
7324                         }
7325                         qctl.qc_type = qtype;
7326                         break;
7327                 case 't':
7328                         qctl.qc_cmd = LUSTRE_Q_GETINFO;
7329                         break;
7330                 case 'o':
7331                         valid = qctl.qc_valid = QC_UUID;
7332                         snprintf(obd_uuid, sizeof(qctl.obd_uuid), "%s", optarg);
7333                         break;
7334                 case 'i':
7335                         valid = qctl.qc_valid = QC_MDTIDX;
7336                         idx = qctl.qc_idx = atoi(optarg);
7337                         if (idx == 0 && *optarg != '0') {
7338                                 fprintf(stderr,
7339                                         "%s quota: invalid MDT index '%s'\n",
7340                                         progname, optarg);
7341                                 return CMD_HELP;
7342                         }
7343                         break;
7344                 case 'I':
7345                         valid = qctl.qc_valid = QC_OSTIDX;
7346                         idx = qctl.qc_idx = atoi(optarg);
7347                         if (idx == 0 && *optarg != '0') {
7348                                 fprintf(stderr,
7349                                         "%s quota: invalid OST index '%s'\n",
7350                                         progname, optarg);
7351                                 return CMD_HELP;
7352                         }
7353                         break;
7354                 case 'v':
7355                         verbose = 1;
7356                         break;
7357                 case 'q':
7358                         quiet = 1;
7359                         break;
7360                 case 'h':
7361                         human_readable = true;
7362                         break;
7363                 default:
7364                         fprintf(stderr, "%s quota: unrecognized option '%s'\n",
7365                                 progname, argv[optind - 1]);
7366                         return CMD_HELP;
7367                 }
7368         }
7369
7370         /* current uid/gid info for "lfs quota /path/to/lustre/mount" */
7371         if (qctl.qc_cmd == LUSTRE_Q_GETQUOTA && qctl.qc_type == ALLQUOTA &&
7372             optind == argc - 1 && !show_default) {
7373
7374                 qctl.qc_cmd = LUSTRE_Q_GETQUOTA;
7375                 qctl.qc_idx = idx;
7376
7377                 for (qtype = USRQUOTA; qtype <= GRPQUOTA; qtype++) {
7378                         qctl.qc_type = qtype;
7379                         qctl.qc_valid = valid;
7380                         if (qtype == USRQUOTA) {
7381                                 qctl.qc_id = geteuid();
7382                                 rc = uid2name(&name, qctl.qc_id);
7383                         } else {
7384                                 qctl.qc_id = getegid();
7385                                 rc = gid2name(&name, qctl.qc_id);
7386                                 memset(&qctl.qc_dqblk, 0,
7387                                        sizeof(qctl.qc_dqblk));
7388                         }
7389                         if (rc)
7390                                 name = "<unknown>";
7391                         mnt = argv[optind];
7392                         rc1 = get_print_quota(mnt, name, &qctl, verbose, quiet,
7393                                               human_readable, show_default);
7394                         if (rc1 && !rc)
7395                                 rc = rc1;
7396                 }
7397                 return rc;
7398         /* lfs quota -u username /path/to/lustre/mount */
7399         } else if (qctl.qc_cmd == LUSTRE_Q_GETQUOTA) {
7400                 /* options should be followed by u/g-name and mntpoint */
7401                 if ((!show_default && optind + 2 != argc) ||
7402                     (show_default && optind + 1 != argc) ||
7403                     qctl.qc_type == ALLQUOTA) {
7404                         fprintf(stderr,
7405                                 "%s quota: name and mount point must be specified\n",
7406                                 progname);
7407                         return CMD_HELP;
7408                 }
7409
7410                 if (!show_default) {
7411                         name = argv[optind++];
7412                         switch (qctl.qc_type) {
7413                         case USRQUOTA:
7414                                 rc = name2uid(&qctl.qc_id, name);
7415                                 break;
7416                         case GRPQUOTA:
7417                                 rc = name2gid(&qctl.qc_id, name);
7418                                 break;
7419                         case PRJQUOTA:
7420                                 rc = name2projid(&qctl.qc_id, name);
7421                                 break;
7422                         default:
7423                                 rc = -ENOTSUP;
7424                                 break;
7425                         }
7426                 } else {
7427                         qctl.qc_valid = QC_GENERAL;
7428                         qctl.qc_cmd = LUSTRE_Q_GETDEFAULT;
7429                         qctl.qc_id = 0;
7430                 }
7431
7432                 if (rc) {
7433                         qctl.qc_id = strtoul(name, &endptr, 10);
7434                         if (*endptr != '\0') {
7435                                 fprintf(stderr, "%s quota: invalid id '%s'\n",
7436                                         progname, name);
7437                                 return CMD_HELP;
7438                         }
7439                 }
7440         } else if (optind + 1 != argc || qctl.qc_type == ALLQUOTA) {
7441                 fprintf(stderr, "%s quota: missing quota info argument(s)\n",
7442                         progname);
7443                 return CMD_HELP;
7444         }
7445
7446         mnt = argv[optind];
7447         rc = get_print_quota(mnt, name, &qctl, verbose, quiet,
7448                              human_readable, show_default);
7449         return rc;
7450 }
7451 #endif /* HAVE_SYS_QUOTA_H! */
7452
7453 static int flushctx_ioctl(char *mp)
7454 {
7455         int fd, rc;
7456
7457         fd = open(mp, O_RDONLY);
7458         if (fd == -1) {
7459                 fprintf(stderr, "flushctx: error open %s: %s\n",
7460                         mp, strerror(errno));
7461                 return -1;
7462         }
7463
7464         rc = ioctl(fd, LL_IOC_FLUSHCTX);
7465         if (rc == -1)
7466                 fprintf(stderr, "flushctx: error ioctl %s: %s\n",
7467                         mp, strerror(errno));
7468
7469         close(fd);
7470         return rc;
7471 }
7472
7473 static int lfs_flushctx(int argc, char **argv)
7474 {
7475         int     kdestroy = 0, c;
7476         char    mntdir[PATH_MAX] = {'\0'};
7477         int     index = 0;
7478         int     rc = 0;
7479
7480         while ((c = getopt(argc, argv, "k")) != -1) {
7481                 switch (c) {
7482                 case 'k':
7483                         kdestroy = 1;
7484                         break;
7485                 default:
7486                         fprintf(stderr, "error: %s: option '-%c' "
7487                                         "unrecognized\n", argv[0], c);
7488                         return CMD_HELP;
7489                 }
7490         }
7491
7492         if (kdestroy) {
7493             if ((rc = system("kdestroy > /dev/null")) != 0) {
7494                 rc = WEXITSTATUS(rc);
7495                 fprintf(stderr, "error destroying tickets: %d, continuing\n", rc);
7496             }
7497         }
7498
7499         if (optind >= argc) {
7500                 /* flush for all mounted lustre fs. */
7501                 while (!llapi_search_mounts(NULL, index++, mntdir, NULL)) {
7502                         /* Check if we have a mount point */
7503                         if (mntdir[0] == '\0')
7504                                 continue;
7505
7506                         if (flushctx_ioctl(mntdir))
7507                                 rc = -1;
7508
7509                         mntdir[0] = '\0'; /* avoid matching in next loop */
7510                 }
7511         } else {
7512                 /* flush fs as specified */
7513                 while (optind < argc) {
7514                         if (flushctx_ioctl(argv[optind++]))
7515                                 rc = -1;
7516                 }
7517         }
7518         return rc;
7519 }
7520
7521 static int lfs_changelog(int argc, char **argv)
7522 {
7523         void *changelog_priv;
7524         struct changelog_rec *rec;
7525         long long startrec = 0, endrec = 0;
7526         char *mdd;
7527         struct option long_opts[] = {
7528                 { .val = 'f', .name = "follow", .has_arg = no_argument },
7529                 { .name = NULL } };
7530         char short_opts[] = "f";
7531         int rc, follow = 0;
7532
7533         while ((rc = getopt_long(argc, argv, short_opts,
7534                 long_opts, NULL)) != -1) {
7535                 switch (rc) {
7536                 case 'f':
7537                         follow++;
7538                         break;
7539                 default:
7540                         fprintf(stderr,
7541                                 "%s changelog: unrecognized option '%s'\n",
7542                                 progname, argv[optind - 1]);
7543                         return CMD_HELP;
7544                 }
7545         }
7546         if (optind >= argc) {
7547                 fprintf(stderr, "%s changelog: mdtname must be specified\n",
7548                         progname);
7549                 return CMD_HELP;
7550         }
7551
7552         mdd = argv[optind++];
7553         if (argc > optind)
7554                 startrec = strtoll(argv[optind++], NULL, 10);
7555         if (argc > optind)
7556                 endrec = strtoll(argv[optind++], NULL, 10);
7557
7558         rc = llapi_changelog_start(&changelog_priv,
7559                                    CHANGELOG_FLAG_BLOCK |
7560                                    CHANGELOG_FLAG_JOBID |
7561                                    CHANGELOG_FLAG_EXTRA_FLAGS |
7562                                    (follow ? CHANGELOG_FLAG_FOLLOW : 0),
7563                                    mdd, startrec);
7564         if (rc < 0) {
7565                 fprintf(stderr, "%s changelog: cannot start changelog: %s\n",
7566                         progname, strerror(errno = -rc));
7567                 return rc;
7568         }
7569
7570         rc = llapi_changelog_set_xflags(changelog_priv,
7571                                         CHANGELOG_EXTRA_FLAG_UIDGID |
7572                                         CHANGELOG_EXTRA_FLAG_NID |
7573                                         CHANGELOG_EXTRA_FLAG_OMODE |
7574                                         CHANGELOG_EXTRA_FLAG_XATTR);
7575         if (rc < 0) {
7576                 fprintf(stderr,
7577                         "%s changelog: cannot set xflags for changelog: %s\n",
7578                         progname, strerror(errno = -rc));
7579                 return rc;
7580         }
7581
7582         while ((rc = llapi_changelog_recv(changelog_priv, &rec)) == 0) {
7583                 time_t secs;
7584                 struct tm ts;
7585
7586                 if (endrec && rec->cr_index > endrec) {
7587                         llapi_changelog_free(&rec);
7588                         break;
7589                 }
7590                 if (rec->cr_index < startrec) {
7591                         llapi_changelog_free(&rec);
7592                         continue;
7593                 }
7594
7595                 secs = rec->cr_time >> 30;
7596                 gmtime_r(&secs, &ts);
7597                 printf("%ju %02d%-5s %02d:%02d:%02d.%09d %04d.%02d.%02d "
7598                        "0x%x t="DFID, (uintmax_t)rec->cr_index, rec->cr_type,
7599                        changelog_type2str(rec->cr_type),
7600                        ts.tm_hour, ts.tm_min, ts.tm_sec,
7601                        (int)(rec->cr_time & ((1 << 30) - 1)),
7602                        ts.tm_year + 1900, ts.tm_mon + 1, ts.tm_mday,
7603                        rec->cr_flags & CLF_FLAGMASK, PFID(&rec->cr_tfid));
7604
7605                 if (rec->cr_flags & CLF_JOBID) {
7606                         struct changelog_ext_jobid *jid =
7607                                 changelog_rec_jobid(rec);
7608
7609                         if (jid->cr_jobid[0] != '\0')
7610                                 printf(" j=%s", jid->cr_jobid);
7611                 }
7612
7613                 if (rec->cr_flags & CLF_EXTRA_FLAGS) {
7614                         struct changelog_ext_extra_flags *ef =
7615                                 changelog_rec_extra_flags(rec);
7616
7617                         printf(" ef=0x%llx",
7618                                (unsigned long long)ef->cr_extra_flags);
7619
7620                         if (ef->cr_extra_flags & CLFE_UIDGID) {
7621                                 struct changelog_ext_uidgid *uidgid =
7622                                         changelog_rec_uidgid(rec);
7623
7624                                 printf(" u=%llu:%llu",
7625                                        (unsigned long long)uidgid->cr_uid,
7626                                        (unsigned long long)uidgid->cr_gid);
7627                         }
7628                         if (ef->cr_extra_flags & CLFE_NID) {
7629                                 struct changelog_ext_nid *nid =
7630                                         changelog_rec_nid(rec);
7631
7632                                 printf(" nid=%s",
7633                                        libcfs_nid2str(nid->cr_nid));
7634                         }
7635
7636                         if (ef->cr_extra_flags & CLFE_OPEN) {
7637                                 struct changelog_ext_openmode *omd =
7638                                         changelog_rec_openmode(rec);
7639                                 char mode[] = "---";
7640
7641                                 /* exec mode must be exclusive */
7642                                 if (omd->cr_openflags & MDS_FMODE_EXEC) {
7643                                         mode[2] = 'x';
7644                                 } else {
7645                                         if (omd->cr_openflags & MDS_FMODE_READ)
7646                                                 mode[0] = 'r';
7647                                         if (omd->cr_openflags &
7648                                             (MDS_FMODE_WRITE |
7649                                              MDS_OPEN_TRUNC |
7650                                              MDS_OPEN_APPEND))
7651                                                 mode[1] = 'w';
7652                                 }
7653
7654                                 if (strcmp(mode, "---") != 0)
7655                                         printf(" m=%s", mode);
7656
7657                         }
7658
7659                         if (ef->cr_extra_flags & CLFE_XATTR) {
7660                                 struct changelog_ext_xattr *xattr =
7661                                         changelog_rec_xattr(rec);
7662
7663                                 if (xattr->cr_xattr[0] != '\0')
7664                                         printf(" x=%s", xattr->cr_xattr);
7665                         }
7666                 }
7667
7668                 if (rec->cr_namelen)
7669                         printf(" p="DFID" %.*s", PFID(&rec->cr_pfid),
7670                                rec->cr_namelen, changelog_rec_name(rec));
7671
7672                 if (rec->cr_flags & CLF_RENAME) {
7673                         struct changelog_ext_rename *rnm =
7674                                 changelog_rec_rename(rec);
7675
7676                         if (!fid_is_zero(&rnm->cr_sfid))
7677                                 printf(" s="DFID" sp="DFID" %.*s",
7678                                        PFID(&rnm->cr_sfid),
7679                                        PFID(&rnm->cr_spfid),
7680                                        (int)changelog_rec_snamelen(rec),
7681                                        changelog_rec_sname(rec));
7682                 }
7683                 printf("\n");
7684
7685                 llapi_changelog_free(&rec);
7686         }
7687
7688         llapi_changelog_fini(&changelog_priv);
7689
7690         if (rc < 0)
7691                 fprintf(stderr, "%s changelog: cannot access changelog: %s\n",
7692                         progname, strerror(errno = -rc));
7693
7694         return (rc == 1 ? 0 : rc);
7695 }
7696
7697 static int lfs_changelog_clear(int argc, char **argv)
7698 {
7699         long long endrec;
7700         int rc;
7701
7702         if (argc != 4)
7703                 return CMD_HELP;
7704
7705         endrec = strtoll(argv[3], NULL, 10);
7706
7707         rc = llapi_changelog_clear(argv[1], argv[2], endrec);
7708
7709         if (rc == -EINVAL)
7710                 fprintf(stderr, "%s: record out of range: %llu\n",
7711                         argv[0], endrec);
7712         else if (rc == -ENOENT)
7713                 fprintf(stderr, "%s: no changelog user: %s\n",
7714                         argv[0], argv[2]);
7715         else if (rc)
7716                 fprintf(stderr, "%s error: %s\n", argv[0],
7717                         strerror(-rc));
7718
7719         if (rc)
7720                 errno = -rc;
7721
7722         return rc;
7723 }
7724
7725 static int lfs_fid2path(int argc, char **argv)
7726 {
7727         struct option long_opts[] = {
7728                 { .val = 'c',   .name = "cur",  .has_arg = no_argument },
7729                 { .val = 'l',   .name = "link", .has_arg = required_argument },
7730                 { .val = 'r',   .name = "rec",  .has_arg = required_argument },
7731                 { .name = NULL } };
7732         char  short_opts[] = "cl:r:";
7733         char *device, *fid, *path;
7734         long long recno = -1;
7735         int linkno = -1;
7736         int lnktmp;
7737         int printcur = 0;
7738         int rc = 0;
7739         char *endptr = NULL;
7740
7741         while ((rc = getopt_long(argc, argv, short_opts,
7742                 long_opts, NULL)) != -1) {
7743                 switch (rc) {
7744                 case 'c':
7745                         printcur++;
7746                         break;
7747                 case 'l':
7748                         linkno = strtol(optarg, &endptr, 10);
7749                         if (*endptr != '\0') {
7750                                 fprintf(stderr,
7751                                         "%s fid2path: invalid linkno '%s'\n",
7752                                         progname, optarg);
7753                                 return CMD_HELP;
7754                         }
7755                         break;
7756                 case 'r':
7757                         recno = strtoll(optarg, &endptr, 10);
7758                         if (*endptr != '\0') {
7759                                 fprintf(stderr,
7760                                         "%s fid2path: invalid recno '%s'\n",
7761                                         progname, optarg);
7762                                 return CMD_HELP;
7763                         }
7764                         break;
7765                 default:
7766                         fprintf(stderr,
7767                                 "%s fid2path: unrecognized option '%s'\n",
7768                                 progname, argv[optind - 1]);
7769                         return CMD_HELP;
7770                 }
7771         }
7772
7773         if (argc < 3) {
7774                 fprintf(stderr,
7775                         "%s fid2path: <fsname|rootpath> and <fid>... must be specified\n",
7776                         progname);
7777                 return CMD_HELP;
7778         }
7779
7780         device = argv[optind++];
7781         path = calloc(1, PATH_MAX);
7782         if (path == NULL) {
7783                 rc = -errno;
7784                 fprintf(stderr,
7785                         "%s fid2path: cannot allocate memory for path: %s\n",
7786                         progname, strerror(-rc));
7787                 return rc;
7788         }
7789
7790         rc = 0;
7791         while (optind < argc) {
7792                 fid = argv[optind++];
7793
7794                 lnktmp = (linkno >= 0) ? linkno : 0;
7795                 while (1) {
7796                         int oldtmp = lnktmp;
7797                         long long rectmp = recno;
7798                         int rc2;
7799                         rc2 = llapi_fid2path(device, fid, path, PATH_MAX,
7800                                              &rectmp, &lnktmp);
7801                         if (rc2 < 0) {
7802                                 fprintf(stderr,
7803                                         "%s fid2path: cannot find '%s': %s\n",
7804                                         progname, fid, strerror(errno = -rc2));
7805                                 if (rc == 0)
7806                                         rc = rc2;
7807                                 break;
7808                         }
7809
7810                         if (printcur)
7811                                 fprintf(stdout, "%lld ", rectmp);
7812                         if (device[0] == '/') {
7813                                 fprintf(stdout, "%s", device);
7814                                 if (device[strlen(device) - 1] != '/')
7815                                         fprintf(stdout, "/");
7816                         } else if (path[0] == '\0') {
7817                                 fprintf(stdout, "/");
7818                         }
7819                         fprintf(stdout, "%s\n", path);
7820
7821                         if (linkno >= 0)
7822                                 /* specified linkno */
7823                                 break;
7824                         if (oldtmp == lnktmp)
7825                                 /* no more links */
7826                                 break;
7827                 }
7828         }
7829
7830         free(path);
7831         return rc;
7832 }
7833
7834 static int lfs_path2fid(int argc, char **argv)
7835 {
7836         struct option long_opts[] = {
7837                 { .val = 'p', .name = "parents", .has_arg = no_argument },
7838                 { .name = NULL } };
7839         char            **path;
7840         const char        short_opts[] = "p";
7841         const char       *sep = "";
7842         struct lu_fid     fid;
7843         int               rc = 0;
7844         bool              show_parents = false;
7845
7846         while ((rc = getopt_long(argc, argv, short_opts,
7847                                  long_opts, NULL)) != -1) {
7848                 switch (rc) {
7849                 case 'p':
7850                         show_parents = true;
7851                         break;
7852                 default:
7853                         fprintf(stderr,
7854                                 "%s path2fid: unrecognized option '%s'\n",
7855                                 progname, argv[optind - 1]);
7856                         return CMD_HELP;
7857                 }
7858         }
7859
7860         if (optind > argc - 1) {
7861                 fprintf(stderr, "%s path2fid: FILE... must be specified\n",
7862                         progname);
7863                 return CMD_HELP;
7864         }
7865         else if (optind < argc - 1)
7866                 sep = ": ";
7867
7868         rc = 0;
7869         for (path = argv + optind; *path != NULL; path++) {
7870                 int err = 0;
7871                 if (!show_parents) {
7872                         err = llapi_path2fid(*path, &fid);
7873                         if (!err)
7874                                 printf("%s%s"DFID"\n",
7875                                        *sep != '\0' ? *path : "", sep,
7876                                        PFID(&fid));
7877                 } else {
7878                         char            name[NAME_MAX + 1];
7879                         unsigned int    linkno = 0;
7880
7881                         while ((err = llapi_path2parent(*path, linkno, &fid,
7882                                                 name, sizeof(name))) == 0) {
7883                                 if (*sep != '\0' && linkno == 0)
7884                                         printf("%s%s", *path, sep);
7885
7886                                 printf("%s"DFID"/%s", linkno != 0 ? "\t" : "",
7887                                        PFID(&fid), name);
7888                                 linkno++;
7889                         }
7890
7891                         /* err == -ENODATA is end-of-loop */
7892                         if (linkno > 0 && err == -ENODATA) {
7893                                 printf("\n");
7894                                 err = 0;
7895                         }
7896                 }
7897
7898                 if (err) {
7899                         fprintf(stderr,
7900                                 "%s path2fid: cannot get %sfid for '%s': %s\n",
7901                                 progname, show_parents ? "parent " : "", *path,
7902                                 strerror(-err));
7903                         if (rc == 0) {
7904                                 rc = err;
7905                                 errno = -err;
7906                         }
7907                 }
7908         }
7909
7910         return rc;
7911 }
7912
7913 #define MAX_ERRNO       4095
7914 #define IS_ERR_VALUE(x) ((unsigned long)(x) >= (unsigned long)-MAX_ERRNO)
7915
7916 static int lfs_rmfid_and_show_errors(const char *device, struct fid_array *fa)
7917 {
7918         int rc, rc2 = 0, k;
7919
7920         rc = llapi_rmfid(device, fa);
7921         if (rc) {
7922                 fprintf(stderr, "rmfid(): rc = %d\n", rc);
7923                 return rc;
7924         }
7925
7926         for (k = 0; k < fa->fa_nr; k++) {
7927                 rc = (__s32)fa->fa_fids[k].f_ver;
7928                 if (!IS_ERR_VALUE(rc))
7929                         continue;
7930                 if (!rc2 && rc)
7931                         rc2 = rc;
7932                 if (!rc)
7933                         continue;
7934                 fa->fa_fids[k].f_ver = 0;
7935                 fprintf(stderr, "rmfid("DFID"): rc = %d\n",
7936                         PFID(&fa->fa_fids[k]), rc);
7937         }
7938
7939         return rc2;
7940 }
7941
7942 static int lfs_rmfid(int argc, char **argv)
7943 {
7944         char *fidstr, *device;
7945         int rc = 0, rc2, nr;
7946         struct fid_array *fa;
7947
7948         if (optind > argc - 1) {
7949                 fprintf(stderr, "%s rmfid: missing dirname\n", progname);
7950                 return CMD_HELP;
7951         }
7952
7953         device = argv[optind++];
7954
7955         nr = argc - optind;
7956         fa = malloc(offsetof(struct fid_array, fa_fids[nr + 1]));
7957         if (fa == NULL)
7958                 return -ENOMEM;
7959
7960         fa->fa_nr = 0;
7961         rc = 0;
7962         while (optind < argc) {
7963                 int found;
7964
7965                 fidstr = argv[optind++];
7966                 while (*fidstr == '[')
7967                         fidstr++;
7968                 found = sscanf(fidstr, SFID, RFID(&fa->fa_fids[fa->fa_nr]));
7969                 if (found != 3) {
7970                         fprintf(stderr, "unrecognized FID: %s\n",
7971                                 argv[optind - 1]);
7972                         exit(1);
7973                 }
7974                 fa->fa_nr++;
7975                 if (fa->fa_nr == OBD_MAX_FIDS_IN_ARRAY) {
7976                         /* start another batch */
7977                         rc2 = lfs_rmfid_and_show_errors(device, fa);
7978                         if (rc2 && !rc)
7979                                 rc = rc2;
7980                         fa->fa_nr = 0;
7981                 }
7982         }
7983         if (fa->fa_nr) {
7984                 rc2 = lfs_rmfid_and_show_errors(device, fa);
7985                 if (rc2 && !rc)
7986                         rc = rc2;
7987         }
7988
7989         return rc;
7990 }
7991
7992 static int lfs_data_version(int argc, char **argv)
7993 {
7994         char *path;
7995         __u64 data_version;
7996         int fd;
7997         int rc;
7998         int c;
7999         int data_version_flags = LL_DV_RD_FLUSH; /* Read by default */
8000
8001         if (argc < 2) {
8002                 fprintf(stderr, "%s data_version: FILE must be specified\n",
8003                         progname);
8004                 return CMD_HELP;
8005         }
8006
8007         while ((c = getopt(argc, argv, "nrw")) != -1) {
8008                 switch (c) {
8009                 case 'n':
8010                         data_version_flags = 0;
8011                         break;
8012                 case 'r':
8013                         data_version_flags |= LL_DV_RD_FLUSH;
8014                         break;
8015                 case 'w':
8016                         data_version_flags |= LL_DV_WR_FLUSH;
8017                         break;
8018                 default:
8019                         fprintf(stderr,
8020                                 "%s data_version: unrecognized option '%s'\n",
8021                                 progname, argv[optind - 1]);
8022                         return CMD_HELP;
8023                 }
8024         }
8025         if (optind == argc) {
8026                 fprintf(stderr, "%s data_version: FILE must be specified\n",
8027                         progname);
8028                 return CMD_HELP;
8029         }
8030
8031         path = argv[optind];
8032         fd = open(path, O_RDONLY);
8033         if (fd < 0) {
8034                 rc = -errno;
8035                 fprintf(stderr, "%s data_version: cannot open file '%s': %s\n",
8036                         progname, path, strerror(-rc));
8037                 return rc;
8038         }
8039
8040         rc = llapi_get_data_version(fd, &data_version, data_version_flags);
8041         if (rc < 0)
8042                 fprintf(stderr,
8043                         "%s data_version: cannot get version for '%s': %s\n",
8044                         progname, path, strerror(-rc));
8045         else
8046                 printf("%ju" "\n", (uintmax_t)data_version);
8047
8048         close(fd);
8049         return rc;
8050 }
8051
8052 static int lfs_hsm_state(int argc, char **argv)
8053 {
8054         int rc;
8055         int i = 1;
8056         char *path;
8057         struct hsm_user_state hus;
8058
8059         if (argc < 2)
8060                 return CMD_HELP;
8061
8062         do {
8063                 path = argv[i];
8064
8065                 rc = llapi_hsm_state_get(path, &hus);
8066                 if (rc) {
8067                         fprintf(stderr, "can't get hsm state for %s: %s\n",
8068                                 path, strerror(errno = -rc));
8069                         return rc;
8070                 }
8071
8072                 /* Display path name and status flags */
8073                 printf("%s: (0x%08x)", path, hus.hus_states);
8074
8075                 if (hus.hus_states & HS_RELEASED)
8076                         printf(" released");
8077                 if (hus.hus_states & HS_EXISTS)
8078                         printf(" exists");
8079                 if (hus.hus_states & HS_DIRTY)
8080                         printf(" dirty");
8081                 if (hus.hus_states & HS_ARCHIVED)
8082                         printf(" archived");
8083                 /* Display user-settable flags */
8084                 if (hus.hus_states & HS_NORELEASE)
8085                         printf(" never_release");
8086                 if (hus.hus_states & HS_NOARCHIVE)
8087                         printf(" never_archive");
8088                 if (hus.hus_states & HS_LOST)
8089                         printf(" lost_from_hsm");
8090
8091                 if (hus.hus_archive_id != 0)
8092                         printf(", archive_id:%d", hus.hus_archive_id);
8093                 printf("\n");
8094
8095         } while (++i < argc);
8096
8097         return 0;
8098 }
8099
8100 #define LFS_HSM_SET   0
8101 #define LFS_HSM_CLEAR 1
8102
8103 /**
8104  * Generic function to set or clear HSM flags.
8105  * Used by hsm_set and hsm_clear.
8106  *
8107  * @mode  if LFS_HSM_SET, set the flags, if LFS_HSM_CLEAR, clear the flags.
8108  */
8109 static int lfs_hsm_change_flags(int argc, char **argv, int mode)
8110 {
8111         struct option long_opts[] = {
8112         { .val = 'A',   .name = "archived",     .has_arg = no_argument },
8113         { .val = 'a',   .name = "noarchive",    .has_arg = no_argument },
8114         { .val = 'd',   .name = "dirty",        .has_arg = no_argument },
8115         { .val = 'e',   .name = "exists",       .has_arg = no_argument },
8116         { .val = 'l',   .name = "lost",         .has_arg = no_argument },
8117         { .val = 'r',   .name = "norelease",    .has_arg = no_argument },
8118         { .val = 'i',   .name = "archive-id",   .has_arg = required_argument },
8119         { .name = NULL } };
8120         char short_opts[] = "lraAdei:";
8121         __u64 mask = 0;
8122         int c, rc;
8123         char *path;
8124         __u32 archive_id = 0;
8125         char *end = NULL;
8126
8127         if (argc < 3)
8128                 return CMD_HELP;
8129
8130         while ((c = getopt_long(argc, argv, short_opts,
8131                                 long_opts, NULL)) != -1) {
8132                 switch (c) {
8133                 case 'l':
8134                         mask |= HS_LOST;
8135                         break;
8136                 case 'a':
8137                         mask |= HS_NOARCHIVE;
8138                         break;
8139                 case 'A':
8140                         mask |= HS_ARCHIVED;
8141                         break;
8142                 case 'r':
8143                         mask |= HS_NORELEASE;
8144                         break;
8145                 case 'd':
8146                         mask |= HS_DIRTY;
8147                         break;
8148                 case 'e':
8149                         mask |= HS_EXISTS;
8150                         break;
8151                 case 'i':
8152                         archive_id = strtol(optarg, &end, 10);
8153                         if (*end != '\0') {
8154                                 fprintf(stderr, "invalid archive_id: '%s'\n",
8155                                         end);
8156                                 return CMD_HELP;
8157                         }
8158                         break;
8159                 case '?':
8160                         return CMD_HELP;
8161                 default:
8162                         fprintf(stderr, "error: %s: option '%s' unrecognized\n",
8163                                 argv[0], argv[optind - 1]);
8164                         return CMD_HELP;
8165                 }
8166         }
8167
8168         /* User should have specified a flag */
8169         if (mask == 0)
8170                 return CMD_HELP;
8171
8172         while (optind < argc) {
8173
8174                 path = argv[optind];
8175
8176                 /* If mode == 0, this means we apply the mask. */
8177                 if (mode == LFS_HSM_SET)
8178                         rc = llapi_hsm_state_set(path, mask, 0, archive_id);
8179                 else
8180                         rc = llapi_hsm_state_set(path, 0, mask, 0);
8181
8182                 if (rc != 0) {
8183                         fprintf(stderr, "Can't change hsm flags for %s: %s\n",
8184                                 path, strerror(errno = -rc));
8185                         return rc;
8186                 }
8187                 optind++;
8188         }
8189
8190         return 0;
8191 }
8192
8193 static int lfs_hsm_action(int argc, char **argv)
8194 {
8195         int                              rc;
8196         int                              i = 1;
8197         char                            *path;
8198         struct hsm_current_action        hca;
8199         struct hsm_extent                he;
8200         enum hsm_user_action             hua;
8201         enum hsm_progress_states         hps;
8202
8203         if (argc < 2)
8204                 return CMD_HELP;
8205
8206         do {
8207                 path = argv[i];
8208
8209                 rc = llapi_hsm_current_action(path, &hca);
8210                 if (rc) {
8211                         fprintf(stderr, "can't get hsm action for %s: %s\n",
8212                                 path, strerror(errno = -rc));
8213                         return rc;
8214                 }
8215                 he = hca.hca_location;
8216                 hua = hca.hca_action;
8217                 hps = hca.hca_state;
8218
8219                 printf("%s: %s", path, hsm_user_action2name(hua));
8220
8221                 /* Skip file without action */
8222                 if (hca.hca_action == HUA_NONE) {
8223                         printf("\n");
8224                         continue;
8225                 }
8226
8227                 printf(" %s ", hsm_progress_state2name(hps));
8228
8229                 if ((hps == HPS_RUNNING) &&
8230                     (hua == HUA_ARCHIVE || hua == HUA_RESTORE))
8231                         printf("(%llu bytes moved)\n",
8232                                (unsigned long long)he.length);
8233                 else if ((he.offset + he.length) == LUSTRE_EOF)
8234                         printf("(from %llu to EOF)\n",
8235                                (unsigned long long)he.offset);
8236                 else
8237                         printf("(from %llu to %llu)\n",
8238                                (unsigned long long)he.offset,
8239                                (unsigned long long)(he.offset + he.length));
8240
8241         } while (++i < argc);
8242
8243         return 0;
8244 }
8245
8246 static int lfs_hsm_set(int argc, char **argv)
8247 {
8248         return lfs_hsm_change_flags(argc, argv, LFS_HSM_SET);
8249 }
8250
8251 static int lfs_hsm_clear(int argc, char **argv)
8252 {
8253         return lfs_hsm_change_flags(argc, argv, LFS_HSM_CLEAR);
8254 }
8255
8256 /**
8257  * Check file state and return its fid, to be used by lfs_hsm_request().
8258  *
8259  * \param[in]     file      Path to file to check
8260  * \param[in,out] fid       Pointer to allocated lu_fid struct.
8261  * \param[in,out] last_dev  Pointer to last device id used.
8262  *
8263  * \return 0 on success.
8264  */
8265 static int lfs_hsm_prepare_file(const char *file, struct lu_fid *fid,
8266                                 dev_t *last_dev)
8267 {
8268         struct stat     st;
8269         int             rc;
8270
8271         rc = lstat(file, &st);
8272         if (rc) {
8273                 fprintf(stderr, "Cannot stat %s: %s\n", file, strerror(errno));
8274                 return -errno;
8275         }
8276         /* Checking for regular file as archiving as posix copytool
8277          * rejects archiving files other than regular files
8278          */
8279         if (!S_ISREG(st.st_mode)) {
8280                 fprintf(stderr, "error: \"%s\" is not a regular file\n", file);
8281                 return CMD_HELP;
8282         }
8283         /* A request should be ... */
8284         if (*last_dev != st.st_dev && *last_dev != 0) {
8285                 fprintf(stderr, "All files should be "
8286                         "on the same filesystem: %s\n", file);
8287                 return -EINVAL;
8288         }
8289         *last_dev = st.st_dev;
8290
8291         rc = llapi_path2fid(file, fid);
8292         if (rc) {
8293                 fprintf(stderr, "Cannot read FID of %s: %s\n",
8294                         file, strerror(-rc));
8295                 return rc;
8296         }
8297         return 0;
8298 }
8299
8300 /* Fill an HSM HUR item with a given file name.
8301  *
8302  * If mntpath is set, then the filename is actually a FID, and no
8303  * lookup on the filesystem will be performed.
8304  *
8305  * \param[in]  hur         the user request to fill
8306  * \param[in]  idx         index of the item inside the HUR to fill
8307  * \param[in]  mntpath     mountpoint of Lustre
8308  * \param[in]  fname       filename (if mtnpath is NULL)
8309  *                         or FID (if mntpath is set)
8310  * \param[in]  last_dev    pointer to last device id used
8311  *
8312  * \retval 0 on success
8313  * \retval CMD_HELP or a negative errno on error
8314  */
8315 static int fill_hur_item(struct hsm_user_request *hur, unsigned int idx,
8316                          const char *mntpath, const char *fname,
8317                          dev_t *last_dev)
8318 {
8319         struct hsm_user_item *hui = &hur->hur_user_item[idx];
8320         int rc;
8321
8322         hui->hui_extent.length = -1;
8323
8324         if (mntpath != NULL) {
8325                 if (*fname == '[')
8326                         fname++;
8327                 rc = sscanf(fname, SFID, RFID(&hui->hui_fid));
8328                 if (rc == 3) {
8329                         rc = 0;
8330                 } else {
8331                         fprintf(stderr, "hsm: '%s' is not a valid FID\n",
8332                                 fname);
8333                         rc = -EINVAL;
8334                 }
8335         } else {
8336                 rc = lfs_hsm_prepare_file(fname, &hui->hui_fid, last_dev);
8337         }
8338
8339         if (rc == 0)
8340                 hur->hur_request.hr_itemcount++;
8341
8342         return rc;
8343 }
8344
8345 static int lfs_hsm_request(int argc, char **argv, int action)
8346 {
8347         struct option long_opts[] = {
8348         { .val = 'a',   .name = "archive",      .has_arg = required_argument },
8349         { .val = 'D',   .name = "data",         .has_arg = required_argument },
8350         { .val = 'l',   .name = "filelist",     .has_arg = required_argument },
8351         { .val = 'm',   .name = "mntpath",      .has_arg = required_argument },
8352         { .name = NULL } };
8353         dev_t                    last_dev = 0;
8354         char                     short_opts[] = "l:D:a:m:";
8355         struct hsm_user_request *hur, *oldhur;
8356         int                      c, i;
8357         size_t                   len;
8358         int                      nbfile;
8359         char                    *line = NULL;
8360         char                    *filelist = NULL;
8361         char                     fullpath[PATH_MAX];
8362         char                    *opaque = NULL;
8363         int                      opaque_len = 0;
8364         int                      archive_id = 0;
8365         FILE                    *fp;
8366         int                      nbfile_alloc = 0;
8367         char                    *some_file = NULL;
8368         char                    *mntpath = NULL;
8369         int                      rc;
8370
8371         if (argc < 2)
8372                 return CMD_HELP;
8373
8374         while ((c = getopt_long(argc, argv, short_opts,
8375                                 long_opts, NULL)) != -1) {
8376                 switch (c) {
8377                 case 'l':
8378                         filelist = optarg;
8379                         break;
8380                 case 'D':
8381                         opaque = optarg;
8382                         break;
8383                 case 'a':
8384                         if (action != HUA_ARCHIVE &&
8385                             action != HUA_REMOVE) {
8386                                 fprintf(stderr,
8387                                         "error: -a is supported only "
8388                                         "when archiving or removing\n");
8389                                 return CMD_HELP;
8390                         }
8391                         archive_id = atoi(optarg);
8392                         break;
8393                 case 'm':
8394                         if (some_file == NULL) {
8395                                 mntpath = optarg;
8396                                 some_file = strdup(optarg);
8397                         }
8398                         break;
8399                 case '?':
8400                         return CMD_HELP;
8401                 default:
8402                         fprintf(stderr, "error: %s: option '%s' unrecognized\n",
8403                                 argv[0], argv[optind - 1]);
8404                         return CMD_HELP;
8405                 }
8406         }
8407
8408         /* All remaining args are files, so we have at least nbfile */
8409         nbfile = argc - optind;
8410
8411         if ((nbfile == 0) && (filelist == NULL))
8412                 return CMD_HELP;
8413
8414         if (opaque != NULL)
8415                 opaque_len = strlen(opaque);
8416
8417         /* Alloc the request structure with enough place to store all files
8418          * from command line. */
8419         hur = llapi_hsm_user_request_alloc(nbfile, opaque_len);
8420         if (hur == NULL) {
8421                 fprintf(stderr, "Cannot create the request: %s\n",
8422                         strerror(errno));
8423                 return errno;
8424         }
8425         nbfile_alloc = nbfile;
8426
8427         hur->hur_request.hr_action = action;
8428         hur->hur_request.hr_archive_id = archive_id;
8429         hur->hur_request.hr_flags = 0;
8430
8431         /* All remaining args are files, add them */
8432         if (nbfile != 0 && some_file == NULL)
8433                 some_file = strdup(argv[optind]);
8434
8435         for (i = 0; i < nbfile; i++) {
8436                 rc = fill_hur_item(hur, i, mntpath, argv[optind + i],
8437                                    &last_dev);
8438                 if (rc)
8439                         goto out_free;
8440         }
8441
8442         /* from here stop using nb_file, use hur->hur_request.hr_itemcount */
8443
8444         /* If a filelist was specified, read the filelist from it. */
8445         if (filelist != NULL) {
8446                 fp = fopen(filelist, "r");
8447                 if (fp == NULL) {
8448                         fprintf(stderr, "Cannot read the file list %s: %s\n",
8449                                 filelist, strerror(errno));
8450                         rc = -errno;
8451                         goto out_free;
8452                 }
8453
8454                 while ((rc = getline(&line, &len, fp)) != -1) {
8455                         /* If allocated buffer was too small, get something
8456                          * larger */
8457                         if (nbfile_alloc <= hur->hur_request.hr_itemcount) {
8458                                 ssize_t size;
8459
8460                                 nbfile_alloc = nbfile_alloc * 2 + 1;
8461                                 oldhur = hur;
8462                                 hur = llapi_hsm_user_request_alloc(nbfile_alloc,
8463                                                                    opaque_len);
8464                                 if (hur == NULL) {
8465                                         fprintf(stderr, "hsm: cannot allocate "
8466                                                 "the request: %s\n",
8467                                                 strerror(errno));
8468                                         hur = oldhur;
8469                                         rc = -errno;
8470                                         fclose(fp);
8471                                         goto out_free;
8472                                 }
8473                                 size = hur_len(oldhur);
8474                                 if (size < 0) {
8475                                         fprintf(stderr, "hsm: cannot allocate "
8476                                                 "%u files + %u bytes data\n",
8477                                             oldhur->hur_request.hr_itemcount,
8478                                             oldhur->hur_request.hr_data_len);
8479                                         free(hur);
8480                                         hur = oldhur;
8481                                         rc = -E2BIG;
8482                                         fclose(fp);
8483                                         goto out_free;
8484                                 }
8485                                 memcpy(hur, oldhur, size);
8486                                 free(oldhur);
8487                         }
8488
8489                         /* Chop CR */
8490                         if (line[strlen(line) - 1] == '\n')
8491                                 line[strlen(line) - 1] = '\0';
8492
8493                         rc = fill_hur_item(hur, hur->hur_request.hr_itemcount,
8494                                            mntpath, line, &last_dev);
8495                         if (rc) {
8496                                 fclose(fp);
8497                                 goto out_free;
8498                         }
8499
8500                         if (some_file == NULL) {
8501                                 some_file = line;
8502                                 line = NULL;
8503                         }
8504                 }
8505
8506                 rc = fclose(fp);
8507                 free(line);
8508         }
8509
8510         /* If a --data was used, add it to the request */
8511         hur->hur_request.hr_data_len = opaque_len;
8512         if (opaque != NULL)
8513                 memcpy(hur_data(hur), opaque, opaque_len);
8514
8515         /* Send the HSM request */
8516         if (realpath(some_file, fullpath) == NULL) {
8517                 fprintf(stderr, "Could not find path '%s': %s\n",
8518                         some_file, strerror(errno));
8519         }
8520         rc = llapi_hsm_request(fullpath, hur);
8521         if (rc) {
8522                 fprintf(stderr, "Cannot send HSM request (use of %s): %s\n",
8523                         some_file, strerror(-rc));
8524                 goto out_free;
8525         }
8526
8527 out_free:
8528         free(some_file);
8529         free(hur);
8530         return rc;
8531 }
8532
8533 static int lfs_hsm_archive(int argc, char **argv)
8534 {
8535         return lfs_hsm_request(argc, argv, HUA_ARCHIVE);
8536 }
8537
8538 static int lfs_hsm_restore(int argc, char **argv)
8539 {
8540         return lfs_hsm_request(argc, argv, HUA_RESTORE);
8541 }
8542
8543 static int lfs_hsm_release(int argc, char **argv)
8544 {
8545         return lfs_hsm_request(argc, argv, HUA_RELEASE);
8546 }
8547
8548 static int lfs_hsm_remove(int argc, char **argv)
8549 {
8550         return lfs_hsm_request(argc, argv, HUA_REMOVE);
8551 }
8552
8553 static int lfs_hsm_cancel(int argc, char **argv)
8554 {
8555         return lfs_hsm_request(argc, argv, HUA_CANCEL);
8556 }
8557
8558 static int lfs_swap_layouts(int argc, char **argv)
8559 {
8560         if (argc != 3)
8561                 return CMD_HELP;
8562
8563         return llapi_swap_layouts(argv[1], argv[2], 0, 0,
8564                                   SWAP_LAYOUTS_KEEP_MTIME |
8565                                   SWAP_LAYOUTS_KEEP_ATIME);
8566 }
8567
8568 static const char *const ladvise_names[] = LU_LADVISE_NAMES;
8569
8570 static const char *const lock_mode_names[] = LOCK_MODE_NAMES;
8571
8572 int lfs_get_mode(const char *string)
8573 {
8574         enum lock_mode_user mode;
8575
8576         for (mode = 0; mode < ARRAY_SIZE(lock_mode_names); mode++) {
8577                 if (lock_mode_names[mode] == NULL)
8578                         continue;
8579                 if (strcmp(string, lock_mode_names[mode]) == 0)
8580                         return mode;
8581         }
8582
8583         return -EINVAL;
8584 }
8585
8586 static enum lu_ladvise_type lfs_get_ladvice(const char *string)
8587 {
8588         enum lu_ladvise_type advice;
8589
8590         for (advice = 0;
8591              advice < ARRAY_SIZE(ladvise_names); advice++) {
8592                 if (ladvise_names[advice] == NULL)
8593                         continue;
8594                 if (strcmp(string, ladvise_names[advice]) == 0)
8595                         return advice;
8596         }
8597
8598         return LU_LADVISE_INVALID;
8599 }
8600
8601 static int lfs_ladvise(int argc, char **argv)
8602 {
8603         struct option long_opts[] = {
8604         { .val = 'a',   .name = "advice",       .has_arg = required_argument },
8605         { .val = 'b',   .name = "background",   .has_arg = no_argument },
8606         { .val = 'e',   .name = "end",          .has_arg = required_argument },
8607         { .val = 'l',   .name = "length",       .has_arg = required_argument },
8608         { .val = 'm',   .name = "mode",         .has_arg = required_argument },
8609         { .val = 's',   .name = "start",        .has_arg = required_argument },
8610         { .val = 'u',   .name = "unset",        .has_arg = no_argument },
8611         { .name = NULL } };
8612         char                     short_opts[] = "a:be:l:m:s:u";
8613         int                      c;
8614         int                      rc = 0;
8615         const char              *path;
8616         int                      fd;
8617         struct llapi_lu_ladvise  advice;
8618         enum lu_ladvise_type     advice_type = LU_LADVISE_INVALID;
8619         unsigned long long       start = 0;
8620         unsigned long long       end = LUSTRE_EOF;
8621         unsigned long long       length = 0;
8622         unsigned long long       size_units;
8623         unsigned long long       flags = 0;
8624         int                      mode = 0;
8625
8626         optind = 0;
8627         while ((c = getopt_long(argc, argv, short_opts,
8628                                 long_opts, NULL)) != -1) {
8629                 switch (c) {
8630                 case 'a':
8631                         advice_type = lfs_get_ladvice(optarg);
8632                         if (advice_type == LU_LADVISE_INVALID) {
8633                                 fprintf(stderr, "%s: invalid advice type "
8634                                         "'%s'\n", argv[0], optarg);
8635                                 fprintf(stderr, "Valid types:");
8636
8637                                 for (advice_type = 0;
8638                                      advice_type < ARRAY_SIZE(ladvise_names);
8639                                      advice_type++) {
8640                                         if (ladvise_names[advice_type] == NULL)
8641                                                 continue;
8642                                         fprintf(stderr, " %s",
8643                                                 ladvise_names[advice_type]);
8644                                 }
8645                                 fprintf(stderr, "\n");
8646
8647                                 return CMD_HELP;
8648                         }
8649                         break;
8650                 case 'b':
8651                         flags |= LF_ASYNC;
8652                         break;
8653                 case 'u':
8654                         flags |= LF_UNSET;
8655                         break;
8656                 case 'e':
8657                         size_units = 1;
8658                         rc = llapi_parse_size(optarg, &end,
8659                                               &size_units, 0);
8660                         if (rc) {
8661                                 fprintf(stderr, "%s: bad end offset '%s'\n",
8662                                         argv[0], optarg);
8663                                 return CMD_HELP;
8664                         }
8665                         break;
8666                 case 's':
8667                         size_units = 1;
8668                         rc = llapi_parse_size(optarg, &start,
8669                                               &size_units, 0);
8670                         if (rc) {
8671                                 fprintf(stderr, "%s: bad start offset "
8672                                         "'%s'\n", argv[0], optarg);
8673                                 return CMD_HELP;
8674                         }
8675                         break;
8676                 case 'l':
8677                         size_units = 1;
8678                         rc = llapi_parse_size(optarg, &length,
8679                                               &size_units, 0);
8680                         if (rc) {
8681                                 fprintf(stderr, "%s: bad length '%s'\n",
8682                                         argv[0], optarg);
8683                                 return CMD_HELP;
8684                         }
8685                         break;
8686                 case 'm':
8687                         mode = lfs_get_mode(optarg);
8688                         if (mode < 0) {
8689                                 fprintf(stderr, "%s: bad mode '%s', valid "
8690                                                  "modes are READ or WRITE\n",
8691                                         argv[0], optarg);
8692                                 return CMD_HELP;
8693                         }
8694                         break;
8695                 case '?':
8696                         return CMD_HELP;
8697                 default:
8698                         fprintf(stderr, "%s: option '%s' unrecognized\n",
8699                                 argv[0], argv[optind - 1]);
8700                         return CMD_HELP;
8701                 }
8702         }
8703
8704         if (advice_type == LU_LADVISE_INVALID) {
8705                 fprintf(stderr, "%s: please give an advice type\n", argv[0]);
8706                 fprintf(stderr, "Valid types:");
8707                 for (advice_type = 0; advice_type < ARRAY_SIZE(ladvise_names);
8708                      advice_type++) {
8709                         if (ladvise_names[advice_type] == NULL)
8710                                 continue;
8711                         fprintf(stderr, " %s", ladvise_names[advice_type]);
8712                 }
8713                 fprintf(stderr, "\n");
8714                 return CMD_HELP;
8715         }
8716
8717         if (advice_type == LU_LADVISE_LOCKNOEXPAND) {
8718                 fprintf(stderr, "%s: Lock no expand advice is a per file "
8719                                  "descriptor advice, so when called from lfs, "
8720                                  "it does nothing.\n", argv[0]);
8721                 return CMD_HELP;
8722         }
8723
8724         if (argc <= optind) {
8725                 fprintf(stderr, "%s: please give one or more file names\n",
8726                         argv[0]);
8727                 return CMD_HELP;
8728         }
8729
8730         if (end != LUSTRE_EOF && length != 0 && end != start + length) {
8731                 fprintf(stderr, "%s: conflicting arguments of -l and -e\n",
8732                         argv[0]);
8733                 return CMD_HELP;
8734         }
8735
8736         if (end == LUSTRE_EOF && length != 0)
8737                 end = start + length;
8738
8739         if (end <= start) {
8740                 fprintf(stderr, "%s: range [%llu, %llu] is invalid\n",
8741                         argv[0], start, end);
8742                 return CMD_HELP;
8743         }
8744
8745         if (advice_type != LU_LADVISE_LOCKAHEAD && mode != 0) {
8746                 fprintf(stderr, "%s: mode is only valid with lockahead\n",
8747                         argv[0]);
8748                 return CMD_HELP;
8749         }
8750
8751         if (advice_type == LU_LADVISE_LOCKAHEAD && mode == 0) {
8752                 fprintf(stderr, "%s: mode is required with lockahead\n",
8753                         argv[0]);
8754                 return CMD_HELP;
8755         }
8756
8757         while (optind < argc) {
8758                 int rc2;
8759
8760                 path = argv[optind++];
8761
8762                 fd = open(path, O_RDONLY);
8763                 if (fd < 0) {
8764                         fprintf(stderr, "%s: cannot open file '%s': %s\n",
8765                                 argv[0], path, strerror(errno));
8766                         rc2 = -errno;
8767                         goto next;
8768                 }
8769
8770                 advice.lla_start = start;
8771                 advice.lla_end = end;
8772                 advice.lla_advice = advice_type;
8773                 advice.lla_value1 = 0;
8774                 advice.lla_value2 = 0;
8775                 advice.lla_value3 = 0;
8776                 advice.lla_value4 = 0;
8777                 if (advice_type == LU_LADVISE_LOCKAHEAD) {
8778                         advice.lla_lockahead_mode = mode;
8779                         advice.lla_peradvice_flags = flags;
8780                 }
8781
8782                 rc2 = llapi_ladvise(fd, flags, 1, &advice);
8783                 close(fd);
8784                 if (rc2 < 0) {
8785                         fprintf(stderr, "%s: cannot give advice '%s' to file "
8786                                 "'%s': %s\n", argv[0],
8787                                 ladvise_names[advice_type],
8788                                 path, strerror(errno));
8789
8790                         goto next;
8791                 }
8792
8793 next:
8794                 if (rc == 0 && rc2 < 0)
8795                         rc = rc2;
8796         }
8797         return rc;
8798 }
8799
8800 static const char *const heat_names[] = LU_HEAT_NAMES;
8801
8802 static int lfs_heat_get(int argc, char **argv)
8803 {
8804         struct lu_heat *heat;
8805         int rc = 0, rc2;
8806         char *path;
8807         int fd;
8808         int i;
8809
8810         if (argc <= 1)
8811                 return CMD_HELP;
8812
8813         heat = calloc(sizeof(*heat) + sizeof(__u64) * OBD_HEAT_COUNT, 1);
8814         if (!heat) {
8815                 fprintf(stderr, "%s: memory allocation failed\n", argv[0]);
8816                 return -ENOMEM;
8817         }
8818
8819         optind = 1;
8820         while (optind < argc) {
8821                 path = argv[optind++];
8822
8823                 fd = open(path, O_RDONLY);
8824                 if (fd < 0) {
8825                         fprintf(stderr, "%s: cannot open file '%s': %s\n",
8826                                 argv[0], path, strerror(errno));
8827                         rc2 = -errno;
8828                         goto next;
8829                 }
8830
8831                 heat->lh_count = OBD_HEAT_COUNT;
8832                 rc2 = llapi_heat_get(fd, heat);
8833                 close(fd);
8834                 if (rc2 < 0) {
8835                         fprintf(stderr, "%s: cannot get heat of file '%s'"
8836                                 ": %s\n", argv[0], path, strerror(errno));
8837                         goto next;
8838                 }
8839
8840                 printf("flags: %x\n", heat->lh_flags);
8841                 for (i = 0; i < heat->lh_count; i++)
8842                         printf("%s: %llu\n", heat_names[i],
8843                                (unsigned long long)heat->lh_heat[i]);
8844 next:
8845                 if (rc == 0 && rc2 < 0)
8846                         rc = rc2;
8847         }
8848
8849         free(heat);
8850         return rc;
8851 }
8852
8853 static int lfs_heat_set(int argc, char **argv)
8854 {
8855         struct option long_opts[] = {
8856         { .val = 'c',   .name = "clear",        .has_arg = no_argument },
8857         { .val = 'o',   .name = "off",          .has_arg = no_argument },
8858         { .val = 'O',   .name = "on",           .has_arg = no_argument },
8859         { .name = NULL } };
8860         enum lu_heat_flag flags = 0;
8861         int rc = 0, rc2;
8862         char *path;
8863         int fd;
8864         int c;
8865
8866         if (argc <= 1)
8867                 return CMD_HELP;
8868
8869         optind = 0;
8870         while ((c = getopt_long(argc, argv, "coO", long_opts, NULL)) != -1) {
8871                 switch (c) {
8872                 case 'c':
8873                         flags |= LU_HEAT_FLAG_CLEAR;
8874                         break;
8875                 case 'o':
8876                         flags |= LU_HEAT_FLAG_CLEAR;
8877                         flags |= LU_HEAT_FLAG_OFF;
8878                         break;
8879                 case 'O':
8880                         flags &= ~LU_HEAT_FLAG_OFF;
8881                         break;
8882                 case '?':
8883                         return CMD_HELP;
8884                 default:
8885                         fprintf(stderr, "%s: option '%s' unrecognized\n",
8886                                 argv[0], argv[optind - 1]);
8887                         return CMD_HELP;
8888                 }
8889         }
8890
8891         if (argc <= optind) {
8892                 fprintf(stderr, "%s: please give one or more file names\n",
8893                         argv[0]);
8894                 return CMD_HELP;
8895         }
8896
8897         while (optind < argc) {
8898                 path = argv[optind++];
8899
8900                 fd = open(path, O_RDONLY);
8901                 if (fd < 0) {
8902                         fprintf(stderr, "%s: cannot open file '%s': %s\n",
8903                                 argv[0], path, strerror(errno));
8904                         rc2 = -errno;
8905                         goto next;
8906                 }
8907
8908                 rc2 = llapi_heat_set(fd, flags);
8909                 close(fd);
8910                 if (rc2 < 0) {
8911                         fprintf(stderr, "%s: cannot setflags heat of file '%s'"
8912                                 ": %s\n", argv[0], path, strerror(errno));
8913                         goto next;
8914                 }
8915 next:
8916                 if (rc == 0 && rc2 < 0)
8917                         rc = rc2;
8918         }
8919         return rc;
8920 }
8921
8922 /** The input string contains a comma delimited list of component ids and
8923  * ranges, for example "1,2-4,7".
8924  */
8925 static int parse_mirror_ids(__u16 *ids, int size, char *arg)
8926 {
8927         bool end_of_loop = false;
8928         char *ptr = NULL;
8929         int nr = 0;
8930         int rc;
8931
8932         if (arg == NULL)
8933                 return -EINVAL;
8934
8935         while (!end_of_loop) {
8936                 int start_index;
8937                 int end_index;
8938                 int i;
8939                 char *endptr = NULL;
8940
8941                 rc = -EINVAL;
8942                 ptr = strchrnul(arg, ',');
8943                 end_of_loop = *ptr == '\0';
8944                 *ptr = '\0';
8945
8946                 start_index = strtol(arg, &endptr, 0);
8947                 if (endptr == arg) /* no data at all */
8948                         break;
8949                 if (*endptr != '-' && *endptr != '\0') /* has invalid data */
8950                         break;
8951                 if (start_index < 0)
8952                         break;
8953
8954                 end_index = start_index;
8955                 if (*endptr == '-') {
8956                         end_index = strtol(endptr + 1, &endptr, 0);
8957                         if (*endptr != '\0')
8958                                 break;
8959                         if (end_index < start_index)
8960                                 break;
8961                 }
8962
8963                 for (i = start_index; i <= end_index && size > 0; i++) {
8964                         int j;
8965
8966                         /* remove duplicate */
8967                         for (j = 0; j < nr; j++) {
8968                                 if (ids[j] == i)
8969                                         break;
8970                         }
8971                         if (j == nr) { /* no duplicate */
8972                                 ids[nr++] = i;
8973                                 --size;
8974                         }
8975                 }
8976
8977                 if (size == 0 && i < end_index)
8978                         break;
8979
8980                 *ptr = ',';
8981                 arg = ++ptr;
8982                 rc = 0;
8983         }
8984         if (!end_of_loop && ptr != NULL)
8985                 *ptr = ',';
8986
8987         return rc < 0 ? rc : nr;
8988 }
8989
8990 /**
8991  * struct verify_mirror_id - Mirror id to be verified.
8992  * @mirror_id:   A specified mirror id.
8993  * @is_valid_id: @mirror_id is valid or not in the mirrored file.
8994  */
8995 struct verify_mirror_id {
8996         __u16 mirror_id;
8997         bool is_valid_id;
8998 };
8999
9000 /**
9001  * compare_mirror_ids() - Compare mirror ids.
9002  * @layout: Mirror component list.
9003  * @cbdata: Callback data in verify_mirror_id structure.
9004  *
9005  * This is a callback function called by llapi_layout_comp_iterate()
9006  * to compare the specified mirror id with the one in the current
9007  * component of @layout. If they are the same, then the specified
9008  * mirror id is valid.
9009  *
9010  * Return: a negative error code on failure or
9011  *         LLAPI_LAYOUT_ITER_CONT: Proceed iteration
9012  *         LLAPI_LAYOUT_ITER_STOP: Stop iteration
9013  */
9014 static inline
9015 int compare_mirror_ids(struct llapi_layout *layout, void *cbdata)
9016 {
9017         struct verify_mirror_id *mirror_id_cbdata =
9018                                  (struct verify_mirror_id *)cbdata;
9019         uint32_t mirror_id;
9020         int rc = 0;
9021
9022         rc = llapi_layout_mirror_id_get(layout, &mirror_id);
9023         if (rc < 0) {
9024                 rc = -errno;
9025                 fprintf(stderr,
9026                         "%s: llapi_layout_mirror_id_get failed: %s.\n",
9027                         progname, strerror(errno));
9028                 return rc;
9029         }
9030
9031         if (mirror_id_cbdata->mirror_id == mirror_id) {
9032                 mirror_id_cbdata->is_valid_id = true;
9033                 return LLAPI_LAYOUT_ITER_STOP;
9034         }
9035
9036         return LLAPI_LAYOUT_ITER_CONT;
9037 }
9038
9039 /**
9040  * verify_mirror_ids() - Verify specified mirror ids.
9041  * @fname:      Mirrored file name.
9042  * @mirror_ids: Specified mirror ids to be verified.
9043  * @ids_nr:     Number of specified mirror ids.
9044  *
9045  * This function verifies that specified @mirror_ids are valid
9046  * in the mirrored file @fname.
9047  *
9048  * Return: 0 on success or a negative error code on failure.
9049  */
9050 static inline
9051 int verify_mirror_ids(const char *fname, __u16 *mirror_ids, int ids_nr)
9052 {
9053         struct llapi_layout *layout = NULL;
9054         struct verify_mirror_id mirror_id_cbdata = { 0 };
9055         struct stat stbuf;
9056         uint32_t flr_state;
9057         int i;
9058         int fd;
9059         int rc = 0;
9060         int rc2 = 0;
9061
9062         if (ids_nr <= 0)
9063                 return -EINVAL;
9064
9065         if (stat(fname, &stbuf) < 0) {
9066                 fprintf(stderr, "%s: cannot stat file '%s': %s.\n",
9067                         progname, fname, strerror(errno));
9068                 rc = -errno;
9069                 goto error;
9070         }
9071
9072         if (!S_ISREG(stbuf.st_mode)) {
9073                 fprintf(stderr, "%s: '%s' is not a regular file.\n",
9074                         progname, fname);
9075                 rc = -EINVAL;
9076                 goto error;
9077         }
9078
9079         fd = open(fname, O_DIRECT | O_RDONLY);
9080         if (fd < 0) {
9081                 fprintf(stderr, "%s: cannot open '%s': %s.\n",
9082                         progname, fname, strerror(errno));
9083                 rc = -errno;
9084                 goto error;
9085         }
9086
9087         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
9088         if (rc < 0) {
9089                 fprintf(stderr, "%s: '%s' llapi_lease_acquire failed: %s.\n",
9090                         progname, fname, strerror(errno));
9091                 goto close_fd;
9092         }
9093
9094         layout = llapi_layout_get_by_fd(fd, 0);
9095         if (layout == NULL) {
9096                 fprintf(stderr, "%s: '%s' llapi_layout_get_by_fd failed: %s.\n",
9097                         progname, fname, strerror(errno));
9098                 rc = -errno;
9099                 llapi_lease_release(fd);
9100                 goto close_fd;
9101         }
9102
9103         rc = llapi_layout_flags_get(layout, &flr_state);
9104         if (rc < 0) {
9105                 fprintf(stderr, "%s: '%s' llapi_layout_flags_get failed: %s.\n",
9106                         progname, fname, strerror(errno));
9107                 rc = -errno;
9108                 goto free_layout;
9109         }
9110
9111         flr_state &= LCM_FL_FLR_MASK;
9112         switch (flr_state) {
9113         case LCM_FL_NONE:
9114                 rc = -EINVAL;
9115                 fprintf(stderr, "%s: '%s' file state error: %s.\n",
9116                         progname, fname, llapi_layout_flags_string(flr_state));
9117                 goto free_layout;
9118         default:
9119                 break;
9120         }
9121
9122         rc2 = 0;
9123         for (i = 0; i < ids_nr; i++) {
9124                 mirror_id_cbdata.mirror_id = mirror_ids[i];
9125                 mirror_id_cbdata.is_valid_id = false;
9126
9127                 rc = llapi_layout_comp_iterate(layout, compare_mirror_ids,
9128                                                &mirror_id_cbdata);
9129                 if (rc < 0) {
9130                         rc = -errno;
9131                         fprintf(stderr,
9132                                 "%s: '%s' failed to verify mirror id: %u.\n",
9133                                 progname, fname, mirror_ids[i]);
9134                         goto free_layout;
9135                 }
9136
9137                 if (!mirror_id_cbdata.is_valid_id) {
9138                         rc2 = -EINVAL;
9139                         fprintf(stderr,
9140                                 "%s: '%s' invalid specified mirror id: %u.\n",
9141                                 progname, fname, mirror_ids[i]);
9142                 }
9143         }
9144         rc = rc2;
9145
9146 free_layout:
9147         llapi_layout_free(layout);
9148         llapi_lease_release(fd);
9149 close_fd:
9150         close(fd);
9151 error:
9152         return rc;
9153 }
9154
9155 static inline
9156 int lfs_mirror_resync_file(const char *fname, struct ll_ioc_lease *ioc,
9157                            __u16 *mirror_ids, int ids_nr)
9158 {
9159         struct llapi_resync_comp comp_array[1024] = { { 0 } };
9160         struct llapi_layout *layout;
9161         struct stat stbuf;
9162         uint32_t flr_state;
9163         uint64_t start;
9164         uint64_t end;
9165         int comp_size = 0;
9166         int idx;
9167         int fd;
9168         int rc;
9169         int rc2;
9170
9171         if (stat(fname, &stbuf) < 0) {
9172                 fprintf(stderr, "%s: cannot stat file '%s': %s.\n",
9173                         progname, fname, strerror(errno));
9174                 rc = -errno;
9175                 goto error;
9176         }
9177         if (!S_ISREG(stbuf.st_mode)) {
9178                 fprintf(stderr, "%s: '%s' is not a regular file.\n",
9179                         progname, fname);
9180                 rc = -EINVAL;
9181                 goto error;
9182         }
9183
9184         fd = open(fname, O_DIRECT | O_RDWR);
9185         if (fd < 0) {
9186                 fprintf(stderr, "%s: cannot open '%s': %s.\n",
9187                         progname, fname, strerror(errno));
9188                 rc = -errno;
9189                 goto error;
9190         }
9191
9192         layout = llapi_layout_get_by_fd(fd, 0);
9193         if (layout == NULL) {
9194                 fprintf(stderr, "%s: '%s' llapi_layout_get_by_fd failed: %s.\n",
9195                         progname, fname, strerror(errno));
9196                 rc = -errno;
9197                 goto close_fd;
9198         }
9199
9200         rc = llapi_layout_flags_get(layout, &flr_state);
9201         if (rc) {
9202                 fprintf(stderr, "%s: '%s' llapi_layout_flags_get failed: %s.\n",
9203                         progname, fname, strerror(errno));
9204                 rc = -errno;
9205                 goto free_layout;
9206         }
9207
9208         flr_state &= LCM_FL_FLR_MASK;
9209         if (flr_state == LCM_FL_NONE) {
9210                 rc = -EINVAL;
9211                 fprintf(stderr, "%s: '%s' is not a FLR file.\n",
9212                         progname, fname);
9213                 goto free_layout;
9214         }
9215
9216         /* get stale component info */
9217         comp_size = llapi_mirror_find_stale(layout, comp_array,
9218                                             ARRAY_SIZE(comp_array),
9219                                             mirror_ids, ids_nr);
9220         if (comp_size <= 0) {
9221                 rc = comp_size;
9222                 goto free_layout;
9223         }
9224
9225         ioc->lil_mode = LL_LEASE_WRLCK;
9226         ioc->lil_flags = LL_LEASE_RESYNC;
9227         rc = llapi_lease_set(fd, ioc);
9228         if (rc < 0) {
9229                 if (rc == -EALREADY)
9230                         rc = 0;
9231                 else
9232                         fprintf(stderr,
9233                             "%s: '%s' llapi_lease_get_ext resync failed: %s.\n",
9234                                 progname, fname, strerror(-rc));
9235                 goto free_layout;
9236         }
9237
9238         /* get the read range [start, end) */
9239         start = comp_array[0].lrc_start;
9240         end = comp_array[0].lrc_end;
9241         for (idx = 1; idx < comp_size; idx++) {
9242                 if (comp_array[idx].lrc_start < start)
9243                         start = comp_array[idx].lrc_start;
9244                 if (end < comp_array[idx].lrc_end)
9245                         end = comp_array[idx].lrc_end;
9246         }
9247
9248         rc = llapi_lease_check(fd);
9249         if (rc != LL_LEASE_WRLCK) {
9250                 fprintf(stderr, "%s: '%s' lost lease lock.\n",
9251                         progname, fname);
9252                 goto free_layout;
9253         }
9254
9255         rc = llapi_mirror_resync_many(fd, layout, comp_array, comp_size,
9256                                       start, end);
9257         if (rc < 0)
9258                 fprintf(stderr, "%s: '%s' llapi_mirror_resync_many: %s.\n",
9259                         progname, fname, strerror(-rc));
9260
9261         /* need to do the lease unlock even resync fails */
9262         ioc->lil_mode = LL_LEASE_UNLCK;
9263         ioc->lil_flags = LL_LEASE_RESYNC_DONE;
9264         ioc->lil_count = 0;
9265         for (idx = 0; idx < comp_size; idx++) {
9266                 if (comp_array[idx].lrc_synced) {
9267                         ioc->lil_ids[ioc->lil_count] = comp_array[idx].lrc_id;
9268                         ioc->lil_count++;
9269                 }
9270         }
9271
9272         rc2 = llapi_lease_set(fd, ioc);
9273         /**
9274          * llapi_lease_set returns lease mode when it request to unlock
9275          * the lease lock.
9276          */
9277         if (rc2 <= 0) {
9278                 /* rc2 == 0 means lost lease lock */
9279                 if (rc2 == 0 && rc == 0)
9280                         rc = -EBUSY;
9281                 fprintf(stderr, "%s: resync file '%s' failed: %s.\n",
9282                         progname, fname,
9283                         rc2 == 0 ? "lost lease lock" : strerror(-rc2));
9284         }
9285
9286 free_layout:
9287         llapi_layout_free(layout);
9288 close_fd:
9289         close(fd);
9290 error:
9291         return rc;
9292 }
9293
9294 static inline int lfs_mirror_resync(int argc, char **argv)
9295 {
9296         struct ll_ioc_lease *ioc = NULL;
9297         __u16 mirror_ids[128] = { 0 };
9298         int ids_nr = 0;
9299         int c;
9300         int rc = 0;
9301
9302         struct option long_opts[] = {
9303         { .val = 'o',   .name = "only",         .has_arg = required_argument },
9304         { .name = NULL } };
9305
9306         while ((c = getopt_long(argc, argv, "o:", long_opts, NULL)) >= 0) {
9307                 switch (c) {
9308                 case 'o':
9309                         rc = parse_mirror_ids(mirror_ids,
9310                                         sizeof(mirror_ids) / sizeof(__u16),
9311                                         optarg);
9312                         if (rc < 0) {
9313                                 fprintf(stderr,
9314                                         "%s: bad mirror ids '%s'.\n",
9315                                         argv[0], optarg);
9316                                 goto error;
9317                         }
9318                         ids_nr = rc;
9319                         break;
9320                 default:
9321                         fprintf(stderr, "%s: options '%s' unrecognized.\n",
9322                                 argv[0], argv[optind - 1]);
9323                         rc = -EINVAL;
9324                         goto error;
9325                 }
9326         }
9327
9328         if (argc == optind) {
9329                 fprintf(stderr, "%s: no file name given.\n", argv[0]);
9330                 rc = CMD_HELP;
9331                 goto error;
9332         }
9333
9334         if (ids_nr > 0 && argc > optind + 1) {
9335                 fprintf(stderr,
9336                     "%s: option '--only' cannot be used upon multiple files.\n",
9337                         argv[0]);
9338                 rc = CMD_HELP;
9339                 goto error;
9340
9341         }
9342
9343         if (ids_nr > 0) {
9344                 rc = verify_mirror_ids(argv[optind], mirror_ids, ids_nr);
9345                 if (rc < 0)
9346                         goto error;
9347         }
9348
9349         /* set the lease on the file */
9350         ioc = calloc(sizeof(*ioc) + sizeof(__u32) * 4096, 1);
9351         if (ioc == NULL) {
9352                 fprintf(stderr, "%s: cannot alloc id array for ioc: %s.\n",
9353                         argv[0], strerror(errno));
9354                 rc = -errno;
9355                 goto error;
9356         }
9357
9358         for (; optind < argc; optind++) {
9359                 rc = lfs_mirror_resync_file(argv[optind], ioc,
9360                                             mirror_ids, ids_nr);
9361                 /* ignore previous file's error, continue with next file */
9362
9363                 /* reset ioc */
9364                 memset(ioc, 0, sizeof(*ioc) + sizeof(__u32) * 4096);
9365         }
9366
9367         free(ioc);
9368 error:
9369         return rc;
9370 }
9371
9372 static inline int verify_mirror_id_by_fd(int fd, __u16 mirror_id)
9373 {
9374         struct llapi_layout *layout;
9375         int rc;
9376
9377         layout = llapi_layout_get_by_fd(fd, 0);
9378         if (layout == NULL) {
9379                 fprintf(stderr, "could not get layout.\n");
9380                 return  -EINVAL;
9381         }
9382
9383         rc = llapi_layout_comp_iterate(layout, find_mirror_id, &mirror_id);
9384         if (rc < 0) {
9385                 fprintf(stderr, "failed to iterate layout\n");
9386                 llapi_layout_free(layout);
9387
9388                 return rc;
9389         } else if (rc == LLAPI_LAYOUT_ITER_CONT) {
9390                 fprintf(stderr, "does not find mirror with ID %u\n", mirror_id);
9391                 llapi_layout_free(layout);
9392
9393                 return -EINVAL;
9394         }
9395         llapi_layout_free(layout);
9396
9397         return 0;
9398 }
9399
9400 /**
9401  * Check whether two files are the same file
9402  * \retval      0  same file
9403  * \retval      1  not the same file
9404  * \retval      <0 error code
9405  */
9406 static inline int check_same_file(const char *f1, const char *f2)
9407 {
9408         struct stat stbuf1;
9409         struct stat stbuf2;
9410
9411         if (stat(f1, &stbuf1) < 0) {
9412                 fprintf(stderr, "%s: cannot stat file '%s': %s\n",
9413                         progname, f1, strerror(errno));
9414                 return -errno;
9415         }
9416
9417         if (stat(f2, &stbuf2) < 0) {
9418                 fprintf(stderr, "%s: cannot stat file '%s': %s\n",
9419                         progname, f2, strerror(errno));
9420                 return -errno;
9421         }
9422
9423         if (stbuf1.st_rdev == stbuf2.st_rdev &&
9424             stbuf1.st_ino == stbuf2.st_ino)
9425                 return 0;
9426
9427         return 1;
9428 }
9429
9430 static inline int lfs_mirror_read(int argc, char **argv)
9431 {
9432         int rc = CMD_HELP;
9433         __u16 mirror_id = 0;
9434         const char *outfile = NULL;
9435         char *fname;
9436         int fd = 0;
9437         int outfd;
9438         int c;
9439         void *buf;
9440         const size_t buflen = 4 << 20;
9441         off_t pos;
9442         struct option long_opts[] = {
9443         { .val = 'N',   .name = "mirror-id",    .has_arg = required_argument },
9444         { .val = 'o',   .name = "outfile",      .has_arg = required_argument },
9445         { .name = NULL } };
9446
9447         while ((c = getopt_long(argc, argv, "N:o:", long_opts, NULL)) >= 0) {
9448                 char *end;
9449
9450                 switch (c) {
9451                 case 'N':
9452                         mirror_id = strtoul(optarg, &end, 0);
9453                         if (*end != '\0' || mirror_id == 0) {
9454                                 fprintf(stderr,
9455                                         "%s %s: invalid mirror ID '%s'\n",
9456                                         progname, argv[0], optarg);
9457                                 return rc;
9458                         }
9459                         break;
9460                 case 'o':
9461                         outfile = optarg;
9462                         break;
9463                 default:
9464                         fprintf(stderr, "%s: option '%s' unrecognized.\n",
9465                                 progname, argv[optind - 1]);
9466                         return -EINVAL;
9467                 }
9468         }
9469
9470         if (argc == optind) {
9471                 fprintf(stderr, "%s %s: no mirrored file provided\n",
9472                         progname, argv[0]);
9473                 return rc;
9474         } else if (argc > optind + 1) {
9475                 fprintf(stderr, "%s %s: too many files\n", progname, argv[0]);
9476                 return rc;
9477         }
9478
9479         if (mirror_id == 0) {
9480                 fprintf(stderr, "%s %s: no valid mirror ID is provided\n",
9481                         progname, argv[0]);
9482                 return rc;
9483         }
9484
9485         /* open mirror file */
9486         fname = argv[optind];
9487
9488         if (outfile) {
9489                 rc = check_same_file(fname, outfile);
9490                 if (rc == 0) {
9491                         fprintf(stderr,
9492                         "%s %s: output file cannot be the mirrored file\n",
9493                                 progname, argv[0]);
9494                         return -EINVAL;
9495                 }
9496                 if (rc < 0)
9497                         return rc;
9498         }
9499
9500         fd = open(fname, O_DIRECT | O_RDONLY);
9501         if (fd < 0) {
9502                 fprintf(stderr, "%s %s: cannot open '%s': %s\n",
9503                         progname, argv[0], fname, strerror(errno));
9504                 return rc;
9505         }
9506
9507         /* verify mirror id */
9508         rc = verify_mirror_id_by_fd(fd, mirror_id);
9509         if (rc) {
9510                 fprintf(stderr,
9511                         "%s %s: cannot find mirror with ID %u in '%s'\n",
9512                         progname, argv[0], mirror_id, fname);
9513                 goto close_fd;
9514         }
9515
9516         /* open output file */
9517         if (outfile) {
9518                 outfd = open(outfile, O_EXCL | O_WRONLY | O_CREAT, 0644);
9519                 if (outfd < 0) {
9520                         fprintf(stderr, "%s %s: cannot create file '%s': %s\n",
9521                                 progname, argv[0], outfile, strerror(errno));
9522                         rc = -errno;
9523                         goto close_fd;
9524                 }
9525         } else {
9526                 outfd = STDOUT_FILENO;
9527         }
9528
9529         /* allocate buffer */
9530         rc = posix_memalign(&buf, sysconf(_SC_PAGESIZE), buflen);
9531         if (rc) {
9532                 fprintf(stderr, "%s %s: posix_memalign returns %d\n",
9533                                 progname, argv[0], rc);
9534                 goto close_outfd;
9535         }
9536
9537         pos = 0;
9538         while (1) {
9539                 ssize_t bytes_read;
9540                 ssize_t written = 0;
9541
9542                 bytes_read = llapi_mirror_read(fd, mirror_id, buf, buflen, pos);
9543                 if (bytes_read < 0) {
9544                         rc = bytes_read;
9545                         fprintf(stderr,
9546                                 "%s %s: fail to read data from mirror %u: %s\n",
9547                                 progname, argv[0], mirror_id, strerror(-rc));
9548                         goto free_buf;
9549                 }
9550
9551                 /* EOF reached */
9552                 if (bytes_read == 0)
9553                         break;
9554
9555                 while (written < bytes_read) {
9556                         ssize_t written2;
9557
9558                         written2 = write(outfd, buf + written,
9559                                          bytes_read - written);
9560                         if (written2 < 0) {
9561                                 fprintf(stderr,
9562                                         "%s %s: fail to write %s: %s\n",
9563                                         progname, argv[0], outfile ? : "STDOUT",
9564                                         strerror(errno));
9565                                 rc = -errno;
9566                                 goto free_buf;
9567                         }
9568                         written += written2;
9569                 }
9570
9571                 if (written != bytes_read) {
9572                         fprintf(stderr,
9573                 "%s %s: written %ld bytes does not match with %ld read.\n",
9574                                 progname, argv[0], written, bytes_read);
9575                         rc = -EIO;
9576                         goto free_buf;
9577                 }
9578
9579                 pos += bytes_read;
9580         }
9581
9582         fsync(outfd);
9583         rc = 0;
9584
9585 free_buf:
9586         free(buf);
9587 close_outfd:
9588         if (outfile)
9589                 close(outfd);
9590 close_fd:
9591         close(fd);
9592
9593         return rc;
9594 }
9595
9596 static inline int lfs_mirror_write(int argc, char **argv)
9597 {
9598         int rc = CMD_HELP;
9599         __u16 mirror_id = 0;
9600         const char *inputfile = NULL;
9601         char *fname;
9602         int fd = 0;
9603         int inputfd;
9604         int c;
9605         void *buf;
9606         const size_t buflen = 4 << 20;
9607         off_t pos;
9608         size_t page_size = sysconf(_SC_PAGESIZE);
9609         struct ll_ioc_lease_id ioc;
9610
9611         struct option long_opts[] = {
9612         { .val = 'N',   .name = "mirror-id",    .has_arg = required_argument },
9613         { .val = 'i',   .name = "inputfile",    .has_arg = required_argument },
9614         { .name = NULL } };
9615
9616         while ((c = getopt_long(argc, argv, "N:i:", long_opts, NULL)) >= 0) {
9617                 char *end;
9618
9619                 switch (c) {
9620                 case 'N':
9621                         mirror_id = strtoul(optarg, &end, 0);
9622                         if (*end != '\0' || mirror_id == 0) {
9623                                 fprintf(stderr,
9624                                         "%s %s: invalid mirror ID '%s'\n",
9625                                         progname, argv[0], optarg);
9626                                 return rc;
9627                         }
9628                         break;
9629                 case 'i':
9630                         inputfile = optarg;
9631                         break;
9632                 default:
9633                         fprintf(stderr, "%s: option '%s' unrecognized\n",
9634                                 progname, argv[optind - 1]);
9635                         return -EINVAL;
9636                 }
9637         }
9638
9639         if (argc == optind) {
9640                 fprintf(stderr, "%s %s: no mirrored file provided\n",
9641                         progname, argv[0]);
9642                 return rc;
9643         } else if (argc > optind + 1) {
9644                 fprintf(stderr, "%s %s: too many files\n", progname, argv[0]);
9645                 return rc;
9646         }
9647
9648         if (mirror_id == 0) {
9649                 fprintf(stderr, "%s %s: no valid mirror ID is provided\n",
9650                         progname, argv[0]);
9651                 return rc;
9652         }
9653
9654         /* open mirror file */
9655         fname = argv[optind];
9656
9657         if (inputfile) {
9658                 rc = check_same_file(fname, inputfile);
9659                 if (rc == 0) {
9660                         fprintf(stderr,
9661                         "%s %s: input file cannot be the mirrored file\n",
9662                                 progname, argv[0]);
9663                         return -EINVAL;
9664                 }
9665                 if (rc < 0)
9666                         return rc;
9667         }
9668
9669         fd = open(fname, O_DIRECT | O_WRONLY);
9670         if (fd < 0) {
9671                 fprintf(stderr, "%s %s: cannot open '%s': %s\n",
9672                         progname, argv[0], fname, strerror(errno));
9673                 return rc;
9674         }
9675
9676         /* verify mirror id */
9677         rc = verify_mirror_id_by_fd(fd, mirror_id);
9678         if (rc) {
9679                 fprintf(stderr,
9680                         "%s %s: cannot find mirror with ID %u in '%s'\n",
9681                         progname, argv[0], mirror_id, fname);
9682                 goto close_fd;
9683         }
9684
9685         /* open input file */
9686         if (inputfile) {
9687                 inputfd = open(inputfile, O_RDONLY, 0644);
9688                 if (inputfd < 0) {
9689                         fprintf(stderr, "%s %s: cannot open file '%s': %s\n",
9690                                 progname, argv[0], inputfile, strerror(errno));
9691                         rc = -errno;
9692                         goto close_fd;
9693                 }
9694         } else {
9695                 inputfd = STDIN_FILENO;
9696         }
9697
9698         /* allocate buffer */
9699         rc = posix_memalign(&buf, page_size, buflen);
9700         if (rc) {
9701                 fprintf(stderr, "%s %s: posix_memalign returns %d\n",
9702                         progname, argv[0], rc);
9703                 goto close_inputfd;
9704         }
9705
9706         /* prepare target mirror components instantiation */
9707         ioc.lil_mode = LL_LEASE_WRLCK;
9708         ioc.lil_flags = LL_LEASE_RESYNC;
9709         ioc.lil_mirror_id = mirror_id;
9710         rc = llapi_lease_set(fd, (struct ll_ioc_lease *)&ioc);
9711         if (rc < 0) {
9712                 fprintf(stderr,
9713                         "%s %s: '%s' llapi_lease_get_ext failed: %s\n",
9714                         progname, argv[0], fname, strerror(errno));
9715                 goto free_buf;
9716         }
9717
9718         pos = 0;
9719         while (1) {
9720                 ssize_t bytes_read;
9721                 ssize_t written;
9722                 size_t to_write;
9723
9724                 rc = llapi_lease_check(fd);
9725                 if (rc != LL_LEASE_WRLCK) {
9726                         fprintf(stderr, "%s %s: '%s' lost lease lock\n",
9727                                 progname, argv[0], fname);
9728                         goto free_buf;
9729                 }
9730
9731                 bytes_read = read(inputfd, buf, buflen);
9732                 if (bytes_read < 0) {
9733                         rc = bytes_read;
9734                         fprintf(stderr,
9735                                 "%s %s: fail to read data from '%s': %s\n",
9736                                 progname, argv[0], inputfile ? : "STDIN",
9737                                 strerror(errno));
9738                         rc = -errno;
9739                         goto free_buf;
9740                 }
9741
9742                 /* EOF reached */
9743                 if (bytes_read == 0)
9744                         break;
9745
9746                 /* round up to page align to make direct IO happy. */
9747                 to_write = (bytes_read + page_size - 1) & ~(page_size - 1);
9748
9749                 written = llapi_mirror_write(fd, mirror_id, buf, to_write,
9750                                              pos);
9751                 if (written < 0) {
9752                         rc = written;
9753                         fprintf(stderr,
9754                               "%s %s: fail to write to mirror %u: %s\n",
9755                                 progname, argv[0], mirror_id,
9756                                 strerror(-rc));
9757                         goto free_buf;
9758                 }
9759
9760                 pos += bytes_read;
9761         }
9762
9763         if (pos & (page_size - 1)) {
9764                 rc = llapi_mirror_truncate(fd, mirror_id, pos);
9765                 if (rc < 0)
9766                         goto free_buf;
9767         }
9768
9769         ioc.lil_mode = LL_LEASE_UNLCK;
9770         ioc.lil_flags = LL_LEASE_RESYNC_DONE;
9771         ioc.lil_count = 0;
9772         rc = llapi_lease_set(fd, (struct ll_ioc_lease *)&ioc);
9773         if (rc <= 0) {
9774                 if (rc == 0)
9775                         rc = -EBUSY;
9776                 fprintf(stderr,
9777                         "%s %s: release lease lock of '%s' failed: %s\n",
9778                         progname, argv[0], fname, strerror(errno));
9779                 goto free_buf;
9780         }
9781
9782         rc = 0;
9783
9784 free_buf:
9785         free(buf);
9786 close_inputfd:
9787         if (inputfile)
9788                 close(inputfd);
9789 close_fd:
9790         close(fd);
9791
9792         return rc;
9793 }
9794
9795 static inline int get_other_mirror_ids(int fd, __u16 *ids, __u16 exclude_id)
9796 {
9797         struct llapi_layout *layout;
9798         struct collect_ids_data cid = { .cid_ids = ids,
9799                                         .cid_count = 0,
9800                                         .cid_exclude = exclude_id, };
9801         int rc;
9802
9803         layout = llapi_layout_get_by_fd(fd, 0);
9804         if (layout == NULL) {
9805                 fprintf(stderr, "could not get layout\n");
9806                 return -EINVAL;
9807         }
9808
9809         rc = llapi_layout_comp_iterate(layout, collect_mirror_id, &cid);
9810         if (rc < 0) {
9811                 fprintf(stderr, "failed to iterate layout\n");
9812                 llapi_layout_free(layout);
9813
9814                 return rc;
9815         }
9816         llapi_layout_free(layout);
9817
9818         return cid.cid_count;
9819 }
9820
9821 static inline int lfs_mirror_copy(int argc, char **argv)
9822 {
9823         int rc = CMD_HELP;
9824         __u16 read_mirror_id = 0;
9825         __u16 ids[128] = { 0 };
9826         int count = 0;
9827         struct llapi_layout *layout = NULL;
9828         struct llapi_resync_comp comp_array[1024] = { { 0 } };
9829         int comp_size = 0;
9830         char *fname;
9831         int fd = 0;
9832         int c;
9833         int i;
9834         ssize_t copied;
9835         struct ll_ioc_lease *ioc = NULL;
9836         struct ll_ioc_lease_id *resync_ioc;
9837
9838         struct option long_opts[] = {
9839         { .val = 'i',   .name = "read-mirror",  .has_arg = required_argument },
9840         { .val = 'o',   .name = "write-mirror", .has_arg = required_argument },
9841         { .name = NULL } };
9842
9843         while ((c = getopt_long(argc, argv, "i:o:", long_opts, NULL)) >= 0) {
9844                 char *end;
9845
9846                 switch (c) {
9847                 case 'i':
9848                         read_mirror_id = strtoul(optarg, &end, 0);
9849                         if (*end != '\0' || read_mirror_id == 0) {
9850                                 fprintf(stderr,
9851                                         "%s %s: invalid read mirror ID '%s'\n",
9852                                         progname, argv[0], optarg);
9853                                 return rc;
9854                         }
9855                         break;
9856                 case 'o':
9857                         if (!strcmp(optarg, "-1")) {
9858                                 /* specify all other mirrors */
9859                                 ids[0] = (__u16)-1;
9860                                 count = 1;
9861                         } else {
9862                                 count = parse_mirror_ids((__u16 *)ids,
9863                                                          ARRAY_SIZE(ids),
9864                                                          optarg);
9865                                 if (count < 0)
9866                                         return rc;
9867                         }
9868                         break;
9869                 default:
9870                         fprintf(stderr, "%s: option '%s' unrecognized\n",
9871                                 progname, argv[optind - 1]);
9872                         return -EINVAL;
9873                 }
9874         }
9875
9876         if (argc == optind) {
9877                 fprintf(stderr, "%s %s: no mirrored file provided\n",
9878                         progname, argv[0]);
9879                 return rc;
9880         } else if (argc > optind + 1) {
9881                 fprintf(stderr, "%s %s: too many files\n", progname, argv[0]);
9882                 return rc;
9883         }
9884
9885         if (read_mirror_id == 0) {
9886                 fprintf(stderr,
9887                         "%s %s: no valid read mirror ID %d is provided\n",
9888                         progname, argv[0], read_mirror_id);
9889                 return rc;
9890         }
9891
9892         if (count == 0) {
9893                 fprintf(stderr,
9894                         "%s %s: no write mirror ID is provided\n",
9895                         progname, argv[0]);
9896                 return rc;
9897         }
9898
9899         for (i = 0; i < count; i++) {
9900                 if (read_mirror_id == ids[i]) {
9901                         fprintf(stderr,
9902                         "%s %s: read and write mirror ID cannot be the same\n",
9903                                 progname, argv[0]);
9904                         return rc;
9905                 }
9906         }
9907
9908         /* open mirror file */
9909         fname = argv[optind];
9910
9911         fd = open(fname, O_DIRECT | O_RDWR);
9912         if (fd < 0) {
9913                 fprintf(stderr, "%s %s: cannot open '%s': %s\n",
9914                         progname, argv[0], fname, strerror(errno));
9915                 return rc;
9916         }
9917
9918         /* write to all other mirrors */
9919         if (ids[0] == (__u16)-1) {
9920                 count = get_other_mirror_ids(fd, ids, read_mirror_id);
9921                 if (count <= 0) {
9922                         rc = count;
9923                         fprintf(stderr,
9924                         "%s %s: failed to get other mirror ids in '%s': %d\n",
9925                                 progname, argv[0], fname, rc);
9926                         goto close_fd;
9927                 }
9928         }
9929
9930         /* verify mirror id */
9931         rc = verify_mirror_id_by_fd(fd, read_mirror_id);
9932         if (rc) {
9933                 fprintf(stderr,
9934                         "%s %s: cannot find mirror with ID %u in '%s'\n",
9935                         progname, argv[0], read_mirror_id, fname);
9936                 goto close_fd;
9937         }
9938
9939         for (i = 0; i < count; i++) {
9940                 rc = verify_mirror_id_by_fd(fd, ids[i]);
9941                 if (rc) {
9942                         fprintf(stderr,
9943                         "%s %s: cannot find mirror with ID %u in '%s'\n",
9944                                 progname, argv[0], ids[i], fname);
9945                         goto close_fd;
9946                 }
9947         }
9948
9949         ioc = calloc(sizeof(*ioc) + sizeof(__u32) * 4096, 1);
9950         if (ioc == NULL) {
9951                 fprintf(stderr,
9952                         "%s %s: cannot alloc comp id array for ioc: %s\n",
9953                         progname, argv[0], strerror(errno));
9954                 rc = -errno;
9955                 goto close_fd;
9956         }
9957
9958         /* get stale component info */
9959         layout = llapi_layout_get_by_fd(fd, 0);
9960         if (layout == NULL) {
9961                 fprintf(stderr, "%s %s: failed to get layout of '%s': %s\n",
9962                         progname, argv[0], fname, strerror(errno));
9963                 rc = -errno;
9964                 goto free_ioc;
9965         }
9966         comp_size = llapi_mirror_find_stale(layout, comp_array,
9967                                             ARRAY_SIZE(comp_array),
9968                                             ids, count);
9969         llapi_layout_free(layout);
9970         if (comp_size < 0) {
9971                 rc = comp_size;
9972                 goto free_ioc;
9973         }
9974
9975         /* prepare target mirror components instantiation */
9976         resync_ioc = (struct ll_ioc_lease_id *)ioc;
9977         resync_ioc->lil_mode = LL_LEASE_WRLCK;
9978         resync_ioc->lil_flags = LL_LEASE_RESYNC;
9979         if (count == 1)
9980                 resync_ioc->lil_mirror_id = ids[0];
9981         else
9982                 resync_ioc->lil_mirror_id = read_mirror_id | MIRROR_ID_NEG;
9983         rc = llapi_lease_set(fd, ioc);
9984         if (rc < 0) {
9985                 fprintf(stderr,
9986                         "%s %s: '%s' llapi_lease_get_ext failed: %s\n",
9987                         progname, argv[0], fname, strerror(errno));
9988                 goto free_ioc;
9989         }
9990
9991         copied = llapi_mirror_copy_many(fd, read_mirror_id, ids, count);
9992         if (copied < 0) {
9993                 rc = copied;
9994                 fprintf(stderr, "%s %s: copy error: %d\n",
9995                         progname, argv[0], rc);
9996                 goto free_ioc;
9997         }
9998
9999         fprintf(stdout, "mirror copied successfully: ");
10000         for (i = 0; i < copied; i++)
10001                 fprintf(stdout, "%d ", ids[i]);
10002         fprintf(stdout, "\n");
10003
10004         ioc->lil_mode = LL_LEASE_UNLCK;
10005         ioc->lil_flags = LL_LEASE_RESYNC_DONE;
10006         ioc->lil_count = 0;
10007         for (i = 0; i < comp_size; i++) {
10008                 int j;
10009
10010                 for (j = 0; j < copied; j++) {
10011                         if (comp_array[i].lrc_mirror_id != ids[j])
10012                                 continue;
10013
10014                         ioc->lil_ids[ioc->lil_count] = comp_array[i].lrc_id;
10015                         ioc->lil_count++;
10016                 }
10017         }
10018         rc = llapi_lease_set(fd, ioc);
10019         if (rc <= 0) {
10020                 if (rc == 0)
10021                         rc = -EBUSY;
10022                 fprintf(stderr,
10023                         "%s %s: release lease lock of '%s' failed: %s\n",
10024                         progname, argv[0], fname, strerror(errno));
10025                 goto free_ioc;
10026         }
10027
10028         rc = 0;
10029
10030 free_ioc:
10031         free(ioc);
10032 close_fd:
10033         close(fd);
10034
10035         return rc;
10036 }
10037 /**
10038  * struct verify_chunk - Mirror chunk to be verified.
10039  * @chunk:        [start, end) of the chunk.
10040  * @mirror_count: Number of mirror ids in @mirror_id array.
10041  * @mirror_id:    Array of valid mirror ids that cover the chunk.
10042  */
10043 struct verify_chunk {
10044         struct lu_extent chunk;
10045         unsigned int mirror_count;
10046         __u16 mirror_id[LUSTRE_MIRROR_COUNT_MAX];
10047 };
10048
10049 /**
10050  * print_chunks() - Print chunk information.
10051  * @fname:       Mirrored file name.
10052  * @chunks:      Array of chunks.
10053  * @chunk_count: Number of chunks in @chunks array.
10054  *
10055  * This function prints [start, end) of each chunk in @chunks
10056  * for mirrored file @fname, and also prints the valid mirror ids
10057  * that cover the chunk.
10058  *
10059  * Return: void.
10060  */
10061 static inline
10062 void print_chunks(const char *fname, struct verify_chunk *chunks,
10063                   int chunk_count)
10064 {
10065         int i;
10066         int j;
10067
10068         fprintf(stdout, "Chunks to be verified in %s:\n", fname);
10069         for (i = 0; i < chunk_count; i++) {
10070                 fprintf(stdout, DEXT, PEXT(&chunks[i].chunk));
10071
10072                 if (chunks[i].mirror_count == 0)
10073                         fprintf(stdout, "\t[");
10074                 else {
10075                         fprintf(stdout, "\t[%u", chunks[i].mirror_id[0]);
10076                         for (j = 1; j < chunks[i].mirror_count; j++)
10077                                 fprintf(stdout, ", %u", chunks[i].mirror_id[j]);
10078                 }
10079                 fprintf(stdout, "]\t%u\n", chunks[i].mirror_count);
10080         }
10081         fprintf(stdout, "\n");
10082 }
10083
10084 /**
10085  * print_checksums() - Print CRC-32 checksum values.
10086  * @chunk: A chunk and its corresponding valid mirror ids.
10087  * @crc:   CRC-32 checksum values on the chunk for each valid mirror.
10088  *
10089  * This function prints CRC-32 checksum values on @chunk for
10090  * each valid mirror that covers it.
10091  *
10092  * Return: void.
10093  */
10094 static inline
10095 void print_checksums(struct verify_chunk *chunk, unsigned long *crc)
10096 {
10097         int i;
10098
10099         fprintf(stdout,
10100                 "CRC-32 checksum value for chunk "DEXT":\n",
10101                 PEXT(&chunk->chunk));
10102         for (i = 0; i < chunk->mirror_count; i++)
10103                 fprintf(stdout, "Mirror %u:\t%#lx\n",
10104                         chunk->mirror_id[i], crc[i]);
10105         fprintf(stdout, "\n");
10106 }
10107
10108 /**
10109  * filter_mirror_id() - Filter specified mirror ids.
10110  * @chunks:      Array of chunks.
10111  * @chunk_count: Number of chunks in @chunks array.
10112  * @mirror_ids:  Specified mirror ids to be verified.
10113  * @ids_nr:      Number of specified mirror ids.
10114  *
10115  * This function scans valid mirror ids that cover each chunk in @chunks
10116  * and filters specified mirror ids.
10117  *
10118  * Return: void.
10119  */
10120 static inline
10121 void filter_mirror_id(struct verify_chunk *chunks, int chunk_count,
10122                       __u16 *mirror_ids, int ids_nr)
10123 {
10124         int i;
10125         int j;
10126         int k;
10127         __u16 valid_id[LUSTRE_MIRROR_COUNT_MAX] = { 0 };
10128         unsigned int valid_count = 0;
10129
10130         for (i = 0; i < chunk_count; i++) {
10131                 if (chunks[i].mirror_count == 0)
10132                         continue;
10133
10134                 valid_count = 0;
10135                 for (j = 0; j < ids_nr; j++) {
10136                         for (k = 0; k < chunks[i].mirror_count; k++) {
10137                                 if (chunks[i].mirror_id[k] == mirror_ids[j]) {
10138                                         valid_id[valid_count] = mirror_ids[j];
10139                                         valid_count++;
10140                                         break;
10141                                 }
10142                         }
10143                 }
10144
10145                 memcpy(chunks[i].mirror_id, valid_id,
10146                        sizeof(__u16) * valid_count);
10147                 chunks[i].mirror_count = valid_count;
10148         }
10149 }
10150
10151 /**
10152  * lfs_mirror_prepare_chunk() - Find mirror chunks to be verified.
10153  * @layout:      Mirror component list.
10154  * @chunks:      Array of chunks.
10155  * @chunks_size: Array size of @chunks.
10156  *
10157  * This function scans the components in @layout from offset 0 to LUSTRE_EOF
10158  * to find out chunk segments and store them in @chunks array.
10159  *
10160  * The @mirror_id array in each element of @chunks will store the valid
10161  * mirror ids that cover the chunk. If a mirror component covering the
10162  * chunk has LCME_FL_STALE or LCME_FL_OFFLINE flag, then the mirror id
10163  * will not be stored into the @mirror_id array, and the chunk for that
10164  * mirror will not be verified.
10165  *
10166  * The @mirror_count in each element of @chunks will store the number of
10167  * mirror ids in @mirror_id array. If @mirror_count is 0, it indicates the
10168  * chunk is invalid in all of the mirrors. And if @mirror_count is 1, it
10169  * indicates the chunk is valid in only one mirror. In both cases, the
10170  * chunk will not be verified.
10171  *
10172  * Here is an example:
10173  *
10174  *  0      1M     2M     3M     4M           EOF
10175  *  +------+-------------+--------------------+
10176  *  |      |             |      S             |       mirror1
10177  *  +------+------+------+------+-------------+
10178  *  |             |   S  |   S  |             |       mirror2
10179  *  +-------------+------+------+-------------+
10180  *
10181  * prepared @chunks array will contain 5 elements:
10182  * (([0, 1M), [1, 2], 2),
10183  *  ([1M, 2M), [1, 2], 2),
10184  *  ([2M, 3M), [1], 1),
10185  *  ([3M, 4M], [], 0),
10186  *  ([4M, EOF), [2], 1))
10187  *
10188  * Return: the actual array size of @chunks on success
10189  *         or a negative error code on failure.
10190  */
10191 static inline
10192 int lfs_mirror_prepare_chunk(struct llapi_layout *layout,
10193                              struct verify_chunk *chunks,
10194                              size_t chunks_size)
10195 {
10196         uint64_t start;
10197         uint64_t end;
10198         uint32_t mirror_id;
10199         uint32_t flags;
10200         int idx = 0;
10201         int i = 0;
10202         int rc = 0;
10203
10204         memset(chunks, 0, sizeof(*chunks) * chunks_size);
10205
10206         while (1) {
10207                 rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_FIRST);
10208                 if (rc < 0) {
10209                         fprintf(stderr,
10210                                 "%s: move to the first layout component: %s.\n",
10211                                 progname, strerror(errno));
10212                         goto error;
10213                 }
10214
10215                 i = 0;
10216                 rc = 0;
10217                 chunks[idx].chunk.e_end = LUSTRE_EOF;
10218                 while (rc == 0) {
10219                         rc = llapi_layout_comp_extent_get(layout, &start, &end);
10220                         if (rc < 0) {
10221                                 fprintf(stderr,
10222                                         "%s: llapi_layout_comp_extent_get failed: %s.\n",
10223                                         progname, strerror(errno));
10224                                 goto error;
10225                         }
10226
10227                         if (start > chunks[idx].chunk.e_start ||
10228                             end <= chunks[idx].chunk.e_start)
10229                                 goto next;
10230
10231                         if (end < chunks[idx].chunk.e_end)
10232                                 chunks[idx].chunk.e_end = end;
10233
10234                         rc = llapi_layout_comp_flags_get(layout, &flags);
10235                         if (rc < 0) {
10236                                 fprintf(stderr,
10237                                         "%s: llapi_layout_comp_flags_get failed: %s.\n",
10238                                         progname, strerror(errno));
10239                                 goto error;
10240                         }
10241
10242                         if (flags & LCME_FL_STALE || flags & LCME_FL_OFFLINE)
10243                                 goto next;
10244
10245                         rc = llapi_layout_mirror_id_get(layout, &mirror_id);
10246                         if (rc < 0) {
10247                                 fprintf(stderr,
10248                                         "%s: llapi_layout_mirror_id_get failed: %s.\n",
10249                                         progname, strerror(errno));
10250                                 goto error;
10251                         }
10252
10253                         chunks[idx].mirror_id[i] = mirror_id;
10254                         i++;
10255                         if (i >= ARRAY_SIZE(chunks[idx].mirror_id)) {
10256                                 fprintf(stderr,
10257                                         "%s: mirror_id array is too small.\n",
10258                                         progname);
10259                                 rc = -EINVAL;
10260                                 goto error;
10261                         }
10262
10263                 next:
10264                         rc = llapi_layout_comp_use(layout,
10265                                                    LLAPI_LAYOUT_COMP_USE_NEXT);
10266                         if (rc < 0) {
10267                                 fprintf(stderr,
10268                                         "%s: move to the next layout component: %s.\n",
10269                                         progname, strerror(errno));
10270                                 goto error;
10271                         }
10272                 } /* loop through all components */
10273
10274                 chunks[idx].mirror_count = i;
10275
10276                 if (chunks[idx].chunk.e_end == LUSTRE_EOF)
10277                         break;
10278
10279                 idx++;
10280                 if (idx >= chunks_size) {
10281                         fprintf(stderr, "%s: chunks array is too small.\n",
10282                                 progname);
10283                         rc = -EINVAL;
10284                         goto error;
10285                 }
10286
10287                 chunks[idx].chunk.e_start = chunks[idx - 1].chunk.e_end;
10288         }
10289
10290 error:
10291         return rc < 0 ? rc : idx + 1;
10292 }
10293
10294 /**
10295  * lfs_mirror_verify_chunk() - Verify a chunk.
10296  * @fd:        File descriptor of the mirrored file.
10297  * @file_size: Size of the mirrored file.
10298  * @chunk:     A chunk and its corresponding valid mirror ids.
10299  * @verbose:   Verbose mode.
10300  *
10301  * This function verifies a @chunk contains exactly the same data
10302  * ammong the mirrors that cover it.
10303  *
10304  * If @verbose is specified, then the function will print where the
10305  * differences are if the data do not match. Otherwise, it will
10306  * just return an error in that case.
10307  *
10308  * Return: 0 on success or a negative error code on failure.
10309  */
10310 static inline
10311 int lfs_mirror_verify_chunk(int fd, size_t file_size,
10312                             struct verify_chunk *chunk, int verbose)
10313 {
10314         const size_t buflen = 4 * 1024 * 1024; /* 4M */
10315         void *buf;
10316         size_t page_size = sysconf(_SC_PAGESIZE);
10317         ssize_t bytes_read;
10318         ssize_t bytes_done;
10319         size_t count;
10320         off_t pos;
10321         unsigned long crc;
10322         unsigned long crc_array[LUSTRE_MIRROR_COUNT_MAX] = { 0 };
10323         int i;
10324         int rc = 0;
10325
10326         if (file_size == 0)
10327                 return 0;
10328
10329         rc = posix_memalign(&buf, page_size, buflen);
10330         if (rc) /* error code is returned directly */
10331                 return -rc;
10332
10333         if (verbose > 1) {
10334                 fprintf(stdout, "Verifying chunk "DEXT" on mirror:",
10335                         PEXT(&chunk->chunk));
10336                 for (i = 0; i < chunk->mirror_count; i++)
10337                         fprintf(stdout, " %u", chunk->mirror_id[i]);
10338                 fprintf(stdout, "\n");
10339         }
10340
10341         bytes_done = 0;
10342         count = MIN(chunk->chunk.e_end, file_size) - chunk->chunk.e_start;
10343         pos = chunk->chunk.e_start;
10344         while (bytes_done < count) {
10345                 /* compute initial CRC-32 checksum */
10346                 crc = crc32(0L, Z_NULL, 0);
10347                 memset(crc_array, 0, sizeof(crc_array));
10348
10349                 bytes_read = 0;
10350                 for (i = 0; i < chunk->mirror_count; i++) {
10351                         bytes_read = llapi_mirror_read(fd, chunk->mirror_id[i],
10352                                                        buf, buflen, pos);
10353                         if (bytes_read < 0) {
10354                                 rc = bytes_read;
10355                                 fprintf(stderr,
10356                                         "%s: failed to read data from mirror %u: %s.\n",
10357                                         progname, chunk->mirror_id[i],
10358                                         strerror(-rc));
10359                                 goto error;
10360                         }
10361
10362                         /* compute new CRC-32 checksum */
10363                         crc_array[i] = crc32(crc, buf, bytes_read);
10364                 }
10365
10366                 if (verbose)
10367                         print_checksums(chunk, crc_array);
10368
10369                 /* compare CRC-32 checksum values */
10370                 for (i = 1; i < chunk->mirror_count; i++) {
10371                         if (crc_array[i] != crc_array[0]) {
10372                                 rc = -EINVAL;
10373
10374                                 fprintf(stderr,
10375                                         "%s: chunk "DEXT" has different checksum value on mirror %u and mirror %u.\n",
10376                                         progname, PEXT(&chunk->chunk),
10377                                         chunk->mirror_id[0],
10378                                         chunk->mirror_id[i]);
10379                         }
10380                 }
10381
10382                 pos += bytes_read;
10383                 bytes_done += bytes_read;
10384         }
10385
10386         if (verbose > 1 && rc == 0) {
10387                 fprintf(stdout, "Verifying chunk "DEXT" on mirror:",
10388                         PEXT(&chunk->chunk));
10389                 for (i = 0; i < chunk->mirror_count; i++)
10390                         fprintf(stdout, " %u", chunk->mirror_id[i]);
10391                 fprintf(stdout, " PASS\n\n");
10392         }
10393
10394 error:
10395         free(buf);
10396         return rc;
10397 }
10398
10399 /**
10400  * lfs_mirror_verify_file() - Verify a mirrored file.
10401  * @fname:      Mirrored file name.
10402  * @mirror_ids: Specified mirror ids to be verified.
10403  * @ids_nr:     Number of specified mirror ids.
10404  * @verbose:    Verbose mode.
10405  *
10406  * This function verifies that each SYNC mirror of a mirrored file
10407  * specified by @fname contains exactly the same data.
10408  *
10409  * If @mirror_ids is specified, then the function will verify the
10410  * mirrors specified by @mirror_ids contain exactly the same data.
10411  *
10412  * If @verbose is specified, then the function will print where the
10413  * differences are if the data do not match. Otherwise, it will
10414  * just return an error in that case.
10415  *
10416  * Return: 0 on success or a negative error code on failure.
10417  */
10418 static inline
10419 int lfs_mirror_verify_file(const char *fname, __u16 *mirror_ids, int ids_nr,
10420                            int verbose)
10421 {
10422         struct verify_chunk chunks_array[1024] = { };
10423         struct llapi_layout *layout = NULL;
10424         struct stat stbuf;
10425         uint32_t flr_state;
10426         int fd;
10427         int chunk_count = 0;
10428         int idx = 0;
10429         int rc = 0;
10430         int rc1 = 0;
10431         int rc2 = 0;
10432
10433         if (stat(fname, &stbuf) < 0) {
10434                 fprintf(stderr, "%s: cannot stat file '%s': %s.\n",
10435                         progname, fname, strerror(errno));
10436                 rc = -errno;
10437                 goto error;
10438         }
10439
10440         if (!S_ISREG(stbuf.st_mode)) {
10441                 fprintf(stderr, "%s: '%s' is not a regular file.\n",
10442                         progname, fname);
10443                 rc = -EINVAL;
10444                 goto error;
10445         }
10446
10447         if (stbuf.st_size == 0) {
10448                 if (verbose)
10449                         fprintf(stdout, "%s: '%s' file size is 0.\n",
10450                                 progname, fname);
10451                 rc = 0;
10452                 goto error;
10453         }
10454
10455         fd = open(fname, O_DIRECT | O_RDONLY);
10456         if (fd < 0) {
10457                 fprintf(stderr, "%s: cannot open '%s': %s.\n",
10458                         progname, fname, strerror(errno));
10459                 rc = -errno;
10460                 goto error;
10461         }
10462
10463         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
10464         if (rc < 0) {
10465                 fprintf(stderr, "%s: '%s' llapi_lease_acquire failed: %s.\n",
10466                         progname, fname, strerror(errno));
10467                 goto close_fd;
10468         }
10469
10470         layout = llapi_layout_get_by_fd(fd, 0);
10471         if (layout == NULL) {
10472                 fprintf(stderr, "%s: '%s' llapi_layout_get_by_fd failed: %s.\n",
10473                         progname, fname, strerror(errno));
10474                 rc = -errno;
10475                 llapi_lease_release(fd);
10476                 goto close_fd;
10477         }
10478
10479         rc = llapi_layout_flags_get(layout, &flr_state);
10480         if (rc < 0) {
10481                 fprintf(stderr, "%s: '%s' llapi_layout_flags_get failed: %s.\n",
10482                         progname, fname, strerror(errno));
10483                 rc = -errno;
10484                 goto free_layout;
10485         }
10486
10487         flr_state &= LCM_FL_FLR_MASK;
10488         switch (flr_state) {
10489         case LCM_FL_NONE:
10490                 rc = -EINVAL;
10491                 fprintf(stderr, "%s: '%s' file state error: %s.\n",
10492                         progname, fname, llapi_layout_flags_string(flr_state));
10493                 goto free_layout;
10494         default:
10495                 break;
10496         }
10497
10498         /* find out mirror chunks to be verified */
10499         chunk_count = lfs_mirror_prepare_chunk(layout, chunks_array,
10500                                                ARRAY_SIZE(chunks_array));
10501         if (chunk_count < 0) {
10502                 rc = chunk_count;
10503                 goto free_layout;
10504         }
10505
10506         if (ids_nr > 0)
10507                 /* filter specified mirror ids */
10508                 filter_mirror_id(chunks_array, chunk_count, mirror_ids, ids_nr);
10509
10510         if (verbose > 2)
10511                 print_chunks(fname, chunks_array, chunk_count);
10512
10513         for (idx = 0; idx < chunk_count; idx++) {
10514                 if (chunks_array[idx].chunk.e_start >= stbuf.st_size) {
10515                         if (verbose)
10516                                 fprintf(stdout,
10517                                         "%s: '%s' chunk "DEXT" exceeds file size %#llx: skipped\n",
10518                                         progname, fname,
10519                                         PEXT(&chunks_array[idx].chunk),
10520                                         (unsigned long long)stbuf.st_size);
10521                         break;
10522                 }
10523
10524                 if (chunks_array[idx].mirror_count == 0) {
10525                         fprintf(stderr,
10526                                 "%s: '%s' chunk "DEXT" is invalid in all of the mirrors: ",
10527                                 progname, fname,
10528                                 PEXT(&chunks_array[idx].chunk));
10529                         if (verbose) {
10530                                 fprintf(stderr, "skipped\n");
10531                                 continue;
10532                         }
10533                         rc = -EINVAL;
10534                         fprintf(stderr, "failed\n");
10535                         goto free_layout;
10536                 }
10537
10538                 if (chunks_array[idx].mirror_count == 1) {
10539                         if (verbose)
10540                                 fprintf(stdout,
10541                                         "%s: '%s' chunk "DEXT" is only valid in mirror %u: skipped\n",
10542                                         progname, fname,
10543                                         PEXT(&chunks_array[idx].chunk),
10544                                         chunks_array[idx].mirror_id[0]);
10545                         continue;
10546                 }
10547
10548                 rc = llapi_lease_check(fd);
10549                 if (rc != LL_LEASE_RDLCK) {
10550                         fprintf(stderr, "%s: '%s' lost lease lock.\n",
10551                                 progname, fname);
10552                         goto free_layout;
10553                 }
10554
10555                 /* verify one chunk */
10556                 rc1 = lfs_mirror_verify_chunk(fd, stbuf.st_size,
10557                                               &chunks_array[idx], verbose);
10558                 if (rc1 < 0) {
10559                         rc2 = rc1;
10560                         if (!verbose) {
10561                                 rc = rc1;
10562                                 goto free_layout;
10563                         }
10564                 }
10565         }
10566
10567         if (rc2 < 0)
10568                 rc = rc2;
10569
10570 free_layout:
10571         llapi_layout_free(layout);
10572         llapi_lease_release(fd);
10573 close_fd:
10574         close(fd);
10575 error:
10576         return rc;
10577 }
10578
10579 /**
10580  * lfs_mirror_verify() - Parse and execute lfs mirror verify command.
10581  * @argc: The count of lfs mirror verify command line arguments.
10582  * @argv: Array of strings for lfs mirror verify command line arguments.
10583  *
10584  * This function parses lfs mirror verify command and verifies the
10585  * specified mirrored file(s).
10586  *
10587  * Return: 0 on success or a negative error code on failure.
10588  */
10589 static inline int lfs_mirror_verify(int argc, char **argv)
10590 {
10591         __u16 mirror_ids[LUSTRE_MIRROR_COUNT_MAX] = { 0 };
10592         int ids_nr = 0;
10593         int c;
10594         int verbose = 0;
10595         int rc = 0;
10596         int rc1 = 0;
10597         char cmd[PATH_MAX];
10598
10599         struct option long_opts[] = {
10600         { .val = 'o',   .name = "only",         .has_arg = required_argument },
10601         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
10602         { .name = NULL } };
10603
10604         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
10605         progname = cmd;
10606         while ((c = getopt_long(argc, argv, "o:v", long_opts, NULL)) >= 0) {
10607                 switch (c) {
10608                 case 'o':
10609                         rc = parse_mirror_ids(mirror_ids,
10610                                               ARRAY_SIZE(mirror_ids),
10611                                               optarg);
10612                         if (rc < 0) {
10613                                 fprintf(stderr,
10614                                         "%s: bad mirror ids '%s'.\n",
10615                                         progname, optarg);
10616                                 goto error;
10617                         }
10618                         ids_nr = rc;
10619                         if (ids_nr < 2) {
10620                                 fprintf(stderr,
10621                                         "%s: at least 2 mirror ids needed with '--only' option.\n",
10622                                         progname);
10623                                 rc = CMD_HELP;
10624                                 goto error;
10625                         }
10626                         break;
10627                 case 'v':
10628                         verbose++;
10629                         break;
10630                 default:
10631                         fprintf(stderr, "%s: option '%s' unrecognized.\n",
10632                                 progname, argv[optind - 1]);
10633                         rc = -EINVAL;
10634                         goto error;
10635                 }
10636         }
10637
10638         if (argc == optind) {
10639                 fprintf(stderr, "%s: no file name given.\n", progname);
10640                 rc = CMD_HELP;
10641                 goto error;
10642         }
10643
10644         if (ids_nr > 0 && argc > optind + 1) {
10645                 fprintf(stderr,
10646                         "%s: '--only' cannot be used upon multiple files.\n",
10647                         progname);
10648                 rc = CMD_HELP;
10649                 goto error;
10650
10651         }
10652
10653         if (ids_nr > 0) {
10654                 rc = verify_mirror_ids(argv[optind], mirror_ids, ids_nr);
10655                 if (rc < 0)
10656                         goto error;
10657         }
10658
10659         rc = 0;
10660         for (; optind < argc; optind++) {
10661                 rc1 = lfs_mirror_verify_file(argv[optind], mirror_ids, ids_nr,
10662                                              verbose);
10663                 if (rc1 < 0)
10664                         rc = rc1;
10665         }
10666 error:
10667         return rc;
10668 }
10669
10670 /**
10671  * lfs_mirror() - Parse and execute lfs mirror commands.
10672  * @argc: The count of lfs mirror command line arguments.
10673  * @argv: Array of strings for lfs mirror command line arguments.
10674  *
10675  * This function parses lfs mirror commands and performs the
10676  * corresponding functions specified in mirror_cmdlist[].
10677  *
10678  * Return: 0 on success or an error code on failure.
10679  */
10680 static int lfs_mirror(int argc, char **argv)
10681 {
10682         char cmd[PATH_MAX];
10683         int rc = 0;
10684
10685         setlinebuf(stdout);
10686
10687         Parser_init("lfs-mirror > ", mirror_cmdlist);
10688
10689         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
10690         progname = cmd;
10691         program_invocation_short_name = cmd;
10692         if (argc > 1)
10693                 rc = Parser_execarg(argc - 1, argv + 1, mirror_cmdlist);
10694         else
10695                 rc = Parser_commands();
10696
10697         return rc < 0 ? -rc : rc;
10698 }
10699
10700 static void lustre_som_swab(struct lustre_som_attrs *attrs)
10701 {
10702 #if __BYTE_ORDER == __BIG_ENDIAN
10703         __swab16s(&attrs->lsa_valid);
10704         __swab64s(&attrs->lsa_size);
10705         __swab64s(&attrs->lsa_blocks);
10706 #endif
10707 }
10708
10709 enum lfs_som_type {
10710         LFS_SOM_SIZE = 0x1,
10711         LFS_SOM_BLOCKS = 0x2,
10712         LFS_SOM_FLAGS = 0x4,
10713         LFS_SOM_ATTR_ALL = LFS_SOM_SIZE | LFS_SOM_BLOCKS |
10714                            LFS_SOM_FLAGS,
10715 };
10716
10717 static int lfs_getsom(int argc, char **argv)
10718 {
10719         const char *path;
10720         struct lustre_som_attrs *attrs;
10721         char buf[sizeof(*attrs) + 64];
10722         enum lfs_som_type type = LFS_SOM_ATTR_ALL;
10723         int rc = 0, c;
10724
10725         while ((c = getopt(argc, argv, "sbf")) != -1) {
10726                 switch (c) {
10727                 case 's':
10728                         type = LFS_SOM_SIZE;
10729                         break;
10730                 case 'b':
10731                         type = LFS_SOM_BLOCKS;
10732                         break;
10733                 case 'f':
10734                         type = LFS_SOM_FLAGS;
10735                         break;
10736                 default:
10737                         fprintf(stderr, "%s: invalid option '%c'\n",
10738                                 progname, optopt);
10739                         return CMD_HELP;
10740                 }
10741         }
10742
10743         argc -= optind;
10744         argv += optind;
10745
10746         if (argc != 1) {
10747                 fprintf(stderr, "%s: %s\n",
10748                         progname, argc == 0 ? "miss file target" :
10749                         "input more than 2 files");
10750                 return CMD_HELP;
10751         }
10752
10753         path = argv[0];
10754         attrs = (void *)buf;
10755         rc = lgetxattr(path, "trusted.som", attrs, sizeof(buf));
10756         if (rc < 0) {
10757                 rc = -errno;
10758                 fprintf(stderr, "%s failed to get som xattr: %s (%d)\n",
10759                         argv[0], strerror(errno), errno);
10760                 return rc;
10761         }
10762
10763         lustre_som_swab(attrs);
10764
10765         switch (type) {
10766         case LFS_SOM_ATTR_ALL:
10767                 printf("file: %s size: %llu blocks: %llu flags: %x\n",
10768                        path, (unsigned long long)attrs->lsa_size,
10769                        (unsigned long long)attrs->lsa_blocks,
10770                        attrs->lsa_valid);
10771                 break;
10772         case LFS_SOM_SIZE:
10773                 printf("%llu\n", (unsigned long long)attrs->lsa_size);
10774                 break;
10775         case LFS_SOM_BLOCKS:
10776                 printf("%llu\n", (unsigned long long)attrs->lsa_blocks);
10777                 break;
10778         case LFS_SOM_FLAGS:
10779                 printf("%x\n", attrs->lsa_valid);
10780                 break;
10781         default:
10782                 fprintf(stderr, "%s: unknown option\n", progname);
10783                 return CMD_HELP;
10784         }
10785
10786         return 0;
10787 }
10788
10789 /**
10790  * lfs_mirror_list_commands() - List lfs mirror commands.
10791  * @argc: The count of command line arguments.
10792  * @argv: Array of strings for command line arguments.
10793  *
10794  * This function lists lfs mirror commands defined in mirror_cmdlist[].
10795  *
10796  * Return: 0 on success.
10797  */
10798 static int lfs_mirror_list_commands(int argc, char **argv)
10799 {
10800         char buffer[81] = "";
10801
10802         Parser_list_commands(mirror_cmdlist, buffer, sizeof(buffer),
10803                              NULL, 0, 4);
10804
10805         return 0;
10806 }
10807
10808 static int lfs_pcc_attach(int argc, char **argv)
10809 {
10810         struct option long_opts[] = {
10811         { .val = 'i',   .name = "id",   .has_arg = required_argument },
10812         { .name = NULL } };
10813         int c;
10814         int rc = 0;
10815         __u32 archive_id = 0;
10816         const char *path;
10817         char *end;
10818         char fullpath[PATH_MAX];
10819         enum lu_pcc_type type = LU_PCC_READWRITE;
10820
10821         optind = 0;
10822         while ((c = getopt_long(argc, argv, "i:",
10823                                 long_opts, NULL)) != -1) {
10824                 switch (c) {
10825                 case 'i':
10826                         archive_id = strtoul(optarg, &end, 0);
10827                         if (*end != '\0' || archive_id == 0) {
10828                                 fprintf(stderr, "error: %s: bad archive ID "
10829                                         "'%s'\n", argv[0], optarg);
10830                                 return CMD_HELP;
10831                         }
10832                         break;
10833                 case '?':
10834                         return CMD_HELP;
10835                 default:
10836                         fprintf(stderr, "%s: option '%s' unrecognized\n",
10837                                 argv[0], argv[optind - 1]);
10838                         return CMD_HELP;
10839                 }
10840         }
10841
10842         if (argc <= optind) {
10843                 fprintf(stderr, "%s: must specify one or more file names\n",
10844                         argv[0]);
10845                 return CMD_HELP;
10846         }
10847
10848         while (optind < argc) {
10849                 int rc2;
10850
10851                 path = argv[optind++];
10852                 if (realpath(path, fullpath) == NULL) {
10853                         fprintf(stderr, "%s: could not find path '%s': %s\n",
10854                                 argv[0], path, strerror(errno));
10855                         if (rc == 0)
10856                                 rc = -EINVAL;
10857                         continue;
10858                 }
10859
10860                 rc2 = llapi_pcc_attach(fullpath, archive_id, type);
10861                 if (rc2 < 0) {
10862                         fprintf(stderr, "%s: cannot attach '%s' to PCC "
10863                                 "with archive ID '%u': %s\n", argv[0],
10864                                 path, archive_id, strerror(-rc2));
10865                         if (rc == 0)
10866                                 rc = rc2;
10867                 }
10868         }
10869         return rc;
10870 }
10871
10872 static int lfs_pcc_attach_fid(int argc, char **argv)
10873 {
10874         struct option long_opts[] = {
10875         { .val = 'i',   .name = "id",   .has_arg = required_argument },
10876         { .val = 'm',   .name = "mnt",  .has_arg = required_argument },
10877         { .name = NULL } };
10878         char                     short_opts[] = "i:m:";
10879         int                      c;
10880         int                      rc = 0;
10881         __u32                    archive_id = 0;
10882         char                    *end;
10883         const char              *mntpath = NULL;
10884         const char              *fidstr;
10885         enum lu_pcc_type         type = LU_PCC_READWRITE;
10886
10887         optind = 0;
10888         while ((c = getopt_long(argc, argv, short_opts,
10889                                 long_opts, NULL)) != -1) {
10890                 switch (c) {
10891                 case 'i':
10892                         archive_id = strtoul(optarg, &end, 0);
10893                         if (*end != '\0') {
10894                                 fprintf(stderr, "error: %s: bad archive ID "
10895                                         "'%s'\n", argv[0], optarg);
10896                                 return CMD_HELP;
10897                         }
10898                         break;
10899                 case 'm':
10900                         mntpath = optarg;
10901                         break;
10902                 case '?':
10903                         return CMD_HELP;
10904                 default:
10905                         fprintf(stderr, "%s: option '%s' unrecognized\n",
10906                                 argv[0], argv[optind - 1]);
10907                         return CMD_HELP;
10908                 }
10909         }
10910
10911         if (archive_id == 0) {
10912                 fprintf(stderr, "%s: must specify an archive ID\n", argv[0]);
10913                 return CMD_HELP;
10914         }
10915
10916         if (mntpath == NULL) {
10917                 fprintf(stderr, "%s: must specify Lustre mount point\n",
10918                         argv[0]);
10919                 return CMD_HELP;
10920         }
10921
10922         if (argc <= optind) {
10923                 fprintf(stderr, "%s: must specify one or more fids\n", argv[0]);
10924                 return CMD_HELP;
10925         }
10926
10927         while (optind < argc) {
10928                 int rc2;
10929
10930                 fidstr = argv[optind++];
10931
10932                 rc2 = llapi_pcc_attach_fid_str(mntpath, fidstr,
10933                                                archive_id, type);
10934                 if (rc2 < 0) {
10935                         fprintf(stderr, "%s: cannot attach '%s' on '%s' to PCC "
10936                                 "with archive ID '%u': %s\n", argv[0],
10937                                 fidstr, mntpath, archive_id, strerror(rc2));
10938                 }
10939                 if (rc == 0 && rc2 < 0)
10940                         rc = rc2;
10941         }
10942         return rc;
10943 }
10944
10945 static int lfs_pcc_detach(int argc, char **argv)
10946 {
10947         struct option long_opts[] = {
10948         { .val = 'k',   .name = "keep", .has_arg = no_argument },
10949         { .name = NULL } };
10950         char                     short_opts[] = "k";
10951         int                      c;
10952         int                      rc = 0;
10953         const char              *path;
10954         char                     fullpath[PATH_MAX];
10955         __u32                    detach_opt = PCC_DETACH_OPT_UNCACHE;
10956
10957         optind = 0;
10958         while ((c = getopt_long(argc, argv, short_opts,
10959                                 long_opts, NULL)) != -1) {
10960                 switch (c) {
10961                 case 'k':
10962                         detach_opt = PCC_DETACH_OPT_NONE;
10963                         break;
10964                 case '?':
10965                         return CMD_HELP;
10966                 default:
10967                         fprintf(stderr, "%s: option '%s' unrecognized\n",
10968                                 argv[0], argv[optind - 1]);
10969                         return CMD_HELP;
10970                 }
10971         }
10972
10973         while (optind < argc) {
10974                 int rc2;
10975
10976                 path = argv[optind++];
10977                 if (realpath(path, fullpath) == NULL) {
10978                         fprintf(stderr, "%s: could not find path '%s': %s\n",
10979                                 argv[0], path, strerror(errno));
10980                         if (rc == 0)
10981                                 rc = -EINVAL;
10982                         continue;
10983                 }
10984
10985                 rc2 = llapi_pcc_detach_file(fullpath, detach_opt);
10986                 if (rc2 < 0) {
10987                         rc2 = -errno;
10988                         fprintf(stderr, "%s: cannot detach '%s' from PCC: "
10989                                 "%s\n", argv[0], path, strerror(errno));
10990                         if (rc == 0)
10991                                 rc = rc2;
10992                 }
10993         }
10994         return rc;
10995 }
10996
10997 static int lfs_pcc_detach_fid(int argc, char **argv)
10998 {
10999         struct option long_opts[] = {
11000         { .val = 'k',   .name = "keep", .has_arg = no_argument },
11001         { .name = NULL } };
11002         char             short_opts[] = "k";
11003         int              c;
11004         int              rc = 0;
11005         const char      *fid;
11006         const char      *mntpath;
11007         __u32            detach_opt = PCC_DETACH_OPT_UNCACHE;
11008
11009         optind = 0;
11010         while ((c = getopt_long(argc, argv, short_opts,
11011                                 long_opts, NULL)) != -1) {
11012                 switch (c) {
11013                 case 'k':
11014                         detach_opt = PCC_DETACH_OPT_NONE;
11015                         break;
11016                 case '?':
11017                         return CMD_HELP;
11018                 default:
11019                         fprintf(stderr, "%s: option '%s' unrecognized\n",
11020                                 argv[0], argv[optind - 1]);
11021                         return CMD_HELP;
11022                 }
11023         }
11024
11025         mntpath = argv[optind++];
11026
11027         while (optind < argc) {
11028                 int rc2;
11029
11030                 fid = argv[optind++];
11031
11032                 rc2 = llapi_pcc_detach_fid_str(mntpath, fid, detach_opt);
11033                 if (rc2 < 0) {
11034                         fprintf(stderr, "%s: cannot detach '%s' on '%s' "
11035                                 "from PCC: %s\n", argv[0], fid, mntpath,
11036                                 strerror(-rc2));
11037                         if (rc == 0)
11038                                 rc = rc2;
11039                 }
11040         }
11041         return rc;
11042 }
11043
11044 static int lfs_pcc_state(int argc, char **argv)
11045 {
11046         int                      rc = 0;
11047         const char              *path;
11048         char                     fullpath[PATH_MAX];
11049         struct lu_pcc_state      state;
11050
11051         optind = 1;
11052
11053         if (argc <= 1) {
11054                 fprintf(stderr, "%s: must specify one or more file names\n",
11055                         argv[0]);
11056                 return CMD_HELP;
11057         }
11058
11059         while (optind < argc) {
11060                 int rc2;
11061
11062                 path = argv[optind++];
11063                 if (realpath(path, fullpath) == NULL) {
11064                         fprintf(stderr, "%s: could not find path '%s': %s\n",
11065                                 argv[0], path, strerror(errno));
11066                         if (rc == 0)
11067                                 rc = -EINVAL;
11068                         continue;
11069                 }
11070
11071                 rc2 = llapi_pcc_state_get(fullpath, &state);
11072                 if (rc2 < 0) {
11073                         if (rc == 0)
11074                                 rc = rc2;
11075                         fprintf(stderr, "%s: cannot get PCC state of '%s': "
11076                                 "%s\n", argv[0], path, strerror(-rc2));
11077                         continue;
11078                 }
11079
11080                 printf("file: %s", path);
11081                 printf(", type: %s", pcc_type2string(state.pccs_type));
11082                 if (state.pccs_type == LU_PCC_NONE &&
11083                     state.pccs_open_count == 0) {
11084                         printf("\n");
11085                         continue;
11086                 }
11087
11088                 printf(", PCC file: %s", state.pccs_path);
11089                 printf(", user number: %u", state.pccs_open_count);
11090                 printf(", flags: %x", state.pccs_flags);
11091                 printf("\n");
11092         }
11093         return rc;
11094 }
11095
11096 /**
11097  * lfs_pcc_list_commands() - List lfs pcc commands.
11098  * @argc: The count of command line arguments.
11099  * @argv: Array of strings for command line arguments.
11100  *
11101  * This function lists lfs pcc commands defined in pcc_cmdlist[].
11102  *
11103  * Return: 0 on success.
11104  */
11105 static int lfs_pcc_list_commands(int argc, char **argv)
11106 {
11107         char buffer[81] = "";
11108
11109         Parser_list_commands(pcc_cmdlist, buffer, sizeof(buffer),
11110                              NULL, 0, 4);
11111
11112         return 0;
11113 }
11114
11115 /**
11116  * lfs_pcc() - Parse and execute lfs pcc commands.
11117  * @argc: The count of lfs pcc command line arguments.
11118  * @argv: Array of strings for lfs pcc command line arguments.
11119  *
11120  * This function parses lfs pcc commands and performs the
11121  * corresponding functions specified in pcc_cmdlist[].
11122  *
11123  * Return: 0 on success or an error code on failure.
11124  */
11125 static int lfs_pcc(int argc, char **argv)
11126 {
11127         char cmd[PATH_MAX];
11128         int rc = 0;
11129
11130         setlinebuf(stdout);
11131
11132         Parser_init("lfs-pcc > ", pcc_cmdlist);
11133
11134         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
11135         progname = cmd;
11136         program_invocation_short_name = cmd;
11137         if (argc > 1)
11138                 rc = Parser_execarg(argc - 1, argv + 1, pcc_cmdlist);
11139         else
11140                 rc = Parser_commands();
11141
11142         return rc < 0 ? -rc : rc;
11143 }
11144
11145 static int lfs_list_commands(int argc, char **argv)
11146 {
11147         char buffer[81] = ""; /* 80 printable chars + terminating NUL */
11148
11149         Parser_list_commands(cmdlist, buffer, sizeof(buffer), NULL, 0, 4);
11150
11151         return 0;
11152 }
11153
11154 int main(int argc, char **argv)
11155 {
11156         int rc;
11157
11158         /* Ensure that liblustreapi constructor has run */
11159         if (!llapi_liblustreapi_initialized())
11160                 fprintf(stderr, "liblustreapi was not properly initialized\n");
11161
11162         setlinebuf(stdout);
11163         opterr = 0;
11164
11165         Parser_init("lfs > ", cmdlist);
11166
11167         progname = program_invocation_short_name; /* Used in error messages */
11168         if (argc > 1) {
11169                 llapi_set_command_name(argv[1]);
11170                 rc = Parser_execarg(argc - 1, argv + 1, cmdlist);
11171                 llapi_clear_command_name();
11172         } else {
11173                 rc = Parser_commands();
11174         }
11175
11176         return rc < 0 ? -rc : rc;
11177 }
11178
11179 #ifdef _LUSTRE_IDL_H_
11180 /* Everything we need here should be included by lustreapi.h. */
11181 # error "lfs should not depend on lustre_idl.h"
11182 #endif /* _LUSTRE_IDL_H_ */