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