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