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