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