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