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