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