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