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