Whamcloud - gitweb
e21b059faf7180b1df1b217100ff1180fccca17c
[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                 string = node->cy_string;
2259                 /* skip leading lmm_ if present, to simplify parsing */
2260                 if (string != NULL && strncmp(string, "lmm_", 4) == 0)
2261                         string += 4;
2262
2263                 if (node->cy_type == CYAML_TYPE_STRING) {
2264                         if (!strcmp(string, "lcme_extent.e_end")) {
2265                                 if (!strcmp(node->cy_valuestring, "EOF") ||
2266                                     !strcmp(node->cy_valuestring, "eof"))
2267                                         lsa->lsa_comp_end = LUSTRE_EOF;
2268                         } else if (!strcmp(string, "pool")) {
2269                                 lsa->lsa_pool_name = node->cy_valuestring;
2270                         } else if (!strcmp(string, "pattern")) {
2271                                 if (!strcmp(node->cy_valuestring, "mdt"))
2272                                         lsa->lsa_pattern = LLAPI_LAYOUT_MDT;
2273                         }
2274                 } else if (node->cy_type == CYAML_TYPE_NUMBER) {
2275                         if (!strcmp(string, "lcm_mirror_count")) {
2276                                 lsa->lsa_mirror_count = node->cy_valueint;
2277                         } else if (!strcmp(string, "lcme_extent.e_start")) {
2278                                 if (node->cy_valueint != 0 || *layout != NULL) {
2279                                         rc = build_component(layout, lsa, true);
2280                                         if (rc)
2281                                                 return rc;
2282                                 }
2283
2284                                 if (node->cy_valueint == 0)
2285                                         lsa->lsa_first_comp = true;
2286
2287                                 /* initialize lsa */
2288                                 setstripe_args_init(lsa);
2289                                 lsa->lsa_tgts = osts;
2290                         } else if (!strcmp(string, "lcme_extent.e_end")) {
2291                                 if (node->cy_valueint == -1)
2292                                         lsa->lsa_comp_end = LUSTRE_EOF;
2293                                 else
2294                                         lsa->lsa_comp_end = node->cy_valueint;
2295                         } else if (!strcmp(string, "stripe_count")) {
2296                                 lsa->lsa_stripe_count = node->cy_valueint;
2297                         } else if (!strcmp(string, "stripe_size")) {
2298                                 lsa->lsa_stripe_size = node->cy_valueint;
2299                         } else if (!strcmp(string, "stripe_offset")) {
2300                                 lsa->lsa_stripe_off = node->cy_valueint;
2301                         } else if (!strcmp(string, "l_ost_idx")) {
2302                                 osts[lsa->lsa_nr_tgts] = node->cy_valueint;
2303                                 lsa->lsa_nr_tgts++;
2304                         }
2305                 } else if (node->cy_type == CYAML_TYPE_OBJECT) {
2306                         /* go deep to sub blocks */
2307                         rc = build_layout_from_yaml_node(node->cy_child, layout,
2308                                                          lsa, osts);
2309                         if (rc)
2310                                 return rc;
2311                 }
2312                 node = node->cy_next;
2313         }
2314
2315         return rc;
2316 }
2317
2318 static int lfs_comp_create_from_yaml(char *template,
2319                                      struct llapi_layout **layout,
2320                                      struct lfs_setstripe_args *lsa,
2321                                      __u32 *osts)
2322 {
2323         struct cYAML *tree = NULL, *err_rc = NULL;
2324         int rc = 0;
2325
2326         tree = cYAML_build_tree(template, NULL, 0, &err_rc, false);
2327         if (!tree) {
2328                 fprintf(stderr, "%s: cannot parse YAML file %s\n",
2329                         progname, template);
2330                 cYAML_build_error(-EINVAL, -1, "yaml", "from comp yaml",
2331                                   "can't parse", &err_rc);
2332                 cYAML_print_tree2file(stderr, err_rc);
2333                 cYAML_free_tree(err_rc);
2334                 rc = -EINVAL;
2335                 goto err;
2336         }
2337
2338         /* initialize lsa for plain file */
2339         setstripe_args_init(lsa);
2340         lsa->lsa_tgts = osts;
2341
2342         rc = build_layout_from_yaml_node(tree, layout, lsa, osts);
2343         if (rc) {
2344                 fprintf(stderr, "%s: cannot build layout from YAML file %s.\n",
2345                         progname, template);
2346                 goto err;
2347         } else {
2348                 rc = build_component(layout, lsa, *layout != NULL);
2349         }
2350         /* clean clean lsa */
2351         setstripe_args_init(lsa);
2352
2353 err:
2354         if (tree)
2355                 cYAML_free_tree(tree);
2356         return rc;
2357 }
2358
2359 /* In 'lfs setstripe --component-add' mode, we need to fetch the extent
2360  * end of the last component in the existing file, and adjust the
2361  * first extent start of the components to be added accordingly. */
2362 static int adjust_first_extent(char *fname, struct llapi_layout *layout)
2363 {
2364         struct llapi_layout *head;
2365         uint64_t start, end, stripe_size, prev_end = 0;
2366         int rc;
2367
2368         if (layout == NULL) {
2369                 fprintf(stderr,
2370                         "%s setstripe: layout must be specified\n",
2371                         progname);
2372                 return -EINVAL;
2373         }
2374
2375         errno = 0;
2376         head = llapi_layout_get_by_path(fname, 0);
2377         if (head == NULL) {
2378                 fprintf(stderr,
2379                         "%s setstripe: cannot read layout from '%s': %s\n",
2380                         progname, fname, strerror(errno));
2381                 return -EINVAL;
2382         } else if (errno == ENODATA) {
2383                 /* file without LOVEA, this component-add will be turned
2384                  * into a component-create. */
2385                 llapi_layout_free(head);
2386                 return -ENODATA;
2387         } else if (!llapi_layout_is_composite(head)) {
2388                 fprintf(stderr, "%s setstripe: '%s' not a composite file\n",
2389                         progname, fname);
2390                 llapi_layout_free(head);
2391                 return -EINVAL;
2392         }
2393
2394         rc = llapi_layout_comp_extent_get(head, &start, &prev_end);
2395         if (rc) {
2396                 fprintf(stderr, "%s setstripe: cannot get prev extent: %s\n",
2397                         progname, strerror(errno));
2398                 llapi_layout_free(head);
2399                 return rc;
2400         }
2401
2402         llapi_layout_free(head);
2403
2404         /* Make sure we use the first component of the layout to be added. */
2405         rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_FIRST);
2406         if (rc < 0) {
2407                 fprintf(stderr,
2408                         "%s setstripe: cannot move component cursor: %s\n",
2409                         progname, strerror(errno));
2410                 return rc;
2411         }
2412
2413         rc = llapi_layout_comp_extent_get(layout, &start, &end);
2414         if (rc) {
2415                 fprintf(stderr, "%s setstripe: cannot get extent: %s\n",
2416                         progname, strerror(errno));
2417                 return rc;
2418         }
2419
2420         if (start > prev_end || end <= prev_end) {
2421                 fprintf(stderr,
2422                         "%s setstripe: first extent [%lu, %lu) not adjacent with extent end %lu\n",
2423                         progname, start, end, prev_end);
2424                 return -EINVAL;
2425         }
2426
2427         rc = llapi_layout_stripe_size_get(layout, &stripe_size);
2428         if (rc) {
2429                 fprintf(stderr, "%s setstripe: cannot get stripe size: %s\n",
2430                         progname, strerror(errno));
2431                 return rc;
2432         }
2433
2434         if (stripe_size != LLAPI_LAYOUT_DEFAULT &&
2435             (prev_end & (stripe_size - 1))) {
2436                 fprintf(stderr,
2437                         "%s setstripe: stripe size %lu not aligned with %lu\n",
2438                         progname, stripe_size, prev_end);
2439                 return -EINVAL;
2440         }
2441
2442         rc = llapi_layout_comp_extent_set(layout, prev_end, end);
2443         if (rc) {
2444                 fprintf(stderr,
2445                         "%s setstripe: cannot set component extent [%lu, %lu): %s\n",
2446                         progname, prev_end, end, strerror(errno));
2447                 return rc;
2448         }
2449
2450         return 0;
2451 }
2452
2453 static inline bool arg_is_eof(char *arg)
2454 {
2455         return !strncmp(arg, "-1", strlen("-1")) ||
2456                !strncmp(arg, "EOF", strlen("EOF")) ||
2457                !strncmp(arg, "eof", strlen("eof"));
2458 }
2459
2460 /**
2461  * lfs_mirror_alloc() - Allocate a mirror argument structure.
2462  *
2463  * Return: Valid mirror_args pointer on success and
2464  *         NULL if memory allocation fails.
2465  */
2466 static struct mirror_args *lfs_mirror_alloc(void)
2467 {
2468         struct mirror_args *mirror = NULL;
2469
2470         while (1) {
2471                 mirror = calloc(1, sizeof(*mirror));
2472                 if (mirror != NULL)
2473                         break;
2474
2475                 sleep(1);
2476         }
2477
2478         return mirror;
2479 }
2480
2481 /**
2482  * lfs_mirror_free() - Free memory allocated for a mirror argument
2483  *                     structure.
2484  * @mirror: Previously allocated mirror argument structure by
2485  *          lfs_mirror_alloc().
2486  *
2487  * Free memory allocated for @mirror.
2488  *
2489  * Return: void.
2490  */
2491 static void lfs_mirror_free(struct mirror_args *mirror)
2492 {
2493         if (mirror->m_layout != NULL)
2494                 llapi_layout_free(mirror->m_layout);
2495         free(mirror);
2496 }
2497
2498 /**
2499  * lfs_mirror_list_free() - Free memory allocated for a mirror list.
2500  * @mirror_list: Previously allocated mirror list.
2501  *
2502  * Free memory allocated for @mirror_list.
2503  *
2504  * Return: void.
2505  */
2506 static void lfs_mirror_list_free(struct mirror_args *mirror_list)
2507 {
2508         struct mirror_args *next_mirror = NULL;
2509
2510         while (mirror_list != NULL) {
2511                 next_mirror = mirror_list->m_next;
2512                 lfs_mirror_free(mirror_list);
2513                 mirror_list = next_mirror;
2514         }
2515 }
2516
2517 enum {
2518         LFS_POOL_OPT = 3,
2519         LFS_COMP_COUNT_OPT,
2520         LFS_COMP_START_OPT,
2521         LFS_COMP_FLAGS_OPT,
2522         LFS_COMP_DEL_OPT,
2523         LFS_COMP_SET_OPT,
2524         LFS_COMP_ADD_OPT,
2525         LFS_COMP_NO_VERIFY_OPT,
2526         LFS_PROJID_OPT,
2527         LFS_MIRROR_FLAGS_OPT,
2528         LFS_MIRROR_ID_OPT,
2529         LFS_MIRROR_STATE_OPT,
2530         LFS_LAYOUT_COPY,
2531         LFS_MIRROR_INDEX_OPT,
2532 };
2533
2534 /* functions */
2535 static int lfs_setstripe_internal(int argc, char **argv,
2536                                   enum setstripe_origin opc)
2537 {
2538         struct lfs_setstripe_args        lsa = { 0 };
2539         struct llapi_stripe_param       *param = NULL;
2540         struct find_param                migrate_mdt_param = {
2541                 .fp_max_depth = -1,
2542                 .fp_mdt_index = -1,
2543         };
2544         char                            *fname;
2545         int                              result = 0;
2546         int                              result2 = 0;
2547         char                            *end;
2548         int                              c;
2549         int                              delete = 0;
2550         unsigned long long               size_units = 1;
2551         bool                             migrate_mode = false;
2552         bool                             migrate_mdt_mode = false;
2553         bool                             migration_block = false;
2554         __u64                            migration_flags = 0;
2555         __u32                            tgts[LOV_MAX_STRIPE_COUNT] = { 0 };
2556         int                              comp_del = 0, comp_set = 0;
2557         int                              comp_add = 0;
2558         __u32                            comp_id = 0;
2559         struct llapi_layout             *layout = NULL;
2560         struct llapi_layout             **lpp = &layout;
2561         bool                             mirror_mode = false;
2562         bool                             has_m_file = false;
2563         __u32                            mirror_count = 0;
2564         enum mirror_flags                mirror_flags = 0;
2565         struct mirror_args              *mirror_list = NULL;
2566         struct mirror_args              *new_mirror = NULL;
2567         struct mirror_args              *last_mirror = NULL;
2568         __u16                            mirror_id = 0;
2569         char                             cmd[PATH_MAX];
2570         bool from_yaml = false;
2571         bool from_copy = false;
2572         char *template = NULL;
2573
2574         struct option long_opts[] = {
2575 /* find { .val = 'A',   .name = "atime",        .has_arg = required_argument }*/
2576         /* --block is only valid in migrate mode */
2577         { .val = 'b',   .name = "block",        .has_arg = no_argument },
2578         { .val = LFS_COMP_ADD_OPT,
2579                         .name = "comp-add",     .has_arg = no_argument },
2580         { .val = LFS_COMP_ADD_OPT,
2581                         .name = "component-add", .has_arg = no_argument },
2582         { .val = LFS_COMP_DEL_OPT,
2583                         .name = "comp-del",     .has_arg = no_argument },
2584         { .val = LFS_COMP_DEL_OPT,
2585                         .name = "component-del", .has_arg = no_argument },
2586         { .val = LFS_COMP_FLAGS_OPT,
2587                         .name = "comp-flags",   .has_arg = required_argument },
2588         { .val = LFS_COMP_FLAGS_OPT,
2589                         .name = "component-flags",
2590                                                 .has_arg = required_argument },
2591         { .val = LFS_COMP_SET_OPT,
2592                         .name = "comp-set",     .has_arg = no_argument },
2593         { .val = LFS_COMP_SET_OPT,
2594                         .name = "component-set",
2595                                                 .has_arg = no_argument},
2596         { .val = LFS_COMP_NO_VERIFY_OPT,
2597                         .name = "no-verify",    .has_arg = no_argument},
2598         { .val = LFS_MIRROR_FLAGS_OPT,
2599                         .name = "flags",        .has_arg = required_argument},
2600         { .val = LFS_MIRROR_ID_OPT,
2601                         .name = "mirror-id",    .has_arg = required_argument},
2602         { .val = LFS_LAYOUT_COPY,
2603                         .name = "copy",         .has_arg = required_argument},
2604         { .val = 'c',   .name = "stripe-count", .has_arg = required_argument},
2605         { .val = 'c',   .name = "stripe_count", .has_arg = required_argument},
2606         { .val = 'c',   .name = "mdt-count",    .has_arg = required_argument},
2607 /* find { .val = 'C',   .name = "ctime",        .has_arg = required_argument }*/
2608         { .val = 'd',   .name = "delete",       .has_arg = no_argument},
2609         { .val = 'd',   .name = "destroy",      .has_arg = no_argument},
2610         /* --non-direct is only valid in migrate mode */
2611         { .val = 'D',   .name = "non-direct",   .has_arg = no_argument },
2612         { .val = 'E',   .name = "comp-end",     .has_arg = required_argument},
2613         { .val = 'E',   .name = "component-end",
2614                                                 .has_arg = required_argument},
2615         { .val = 'f',   .name = "file",         .has_arg = required_argument },
2616 /* find { .val = 'F',   .name = "fid",          .has_arg = no_argument }, */
2617 /* find { .val = 'g',   .name = "gid",          .has_arg = no_argument }, */
2618 /* find { .val = 'G',   .name = "group",        .has_arg = required_argument }*/
2619         { .val = 'H',   .name = "mdt-hash",     .has_arg = required_argument},
2620         { .val = 'i',   .name = "stripe-index", .has_arg = required_argument},
2621         { .val = 'i',   .name = "stripe_index", .has_arg = required_argument},
2622         { .val = 'I',   .name = "comp-id",      .has_arg = required_argument},
2623         { .val = 'I',   .name = "component-id", .has_arg = required_argument},
2624         { .val = 'L',   .name = "layout",       .has_arg = required_argument },
2625         { .val = 'm',   .name = "mdt",          .has_arg = required_argument},
2626         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument},
2627         { .val = 'm',   .name = "mdt_index",    .has_arg = required_argument},
2628         /* --non-block is only valid in migrate mode */
2629         { .val = 'n',   .name = "non-block",    .has_arg = no_argument },
2630         { .val = 'N',   .name = "mirror-count", .has_arg = optional_argument},
2631         { .val = 'o',   .name = "ost",          .has_arg = required_argument },
2632 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
2633         { .val = 'o',   .name = "ost-list",     .has_arg = required_argument },
2634         { .val = 'o',   .name = "ost_list",     .has_arg = required_argument },
2635 #endif
2636         { .val = 'p',   .name = "pool",         .has_arg = required_argument },
2637 /* find { .val = 'P',   .name = "print",        .has_arg = no_argument }, */
2638 /* getstripe { .val = 'q', .name = "quiet",     .has_arg = no_argument }, */
2639 /* getstripe { .val = 'r', .name = "recursive", .has_arg = no_argument }, */
2640 /* getstripe { .val = 'R', .name = "raw",       .has_arg = no_argument }, */
2641         { .val = 'S',   .name = "stripe-size",  .has_arg = required_argument },
2642         { .val = 'S',   .name = "stripe_size",  .has_arg = required_argument },
2643 /* find { .val = 't',   .name = "type",         .has_arg = required_argument }*/
2644 /* dirstripe { .val = 'T', .name = "mdt-count", .has_arg = required_argument }*/
2645 /* find { .val = 'u',   .name = "uid",          .has_arg = required_argument }*/
2646 /* find { .val = 'U',   .name = "user",         .has_arg = required_argument }*/
2647         /* --verbose is only valid in migrate mode */
2648         { .val = 'v',   .name = "verbose",      .has_arg = no_argument},
2649         { .val = 'y',   .name = "yaml",         .has_arg = required_argument },
2650         { .name = NULL } };
2651
2652         setstripe_args_init(&lsa);
2653
2654         migrate_mode = (opc == SO_MIGRATE);
2655         mirror_mode = (opc == SO_MIRROR_CREATE || opc == SO_MIRROR_EXTEND);
2656
2657         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
2658         progname = cmd;
2659         while ((c = getopt_long(argc, argv,
2660                                 "bc:dDE:f:H:i:I:m:N::no:p:L:s:S:vy:", long_opts,
2661                                 NULL)) >= 0) {
2662                 switch (c) {
2663                 case 0:
2664                         /* Long options. */
2665                         break;
2666                 case LFS_COMP_ADD_OPT:
2667                         comp_add = 1;
2668                         break;
2669                 case LFS_COMP_DEL_OPT:
2670                         comp_del = 1;
2671                         break;
2672                 case LFS_COMP_FLAGS_OPT:
2673                         result = comp_str2flags(optarg, &lsa.lsa_comp_flags,
2674                                                 &lsa.lsa_comp_neg_flags);
2675                         if (result != 0)
2676                                 goto usage_error;
2677                         if (mirror_mode && lsa.lsa_comp_neg_flags) {
2678                                 fprintf(stderr, "%s: inverted flags are not supported\n",
2679                                         progname);
2680                                 goto usage_error;
2681                         }
2682                         if (lsa.lsa_comp_neg_flags & LCME_FL_STALE) {
2683                                 fprintf(stderr,
2684                                         "%s: cannot clear 'stale' flags from component. Please use lfs-mirror-resync(1) instead\n",
2685                                         progname);
2686                                 result = -EINVAL;
2687                                 goto error;
2688                         }
2689
2690                         break;
2691                 case LFS_COMP_SET_OPT:
2692                         comp_set = 1;
2693                         break;
2694                 case LFS_COMP_NO_VERIFY_OPT:
2695                         mirror_flags |= MF_NO_VERIFY;
2696                         break;
2697                 case LFS_MIRROR_ID_OPT:
2698                         mirror_id = strtoul(optarg, &end, 0);
2699                         if (*end != '\0' || mirror_id == 0) {
2700                                 fprintf(stderr,
2701                                         "%s %s: invalid mirror ID '%s'\n",
2702                                         progname, argv[0], optarg);
2703                                 goto usage_error;
2704                         }
2705                         break;
2706                 case LFS_MIRROR_FLAGS_OPT: {
2707                         __u32 flags;
2708
2709                         if (!mirror_mode || !last_mirror) {
2710                                 fprintf(stderr, "error: %s: --flags must be specified with --mirror-count|-N option\n",
2711                                         progname);
2712                                 goto usage_error;
2713                         }
2714
2715                         result = comp_str2flags(optarg, &last_mirror->m_flags,
2716                                                 &flags);
2717                         if (result != 0)
2718                                 goto usage_error;
2719
2720                         if (flags) {
2721                                 fprintf(stderr, "%s: inverted flags are not supported\n",
2722                                         progname);
2723                                 result = -EINVAL;
2724                                 goto usage_error;
2725                         }
2726                         if (last_mirror->m_flags & ~LCME_USER_FLAGS) {
2727                                 fprintf(stderr,
2728                                         "%s: unsupported mirror flags: %s\n",
2729                                         progname, optarg);
2730                                 result = -EINVAL;
2731                                 goto error;
2732                         }
2733                         break;
2734                 }
2735                 case LFS_LAYOUT_COPY:
2736                         from_copy = true;
2737                         template = optarg;
2738                         break;
2739                 case 'b':
2740                         if (!migrate_mode) {
2741                                 fprintf(stderr,
2742                                         "%s %s: -b|--block valid only for migrate command\n",
2743                                         progname, argv[0]);
2744                                 goto usage_error;
2745                         }
2746                         migration_block = true;
2747                         break;
2748                 case 'c':
2749                         lsa.lsa_stripe_count = strtoul(optarg, &end, 0);
2750                         if (*end != '\0') {
2751                                 fprintf(stderr,
2752                                         "%s %s: invalid stripe count '%s'\n",
2753                                         progname, argv[0], optarg);
2754                                 goto usage_error;
2755                         }
2756
2757                         if (lsa.lsa_stripe_count == -1)
2758                                 lsa.lsa_stripe_count = LLAPI_LAYOUT_WIDE;
2759                         break;
2760                 case 'd':
2761                         /* delete the default striping pattern */
2762                         delete = 1;
2763                         if (opc == SO_MIRROR_SPLIT) {
2764                                 if (has_m_file) {
2765                                         fprintf(stderr,
2766                                               "%s %s: -d cannot used with -f\n",
2767                                                 progname, argv[0]);
2768                                         goto usage_error;
2769                                 }
2770                                 mirror_flags |= MF_DESTROY;
2771                         }
2772                         break;
2773                 case 'D':
2774                         if (!migrate_mode) {
2775                                 fprintf(stderr,
2776                                         "%s %s: -D|--non-direct is valid "
2777                                         "only for migrate command\n",
2778                                         progname, argv[0]);
2779                                 goto usage_error;
2780                         }
2781                         migration_flags |= MIGRATION_NONDIRECT;
2782                         break;
2783                 case 'E':
2784                         if (lsa.lsa_comp_end != 0) {
2785                                 result = comp_args_to_layout(lpp, &lsa, true);
2786                                 if (result) {
2787                                         fprintf(stderr,
2788                                                 "%s %s: invalid layout\n",
2789                                                 progname, argv[0]);
2790                                         goto usage_error;
2791                                 }
2792
2793                                 setstripe_args_init_inherit(&lsa);
2794                         }
2795
2796                         if (arg_is_eof(optarg)) {
2797                                 lsa.lsa_comp_end = LUSTRE_EOF;
2798                         } else {
2799                                 result = llapi_parse_size(optarg,
2800                                                         &lsa.lsa_comp_end,
2801                                                         &size_units, 0);
2802                                 if (result) {
2803                                         fprintf(stderr,
2804                                                 "%s %s: invalid component end '%s'\n",
2805                                                 progname, argv[0], optarg);
2806                                         goto usage_error;
2807                                 }
2808                         }
2809                         break;
2810                 case 'H':
2811                         if (!migrate_mode) {
2812                                 fprintf(stderr, "--mdt-hash is valid only for migrate command\n");
2813                                 return CMD_HELP;
2814                         }
2815
2816                         lsa.lsa_pattern = check_hashtype(optarg);
2817                         if (lsa.lsa_pattern == 0) {
2818                                 fprintf(stderr,
2819                                         "%s %s: bad stripe hash type '%s'\n",
2820                                         progname, argv[0], optarg);
2821                                 return CMD_HELP;
2822                         }
2823                         break;
2824                 case 'i':
2825                         lsa.lsa_stripe_off = strtol(optarg, &end, 0);
2826                         if (*end != '\0') {
2827                                 fprintf(stderr,
2828                                         "%s %s: invalid stripe offset '%s'\n",
2829                                         progname, argv[0], optarg);
2830                                 goto usage_error;
2831                         }
2832                         if (lsa.lsa_stripe_off == -1)
2833                                 lsa.lsa_stripe_off = LLAPI_LAYOUT_DEFAULT;
2834                         break;
2835                 case 'I':
2836                         comp_id = strtoul(optarg, &end, 0);
2837                         if (*end != '\0' || comp_id == 0 ||
2838                             comp_id > LCME_ID_MAX) {
2839                                 fprintf(stderr,
2840                                         "%s %s: invalid component ID '%s'\n",
2841                                         progname, argv[0], optarg);
2842                                 goto usage_error;
2843                         }
2844                         break;
2845                 case 'f':
2846                         if (opc != SO_MIRROR_EXTEND && opc != SO_MIRROR_SPLIT) {
2847                                 fprintf(stderr,
2848                                         "error: %s: invalid option: %s\n",
2849                                         progname, argv[optopt + 1]);
2850                                 goto usage_error;
2851                         }
2852                         if (opc == SO_MIRROR_EXTEND) {
2853                                 if (last_mirror == NULL) {
2854                                         fprintf(stderr,
2855                                 "error: %s: '-N' must exist in front of '%s'\n",
2856                                                 progname, argv[optopt + 1]);
2857                                         goto usage_error;
2858                                 }
2859                                 last_mirror->m_file = optarg;
2860                                 last_mirror->m_count = 1;
2861                         } else {
2862                                 /* mirror split */
2863                                 if (mirror_list == NULL)
2864                                         mirror_list = lfs_mirror_alloc();
2865                                 mirror_list->m_file = optarg;
2866                         }
2867                         has_m_file = true;
2868                         break;
2869                 case 'L':
2870                         if (strcmp(argv[optind - 1], "mdt") == 0) {
2871                                 /* Can be only the first component */
2872                                 if (layout != NULL) {
2873                                         result = -EINVAL;
2874                                         fprintf(stderr, "error: 'mdt' layout "
2875                                                 "can be only the first one\n");
2876                                         goto error;
2877                                 }
2878                                 if (lsa.lsa_comp_end > (1ULL << 30)) { /* 1Gb */
2879                                         result = -EFBIG;
2880                                         fprintf(stderr, "error: 'mdt' layout "
2881                                                 "size is too big\n");
2882                                         goto error;
2883                                 }
2884                                 lsa.lsa_pattern = LLAPI_LAYOUT_MDT;
2885                         } else if (strcmp(argv[optind - 1], "raid0") != 0) {
2886                                 result = -EINVAL;
2887                                 fprintf(stderr, "error: layout '%s' is "
2888                                         "unknown, supported layouts are: "
2889                                         "'mdt', 'raid0'\n", argv[optind]);
2890                                 goto error;
2891                         }
2892                         break;
2893                 case 'm':
2894                         if (!migrate_mode) {
2895                                 fprintf(stderr,
2896                                         "%s %s: -m|--mdt is valid only for migrate command\n",
2897                                         progname, argv[0]);
2898                                 goto usage_error;
2899                         }
2900                         migrate_mdt_mode = true;
2901                         lsa.lsa_nr_tgts = parse_targets(tgts,
2902                                                 sizeof(tgts) / sizeof(__u32),
2903                                                 lsa.lsa_nr_tgts, optarg);
2904                         if (lsa.lsa_nr_tgts < 0) {
2905                                 fprintf(stderr,
2906                                         "%s %s: invalid MDT target(s) '%s'\n",
2907                                         progname, argv[0], optarg);
2908                                 return CMD_HELP;
2909                         }
2910
2911                         lsa.lsa_tgts = tgts;
2912                         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
2913                                 lsa.lsa_stripe_off = tgts[0];
2914                         break;
2915                 case 'n':
2916                         if (!migrate_mode) {
2917                                 fprintf(stderr,
2918                                         "%s %s: -n|--non-block valid only for migrate command\n",
2919                                         progname, argv[0]);
2920                                 goto usage_error;
2921                         }
2922                         migration_flags |= MIGRATION_NONBLOCK;
2923                         break;
2924                 case 'N':
2925                         if (opc == SO_SETSTRIPE) {
2926                                 opc = SO_MIRROR_CREATE;
2927                                 mirror_mode = true;
2928                         }
2929                         mirror_count = 1;
2930                         if (optarg != NULL) {
2931                                 mirror_count = strtoul(optarg, &end, 0);
2932                                 if (*end != '\0' || mirror_count == 0) {
2933                                         fprintf(stderr,
2934                                                 "error: %s: bad mirror count: %s\n",
2935                                                 progname, optarg);
2936                                         result = -EINVAL;
2937                                         goto error;
2938                                 }
2939                         }
2940
2941                         new_mirror = lfs_mirror_alloc();
2942                         new_mirror->m_count = mirror_count;
2943
2944                         if (mirror_list == NULL)
2945                                 mirror_list = new_mirror;
2946
2947                         if (last_mirror != NULL) {
2948                                 /* wrap up last mirror */
2949                                 if (lsa.lsa_comp_end == 0)
2950                                         lsa.lsa_comp_end = LUSTRE_EOF;
2951
2952                                 result = comp_args_to_layout(lpp, &lsa, true);
2953                                 if (result) {
2954                                         lfs_mirror_free(new_mirror);
2955                                         goto error;
2956                                 }
2957
2958                                 setstripe_args_init_inherit(&lsa);
2959
2960                                 last_mirror->m_next = new_mirror;
2961                         }
2962
2963                         last_mirror = new_mirror;
2964                         lpp = &last_mirror->m_layout;
2965                         break;
2966                 case 'o':
2967 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
2968                         if (strcmp(argv[optind - 1], "--ost-list") == 0)
2969                                 fprintf(stderr, "warning: '--ost-list' is "
2970                                         "deprecated, use '--ost' instead\n");
2971 #endif
2972                         lsa.lsa_nr_tgts = parse_targets(tgts,
2973                                                 sizeof(tgts) / sizeof(__u32),
2974                                                 lsa.lsa_nr_tgts, optarg);
2975                         if (lsa.lsa_nr_tgts < 0) {
2976                                 fprintf(stderr,
2977                                         "%s %s: invalid OST target(s) '%s'\n",
2978                                         progname, argv[0], optarg);
2979                                 goto usage_error;
2980                         }
2981
2982                         lsa.lsa_tgts = tgts;
2983                         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
2984                                 lsa.lsa_stripe_off = tgts[0];
2985                         break;
2986                 case 'p':
2987                         if (optarg == NULL)
2988                                 goto usage_error;
2989                         lsa.lsa_pool_name = optarg;
2990
2991                         if (strlen(lsa.lsa_pool_name) == 0 ||
2992                             strncmp(lsa.lsa_pool_name, "none",
2993                                     LOV_MAXPOOLNAME) == 0)
2994                                 lsa.lsa_pool_name = NULL;
2995                         break;
2996                 case 'S':
2997                         result = llapi_parse_size(optarg, &lsa.lsa_stripe_size,
2998                                                   &size_units, 0);
2999                         if (result) {
3000                                 fprintf(stderr,
3001                                         "%s %s: invalid stripe size '%s'\n",
3002                                         progname, argv[0], optarg);
3003                                 goto usage_error;
3004                         }
3005                         break;
3006                 case 'v':
3007                         if (!migrate_mode) {
3008                                 fprintf(stderr,
3009                                         "%s %s: -v|--verbose valid only for migrate command\n",
3010                                         progname, argv[0]);
3011                                 goto usage_error;
3012                         }
3013                         migrate_mdt_param.fp_verbose = VERBOSE_DETAIL;
3014                         break;
3015                 case 'y':
3016                         from_yaml = true;
3017                         template = optarg;
3018                         break;
3019                 default:
3020                         fprintf(stderr, "%s %s: unrecognized option '%s'\n",
3021                                 progname, argv[0], argv[optind - 1]);
3022                         goto usage_error;
3023                 }
3024         }
3025
3026         fname = argv[optind];
3027
3028         if (optind == argc) {
3029                 fprintf(stderr, "%s %s: FILE must be specified\n",
3030                         progname, argv[0]);
3031                 goto usage_error;
3032         }
3033
3034         if (mirror_mode && mirror_count == 0) {
3035                 fprintf(stderr,
3036                         "error: %s: --mirror-count|-N option is required\n",
3037                         progname);
3038                 result = -EINVAL;
3039                 goto error;
3040         }
3041
3042         if (mirror_mode) {
3043                 if (lsa.lsa_comp_end == 0)
3044                         lsa.lsa_comp_end = LUSTRE_EOF;
3045         }
3046
3047         if (lsa.lsa_comp_end != 0) {
3048                 result = comp_args_to_layout(lpp, &lsa, true);
3049                 if (result)
3050                         goto error;
3051         }
3052
3053         if (mirror_flags & MF_NO_VERIFY) {
3054                 if (opc != SO_MIRROR_EXTEND) {
3055                         fprintf(stderr,
3056                                 "error: %s: --no-verify is valid only for lfs mirror extend command\n",
3057                                 progname);
3058                         result = -EINVAL;
3059                         goto error;
3060                 } else if (!has_m_file) {
3061                         fprintf(stderr,
3062                                 "error: %s: --no-verify must be specified with -f <victim_file> option\n",
3063                                 progname);
3064                         result = -EINVAL;
3065                         goto error;
3066                 }
3067         }
3068
3069         /* Only LCME_FL_INIT flags is used in PFL, and it shouldn't be
3070          * altered by user space tool, so we don't need to support the
3071          * --component-set for this moment. */
3072         if (comp_set && !comp_id) {
3073                 fprintf(stderr, "%s %s: --component-set doesn't have component-id set\n",
3074                         progname, argv[0]);
3075                 goto usage_error;
3076         }
3077
3078         if ((delete + comp_set + comp_del + comp_add) > 1) {
3079                 fprintf(stderr,
3080                         "%s %s: options --component-set, --component-del, --component-add and -d are mutually exclusive\n",
3081                         progname, argv[0]);
3082                 goto usage_error;
3083         }
3084
3085         if (delete && (setstripe_args_specified(&lsa) || comp_id != 0 ||
3086                        lsa.lsa_comp_flags != 0 || layout != NULL)) {
3087                 fprintf(stderr,
3088                         "%s %s: option -d is mutually exclusive with -s, -c, -o, -p, -I, -F and -E options\n",
3089                         progname, argv[0]);
3090                 goto usage_error;
3091         }
3092
3093         if ((comp_set || comp_del) &&
3094             (setstripe_args_specified(&lsa) || layout != NULL)) {
3095                 fprintf(stderr,
3096                         "%s %s: options --component-del and --component-set are mutually exclusive when used with -c, -E, -o, -p, or -s\n",
3097                         progname, argv[0]);
3098                 goto usage_error;
3099         }
3100
3101         if (comp_del && comp_id != 0 && lsa.lsa_comp_flags != 0) {
3102                 fprintf(stderr,
3103                         "%s %s: options -I and -F are mutually exclusive when used with --component-del\n",
3104                         progname, argv[0]);
3105                 goto usage_error;
3106         }
3107
3108         if (comp_add || comp_del) {
3109                 struct stat st;
3110
3111                 result = lstat(fname, &st);
3112                 if (result == 0 && S_ISDIR(st.st_mode)) {
3113                         fprintf(stderr,
3114                                 "%s setstripe: cannot use --component-add or --component-del for directory\n",
3115                                 progname);
3116                         goto usage_error;
3117                 }
3118
3119                 if (mirror_mode) {
3120                         fprintf(stderr, "error: %s: can't use --component-add "
3121                                 "or --component-del for mirror operation\n",
3122                                 progname);
3123                         goto usage_error;
3124                 }
3125         }
3126
3127         if (comp_add) {
3128                 if (layout == NULL) {
3129                         fprintf(stderr,
3130                                 "%s %s: option -E must be specified with --component-add\n",
3131                                 progname, argv[0]);
3132                         goto usage_error;
3133                 }
3134
3135                 result = adjust_first_extent(fname, layout);
3136                 if (result == -ENODATA)
3137                         comp_add = 0;
3138                 else if (result != 0)
3139                         goto error;
3140         }
3141
3142         if (from_yaml && from_copy) {
3143                 fprintf(stderr,
3144                         "%s: can't specify --yaml and --copy together\n",
3145                         progname);
3146                 goto error;
3147         }
3148
3149         if ((from_yaml || from_copy) &&
3150             (setstripe_args_specified(&lsa) || layout != NULL)) {
3151                 fprintf(stderr, "error: %s: can't specify --yaml with "
3152                         "-c, -S, -i, -o, -p or -E options.\n",
3153                         argv[0]);
3154                 goto error;
3155         }
3156
3157         if ((migration_flags & MIGRATION_NONBLOCK) && migration_block) {
3158                 fprintf(stderr,
3159                         "%s %s: options --non-block and --block are mutually exclusive\n",
3160                         progname, argv[0]);
3161                 goto usage_error;
3162         }
3163
3164         if (!comp_del && !comp_set && (opc != SO_MIRROR_SPLIT) &&
3165             comp_id != 0) {
3166                 fprintf(stderr,
3167                 "%s %s: option -I can only be used with --component-del or --component-set or lfs mirror split\n",
3168                         progname, argv[0]);
3169                 goto usage_error;
3170         }
3171
3172         if (migrate_mdt_mode) {
3173                 struct lmv_user_md *lmu;
3174
3175                 /* initialize migrate mdt parameters */
3176                 lmu = calloc(1, lmv_user_md_size(lsa.lsa_nr_tgts,
3177                                                  LMV_USER_MAGIC_SPECIFIC));
3178                 if (!lmu) {
3179                         fprintf(stderr,
3180                                 "%s %s: cannot allocate memory for lmv_user_md: %s\n",
3181                                 progname, argv[0], strerror(ENOMEM));
3182                         result = -ENOMEM;
3183                         goto error;
3184                 }
3185                 if (lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT)
3186                         lmu->lum_stripe_count = lsa.lsa_stripe_count;
3187                 if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT) {
3188                         fprintf(stderr,
3189                                 "%s %s: migrate should specify MDT index\n",
3190                                 progname, argv[0]);
3191                         free(lmu);
3192                         goto usage_error;
3193                 }
3194                 lmu->lum_stripe_offset = lsa.lsa_stripe_off;
3195                 if (lsa.lsa_pattern != LLAPI_LAYOUT_RAID0)
3196                         lmu->lum_hash_type = lsa.lsa_pattern;
3197                 else
3198                         lmu->lum_hash_type = LMV_HASH_TYPE_FNV_1A_64;
3199                 if (lsa.lsa_pool_name)
3200                         strncpy(lmu->lum_pool_name, lsa.lsa_pool_name,
3201                                 sizeof(lmu->lum_pool_name));
3202                 if (lsa.lsa_nr_tgts > 1) {
3203                         int i;
3204
3205                         if (lsa.lsa_stripe_count > 0 &&
3206                             lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT &&
3207                             lsa.lsa_stripe_count != lsa.lsa_nr_tgts) {
3208                                 fprintf(stderr,
3209                                         "error: %s: stripe count %lld doesn't match the number of MDTs: %d\n",
3210                                         progname, lsa.lsa_stripe_count,
3211                                                 lsa.lsa_nr_tgts);
3212                                 free(lmu);
3213                                 goto usage_error;
3214                         }
3215
3216                         lmu->lum_magic = LMV_USER_MAGIC_SPECIFIC;
3217                         lmu->lum_stripe_count = lsa.lsa_nr_tgts;
3218                         for (i = 0; i < lsa.lsa_nr_tgts; i++)
3219                                 lmu->lum_objects[i].lum_mds = lsa.lsa_tgts[i];
3220                 } else {
3221                         lmu->lum_magic = LMV_USER_MAGIC;
3222                 }
3223
3224                 migrate_mdt_param.fp_lmv_md = lmu;
3225                 migrate_mdt_param.fp_migrate = 1;
3226         } else if (layout == NULL) {
3227                 /* initialize stripe parameters */
3228                 param = calloc(1, offsetof(typeof(*param),
3229                                lsp_osts[lsa.lsa_nr_tgts]));
3230                 if (param == NULL) {
3231                         fprintf(stderr,
3232                                 "%s %s: cannot allocate memory for parameters: %s\n",
3233                                 progname, argv[0], strerror(ENOMEM));
3234                         result = -ENOMEM;
3235                         goto error;
3236                 }
3237
3238                 if (lsa.lsa_stripe_size != LLAPI_LAYOUT_DEFAULT)
3239                         param->lsp_stripe_size = lsa.lsa_stripe_size;
3240                 if (lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT) {
3241                         if (lsa.lsa_stripe_count == LLAPI_LAYOUT_WIDE)
3242                                 param->lsp_stripe_count = -1;
3243                         else
3244                                 param->lsp_stripe_count = lsa.lsa_stripe_count;
3245                 }
3246                 if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
3247                         param->lsp_stripe_offset = -1;
3248                 else
3249                         param->lsp_stripe_offset = lsa.lsa_stripe_off;
3250                 param->lsp_pool = lsa.lsa_pool_name;
3251                 param->lsp_is_specific = false;
3252                 if (lsa.lsa_nr_tgts > 0) {
3253                         if (lsa.lsa_stripe_count > 0 &&
3254                             lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT &&
3255                             lsa.lsa_stripe_count != LLAPI_LAYOUT_WIDE &&
3256                             lsa.lsa_nr_tgts != lsa.lsa_stripe_count) {
3257                                 fprintf(stderr, "error: %s: stripe count %lld "
3258                                         "doesn't match the number of OSTs: %d\n"
3259                                         , argv[0], lsa.lsa_stripe_count,
3260                                         lsa.lsa_nr_tgts);
3261                                 free(param);
3262                                 goto usage_error;
3263                         }
3264
3265                         param->lsp_is_specific = true;
3266                         param->lsp_stripe_count = lsa.lsa_nr_tgts;
3267                         memcpy(param->lsp_osts, tgts,
3268                                sizeof(*tgts) * lsa.lsa_nr_tgts);
3269                 }
3270         }
3271
3272         if (from_yaml) {
3273                 /* generate a layout from a YAML template */
3274                 result = lfs_comp_create_from_yaml(template, &layout,
3275                                                    &lsa, tgts);
3276                 if (result) {
3277                         fprintf(stderr, "error: %s: can't create composite "
3278                                 "layout from template file %s\n",
3279                                 argv[0], template);
3280                         goto error;
3281                 }
3282         } else if (from_copy) {
3283                 layout = llapi_layout_get_by_path(template, 0);
3284                 if (layout == NULL) {
3285                         fprintf(stderr,
3286                             "%s: can't create composite layout from file %s.\n",
3287                                 progname, template);
3288                         goto error;
3289                 }
3290         }
3291
3292         for (fname = argv[optind]; fname != NULL; fname = argv[++optind]) {
3293                 if (migrate_mdt_mode) {
3294                         result = llapi_migrate_mdt(fname, &migrate_mdt_param);
3295                 } else if (migrate_mode) {
3296                         result = lfs_migrate(fname, migration_flags, param,
3297                                              layout);
3298                 } else if (comp_set != 0) {
3299                         result = lfs_component_set(fname, comp_id,
3300                                                    lsa.lsa_comp_flags,
3301                                                    lsa.lsa_comp_neg_flags);
3302                 } else if (comp_del != 0) {
3303                         result = lfs_component_del(fname, comp_id,
3304                                                    lsa.lsa_comp_flags,
3305                                                    lsa.lsa_comp_neg_flags);
3306                 } else if (comp_add != 0) {
3307                         result = lfs_component_add(fname, layout);
3308                 } else if (opc == SO_MIRROR_CREATE) {
3309                         result = mirror_create(fname, mirror_list);
3310                 } else if (opc == SO_MIRROR_EXTEND) {
3311                         result = mirror_extend(fname, mirror_list,
3312                                                mirror_flags);
3313                 } else if (opc == SO_MIRROR_SPLIT) {
3314                         if (mirror_id == 0 && comp_id == 0) {
3315                                 fprintf(stderr,
3316                         "%s %s: no mirror id or component id is specified\n",
3317                                         progname, argv[0]);
3318                                 goto usage_error;
3319                         }
3320                         if (mirror_id != 0)
3321                                 comp_id = mirror_id;
3322                         else
3323                                 mirror_flags |= MF_COMP_ID;
3324                         result = mirror_split(fname, comp_id, mirror_flags,
3325                                               has_m_file ? mirror_list->m_file :
3326                                               NULL);
3327                 } else if (layout != NULL) {
3328                         result = lfs_component_create(fname, O_CREAT | O_WRONLY,
3329                                                       0666, layout);
3330                         if (result >= 0) {
3331                                 close(result);
3332                                 result = 0;
3333                         }
3334                 } else {
3335                         result = llapi_file_open_param(fname,
3336                                                        O_CREAT | O_WRONLY,
3337                                                        0666, param);
3338                         if (result >= 0) {
3339                                 close(result);
3340                                 result = 0;
3341                         }
3342                 }
3343                 if (result) {
3344                         /* Save the first error encountered. */
3345                         if (result2 == 0)
3346                                 result2 = result;
3347                         continue;
3348                 }
3349         }
3350
3351         free(param);
3352         free(migrate_mdt_param.fp_lmv_md);
3353         llapi_layout_free(layout);
3354         lfs_mirror_list_free(mirror_list);
3355         return result2;
3356 usage_error:
3357         result = CMD_HELP;
3358 error:
3359         llapi_layout_free(layout);
3360         lfs_mirror_list_free(mirror_list);
3361         return result;
3362 }
3363
3364 static int lfs_poollist(int argc, char **argv)
3365 {
3366         if (argc != 2)
3367                 return CMD_HELP;
3368
3369         return llapi_poollist(argv[1]);
3370 }
3371
3372 static int set_time(time_t *time, time_t *set, char *str)
3373 {
3374         time_t t;
3375         int res = 0;
3376         char *endptr;
3377
3378         if (str[0] == '+')
3379                 res = 1;
3380         else if (str[0] == '-')
3381                 res = -1;
3382
3383         if (res)
3384                 str++;
3385
3386         t = strtol(str, &endptr, 0);
3387         if (*endptr != '\0') {
3388                 fprintf(stderr,
3389                         "%s find: bad time '%s': %s\n",
3390                         progname, str, strerror(EINVAL));
3391                 return INT_MAX;
3392         }
3393         if (*time < t * 24 * 60 * 60) {
3394                 if (res != 0)
3395                         str--;
3396                 fprintf(stderr,
3397                         "%s find: bad time '%s': too large\n",
3398                         progname, str);
3399                 return INT_MAX;
3400         }
3401
3402         *set = *time - t * 24 * 60 * 60;
3403         return res;
3404 }
3405
3406 static int name2uid(unsigned int *id, const char *name)
3407 {
3408         struct passwd *passwd;
3409
3410         passwd = getpwnam(name);
3411         if (passwd == NULL)
3412                 return -ENOENT;
3413         *id = passwd->pw_uid;
3414
3415         return 0;
3416 }
3417
3418 static int name2gid(unsigned int *id, const char *name)
3419 {
3420         struct group *group;
3421
3422         group = getgrnam(name);
3423         if (group == NULL)
3424                 return -ENOENT;
3425         *id = group->gr_gid;
3426
3427         return 0;
3428 }
3429
3430 static inline int name2projid(unsigned int *id, const char *name)
3431 {
3432         return -ENOTSUP;
3433 }
3434
3435 static int uid2name(char **name, unsigned int id)
3436 {
3437         struct passwd *passwd;
3438
3439         passwd = getpwuid(id);
3440         if (passwd == NULL)
3441                 return -ENOENT;
3442         *name = passwd->pw_name;
3443
3444         return 0;
3445 }
3446
3447 static inline int gid2name(char **name, unsigned int id)
3448 {
3449         struct group *group;
3450
3451         group = getgrgid(id);
3452         if (group == NULL)
3453                 return -ENOENT;
3454         *name = group->gr_name;
3455
3456         return 0;
3457 }
3458
3459 static int name2layout(__u32 *layout, char *name)
3460 {
3461         char *ptr, *layout_name;
3462
3463         *layout = 0;
3464         for (ptr = name; ; ptr = NULL) {
3465                 layout_name = strtok(ptr, ",");
3466                 if (layout_name == NULL)
3467                         break;
3468                 if (strcmp(layout_name, "released") == 0)
3469                         *layout |= LOV_PATTERN_F_RELEASED;
3470                 else if (strcmp(layout_name, "raid0") == 0)
3471                         *layout |= LOV_PATTERN_RAID0;
3472                 else if (strcmp(layout_name, "mdt") == 0)
3473                         *layout |= LOV_PATTERN_MDT;
3474                 else
3475                         return -1;
3476         }
3477         return 0;
3478 }
3479
3480 static int lfs_find(int argc, char **argv)
3481 {
3482         int c, rc;
3483         int ret = 0;
3484         time_t t;
3485         struct find_param param = {
3486                 .fp_max_depth = -1,
3487                 .fp_quiet = 1,
3488         };
3489         struct option long_opts[] = {
3490         { .val = 'A',   .name = "atime",        .has_arg = required_argument },
3491         { .val = 'b',   .name = "blocks",       .has_arg = required_argument },
3492         { .val = LFS_COMP_COUNT_OPT,
3493                         .name = "comp-count",   .has_arg = required_argument },
3494         { .val = LFS_COMP_COUNT_OPT,
3495                         .name = "component-count",
3496                                                 .has_arg = required_argument },
3497         { .val = LFS_COMP_FLAGS_OPT,
3498                         .name = "comp-flags",   .has_arg = required_argument },
3499         { .val = LFS_COMP_FLAGS_OPT,
3500                         .name = "component-flags",
3501                                                 .has_arg = required_argument },
3502         { .val = LFS_COMP_START_OPT,
3503                         .name = "comp-start",   .has_arg = required_argument },
3504         { .val = LFS_COMP_START_OPT,
3505                         .name = "component-start",
3506                                                 .has_arg = required_argument },
3507         { .val = LFS_MIRROR_STATE_OPT,
3508                         .name = "mirror-state", .has_arg = required_argument },
3509         { .val = 'c',   .name = "stripe-count", .has_arg = required_argument },
3510         { .val = 'c',   .name = "stripe_count", .has_arg = required_argument },
3511         { .val = 'C',   .name = "ctime",        .has_arg = required_argument },
3512 /* getstripe { .val = 'd', .name = "directory", .has_arg = no_argument }, */
3513         { .val = 'D',   .name = "maxdepth",     .has_arg = required_argument },
3514         { .val = 'E',   .name = "comp-end",     .has_arg = required_argument },
3515         { .val = 'E',   .name = "component-end",
3516                                                 .has_arg = required_argument },
3517 /* find { .val = 'F',   .name = "fid",          .has_arg = no_argument }, */
3518         { .val = 'g',   .name = "gid",          .has_arg = required_argument },
3519         { .val = 'G',   .name = "group",        .has_arg = required_argument },
3520         { .val = 'H',   .name = "mdt-hash",     .has_arg = required_argument },
3521         { .val = 'i',   .name = "stripe-index", .has_arg = required_argument },
3522         { .val = 'i',   .name = "stripe_index", .has_arg = required_argument },
3523 /* getstripe { .val = 'I', .name = "comp-id",   .has_arg = required_argument }*/
3524         { .val = 'L',   .name = "layout",       .has_arg = required_argument },
3525         { .val = 'm',   .name = "mdt",          .has_arg = required_argument },
3526         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument },
3527         { .val = 'm',   .name = "mdt_index",    .has_arg = required_argument },
3528         { .val = 'M',   .name = "mtime",        .has_arg = required_argument },
3529         { .val = 'n',   .name = "name",         .has_arg = required_argument },
3530         { .val = 'N',   .name = "mirror-count", .has_arg = required_argument },
3531 /* find { .val = 'o'    .name = "or", .has_arg = no_argument }, like find(1) */
3532         { .val = 'O',   .name = "obd",          .has_arg = required_argument },
3533         { .val = 'O',   .name = "ost",          .has_arg = required_argument },
3534         /* no short option for pool yet, can be 'p' after 2.18 */
3535         { .val = LFS_POOL_OPT,
3536                         .name = "pool",         .has_arg = required_argument },
3537         { .val = '0',   .name = "print0",       .has_arg = no_argument },
3538         { .val = 'P',   .name = "print",        .has_arg = no_argument },
3539         { .val = LFS_PROJID_OPT,
3540                         .name = "projid",       .has_arg = required_argument },
3541 /* getstripe { .val = 'q', .name = "quiet",     .has_arg = no_argument }, */
3542 /* getstripe { .val = 'r', .name = "recursive", .has_arg = no_argument }, */
3543 /* getstripe { .val = 'R', .name = "raw",       .has_arg = no_argument }, */
3544         { .val = 's',   .name = "size",         .has_arg = required_argument },
3545         { .val = 'S',   .name = "stripe-size",  .has_arg = required_argument },
3546         { .val = 'S',   .name = "stripe_size",  .has_arg = required_argument },
3547         { .val = 't',   .name = "type",         .has_arg = required_argument },
3548         { .val = 'T',   .name = "mdt-count",    .has_arg = required_argument },
3549         { .val = 'u',   .name = "uid",          .has_arg = required_argument },
3550         { .val = 'U',   .name = "user",         .has_arg = required_argument },
3551 /* getstripe { .val = 'v', .name = "verbose",   .has_arg = no_argument }, */
3552 /* getstripe { .val = 'y', .name = "yaml",      .has_arg = no_argument }, */
3553         { .name = NULL } };
3554         int pathstart = -1;
3555         int pathend = -1;
3556         int neg_opt = 0;
3557         time_t *xtime;
3558         int *xsign;
3559         int isoption;
3560         char *endptr;
3561
3562         time(&t);
3563
3564         /* when getopt_long_only() hits '!' it returns 1, puts "!" in optarg */
3565         while ((c = getopt_long_only(argc, argv,
3566                         "-0A:b:c:C:D:E:g:G:H:i:L:m:M:n:N:O:Ppqrs:S:t:T:u:U:v",
3567                         long_opts, NULL)) >= 0) {
3568                 xtime = NULL;
3569                 xsign = NULL;
3570                 if (neg_opt)
3571                         --neg_opt;
3572                 /* '!' is part of option */
3573                 /* when getopt_long_only() finds a string which is not
3574                  * an option nor a known option argument it returns 1
3575                  * in that case if we already have found pathstart and pathend
3576                  * (i.e. we have the list of pathnames),
3577                  * the only supported value is "!"
3578                  */
3579                 isoption = (c != 1) || (strcmp(optarg, "!") == 0);
3580                 if (!isoption && pathend != -1) {
3581                         fprintf(stderr, "err: %s: filename|dirname must either "
3582                                         "precede options or follow options\n",
3583                                         argv[0]);
3584                         ret = CMD_HELP;
3585                         goto err;
3586                 }
3587                 if (!isoption && pathstart == -1)
3588                         pathstart = optind - 1;
3589                 if (isoption && pathstart != -1 && pathend == -1)
3590                         pathend = optind - 2;
3591                 switch (c) {
3592                 case 0:
3593                         /* Long options. */
3594                         break;
3595                 case 1:
3596                         /* unknown; opt is "!" or path component,
3597                          * checking done above.
3598                          */
3599                         if (strcmp(optarg, "!") == 0)
3600                                 neg_opt = 2;
3601                         break;
3602                 case 'A':
3603                         xtime = &param.fp_atime;
3604                         xsign = &param.fp_asign;
3605                         param.fp_exclude_atime = !!neg_opt;
3606                         /* no break, this falls through to 'C' for ctime */
3607                 case 'C':
3608                         if (c == 'C') {
3609                                 xtime = &param.fp_ctime;
3610                                 xsign = &param.fp_csign;
3611                                 param.fp_exclude_ctime = !!neg_opt;
3612                         }
3613                         /* no break, this falls through to 'M' for mtime */
3614                 case 'M':
3615                         if (c == 'M') {
3616                                 xtime = &param.fp_mtime;
3617                                 xsign = &param.fp_msign;
3618                                 param.fp_exclude_mtime = !!neg_opt;
3619                         }
3620                         rc = set_time(&t, xtime, optarg);
3621                         if (rc == INT_MAX) {
3622                                 ret = -1;
3623                                 goto err;
3624                         }
3625                         if (rc)
3626                                 *xsign = rc;
3627                         break;
3628                 case 'b':
3629                         if (optarg[0] == '+') {
3630                                 param.fp_blocks_sign = -1;
3631                                 optarg++;
3632                         } else if (optarg[0] == '-') {
3633                                 param.fp_blocks_sign =  1;
3634                                 optarg++;
3635                         }
3636
3637                         param.fp_blocks_units = 1024;
3638                         ret = llapi_parse_size(optarg, &param.fp_blocks,
3639                                                &param.fp_blocks_units, 0);
3640                         if (ret) {
3641                                 fprintf(stderr, "error: bad blocks '%s'\n",
3642                                         optarg);
3643                                 goto err;
3644                         }
3645                         param.fp_check_blocks = 1;
3646                         param.fp_exclude_blocks = !!neg_opt;
3647                         break;
3648                 case LFS_COMP_COUNT_OPT:
3649                         if (optarg[0] == '+') {
3650                                 param.fp_comp_count_sign = -1;
3651                                 optarg++;
3652                         } else if (optarg[0] == '-') {
3653                                 param.fp_comp_count_sign =  1;
3654                                 optarg++;
3655                         }
3656
3657                         param.fp_comp_count = strtoul(optarg, &endptr, 0);
3658                         if (*endptr != '\0') {
3659                                 fprintf(stderr, "error: bad component count "
3660                                         "'%s'\n", optarg);
3661                                 goto err;
3662                         }
3663                         param.fp_check_comp_count = 1;
3664                         param.fp_exclude_comp_count = !!neg_opt;
3665                         break;
3666                 case LFS_COMP_FLAGS_OPT:
3667                         rc = comp_str2flags(optarg, &param.fp_comp_flags,
3668                                             &param.fp_comp_neg_flags);
3669                         if (rc) {
3670                                 fprintf(stderr, "error: bad component flags "
3671                                         "'%s'\n", optarg);
3672                                 goto err;
3673                         }
3674                         param.fp_check_comp_flags = 1;
3675                         if (neg_opt) {
3676                                 __u32 flags = param.fp_comp_neg_flags;
3677                                 param.fp_comp_neg_flags = param.fp_comp_flags;
3678                                 param.fp_comp_flags = flags;
3679                         }
3680                         break;
3681                 case LFS_COMP_START_OPT:
3682                         if (optarg[0] == '+') {
3683                                 param.fp_comp_start_sign = -1;
3684                                 optarg++;
3685                         } else if (optarg[0] == '-') {
3686                                 param.fp_comp_start_sign =  1;
3687                                 optarg++;
3688                         }
3689
3690                         rc = llapi_parse_size(optarg, &param.fp_comp_start,
3691                                               &param.fp_comp_start_units, 0);
3692                         if (rc) {
3693                                 fprintf(stderr, "error: bad component start "
3694                                         "'%s'\n", optarg);
3695                                 goto err;
3696                         }
3697                         param.fp_check_comp_start = 1;
3698                         param.fp_exclude_comp_start = !!neg_opt;
3699                         break;
3700                 case LFS_MIRROR_STATE_OPT:
3701                         rc = mirror_str2state(optarg, &param.fp_mirror_state,
3702                                               &param.fp_mirror_neg_state);
3703                         if (rc) {
3704                                 fprintf(stderr,
3705                                         "error: bad mirrored file state '%s'\n",
3706                                         optarg);
3707                                 goto err;
3708                         }
3709                         param.fp_check_mirror_state = 1;
3710                         if (neg_opt) {
3711                                 __u16 state = param.fp_mirror_neg_state;
3712                                 param.fp_mirror_neg_state =
3713                                         param.fp_mirror_state;
3714                                 param.fp_mirror_state = state;
3715                         }
3716                         break;
3717                 case 'c':
3718                         if (optarg[0] == '+') {
3719                                 param.fp_stripe_count_sign = -1;
3720                                 optarg++;
3721                         } else if (optarg[0] == '-') {
3722                                 param.fp_stripe_count_sign =  1;
3723                                 optarg++;
3724                         }
3725
3726                         param.fp_stripe_count = strtoul(optarg, &endptr, 0);
3727                         if (*endptr != '\0') {
3728                                 fprintf(stderr,"error: bad stripe_count '%s'\n",
3729                                         optarg);
3730                                 ret = -1;
3731                                 goto err;
3732                         }
3733                         param.fp_check_stripe_count = 1;
3734                         param.fp_exclude_stripe_count = !!neg_opt;
3735                         break;
3736                 case 'D':
3737                         param.fp_max_depth = strtol(optarg, 0, 0);
3738                         break;
3739                 case 'E':
3740                         if (optarg[0] == '+') {
3741                                 param.fp_comp_end_sign = -1;
3742                                 optarg++;
3743                         } else if (optarg[0] == '-') {
3744                                 param.fp_comp_end_sign =  1;
3745                                 optarg++;
3746                         }
3747
3748                         if (arg_is_eof(optarg)) {
3749                                 param.fp_comp_end = LUSTRE_EOF;
3750                                 param.fp_comp_end_units = 1;
3751                                 rc = 0;
3752                         } else {
3753                                 rc = llapi_parse_size(optarg,
3754                                                 &param.fp_comp_end,
3755                                                 &param.fp_comp_end_units, 0);
3756                         }
3757                         if (rc) {
3758                                 fprintf(stderr, "error: bad component end "
3759                                         "'%s'\n", optarg);
3760                                 goto err;
3761                         }
3762                         param.fp_check_comp_end = 1;
3763                         param.fp_exclude_comp_end = !!neg_opt;
3764                         break;
3765                 case 'g':
3766                 case 'G':
3767                         rc = name2gid(&param.fp_gid, optarg);
3768                         if (rc) {
3769                                 param.fp_gid = strtoul(optarg, &endptr, 10);
3770                                 if (*endptr != '\0') {
3771                                         fprintf(stderr, "Group/GID: %s cannot "
3772                                                 "be found.\n", optarg);
3773                                         ret = -1;
3774                                         goto err;
3775                                 }
3776                         }
3777                         param.fp_exclude_gid = !!neg_opt;
3778                         param.fp_check_gid = 1;
3779                         break;
3780                 case 'H':
3781                         param.fp_hash_type = check_hashtype(optarg);
3782                         if (param.fp_hash_type == 0) {
3783                                 fprintf(stderr, "error: bad hash_type '%s'\n",
3784                                         optarg);
3785                                 ret = -1;
3786                                 goto err;
3787                         }
3788                         param.fp_check_hash_type = 1;
3789                         param.fp_exclude_hash_type = !!neg_opt;
3790                         break;
3791                 case 'L':
3792                         ret = name2layout(&param.fp_layout, optarg);
3793                         if (ret)
3794                                 goto err;
3795                         param.fp_exclude_layout = !!neg_opt;
3796                         param.fp_check_layout = 1;
3797                         break;
3798                 case 'u':
3799                 case 'U':
3800                         rc = name2uid(&param.fp_uid, optarg);
3801                         if (rc) {
3802                                 param.fp_uid = strtoul(optarg, &endptr, 10);
3803                                 if (*endptr != '\0') {
3804                                         fprintf(stderr, "User/UID: %s cannot "
3805                                                 "be found.\n", optarg);
3806                                         ret = -1;
3807                                         goto err;
3808                                 }
3809                         }
3810                         param.fp_exclude_uid = !!neg_opt;
3811                         param.fp_check_uid = 1;
3812                         break;
3813                 case 'n':
3814                         param.fp_pattern = (char *)optarg;
3815                         param.fp_exclude_pattern = !!neg_opt;
3816                         break;
3817                 case 'N':
3818                         if (optarg[0] == '+') {
3819                                 param.fp_mirror_count_sign = -1;
3820                                 optarg++;
3821                         } else if (optarg[0] == '-') {
3822                                 param.fp_mirror_count_sign =  1;
3823                                 optarg++;
3824                         }
3825
3826                         param.fp_mirror_count = strtoul(optarg, &endptr, 0);
3827                         if (*endptr != '\0') {
3828                                 fprintf(stderr,
3829                                         "error: bad mirror count '%s'\n",
3830                                         optarg);
3831                                 goto err;
3832                         }
3833                         param.fp_check_mirror_count = 1;
3834                         param.fp_exclude_mirror_count = !!neg_opt;
3835                         break;
3836                 case 'm':
3837                 case 'i':
3838                 case 'O': {
3839                         char *buf, *token, *next, *p;
3840                         int len = 1;
3841                         void *tmp;
3842
3843                         buf = strdup(optarg);
3844                         if (buf == NULL) {
3845                                 ret = -ENOMEM;
3846                                 goto err;
3847                         }
3848
3849                         param.fp_exclude_obd = !!neg_opt;
3850
3851                         token = buf;
3852                         while (token && *token) {
3853                                 token = strchr(token, ',');
3854                                 if (token) {
3855                                         len++;
3856                                         token++;
3857                                 }
3858                         }
3859                         if (c == 'm') {
3860                                 param.fp_exclude_mdt = !!neg_opt;
3861                                 param.fp_num_alloc_mdts += len;
3862                                 tmp = realloc(param.fp_mdt_uuid,
3863                                               param.fp_num_alloc_mdts *
3864                                               sizeof(*param.fp_mdt_uuid));
3865                                 if (tmp == NULL) {
3866                                         ret = -ENOMEM;
3867                                         goto err_free;
3868                                 }
3869
3870                                 param.fp_mdt_uuid = tmp;
3871                         } else {
3872                                 param.fp_exclude_obd = !!neg_opt;
3873                                 param.fp_num_alloc_obds += len;
3874                                 tmp = realloc(param.fp_obd_uuid,
3875                                               param.fp_num_alloc_obds *
3876                                               sizeof(*param.fp_obd_uuid));
3877                                 if (tmp == NULL) {
3878                                         ret = -ENOMEM;
3879                                         goto err_free;
3880                                 }
3881
3882                                 param.fp_obd_uuid = tmp;
3883                         }
3884                         for (token = buf; token && *token; token = next) {
3885                                 struct obd_uuid *puuid;
3886                                 if (c == 'm') {
3887                                         puuid =
3888                                         &param.fp_mdt_uuid[param.fp_num_mdts++];
3889                                 } else {
3890                                         puuid =
3891                                         &param.fp_obd_uuid[param.fp_num_obds++];
3892                                 }
3893                                 p = strchr(token, ',');
3894                                 next = 0;
3895                                 if (p) {
3896                                         *p = 0;
3897                                         next = p+1;
3898                                 }
3899
3900                                 if (strlen(token) > sizeof(puuid->uuid) - 1) {
3901                                         ret = -E2BIG;
3902                                         goto err_free;
3903                                 }
3904
3905                                 strncpy(puuid->uuid, token,
3906                                         sizeof(puuid->uuid));
3907                         }
3908 err_free:
3909                         if (buf)
3910                                 free(buf);
3911                         break;
3912                 }
3913 #if LUSTRE_VERSION_CODE >= OBD_OCD_VERSION(2, 18, 53, 0)
3914                 case 'p':
3915 #endif
3916                 case LFS_POOL_OPT:
3917                         if (strlen(optarg) > LOV_MAXPOOLNAME) {
3918                                 fprintf(stderr,
3919                                         "Pool name %s is too long (max %d)\n",
3920                                         optarg, LOV_MAXPOOLNAME);
3921                                 ret = -1;
3922                                 goto err;
3923                         }
3924                         /*
3925                          * We do check for empty pool because empty pool
3926                          * is used to find V1 LOV attributes
3927                          */
3928                         strncpy(param.fp_poolname, optarg, LOV_MAXPOOLNAME);
3929                         param.fp_poolname[LOV_MAXPOOLNAME] = '\0';
3930                         param.fp_exclude_pool = !!neg_opt;
3931                         param.fp_check_pool = 1;
3932                         break;
3933 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 14, 53, 0)
3934                 case 'p': /* want this for --pool, to match getstripe/find */
3935                         fprintf(stderr,
3936                                 "warning: -p deprecated, use --print0 or -0\n");
3937 #endif
3938                 case '0':
3939                         param.fp_zero_end = 1;
3940                         break;
3941                 case 'P': /* we always print, this option is a no-op */
3942                         break;
3943                 case LFS_PROJID_OPT:
3944                         rc = name2projid(&param.fp_projid, optarg);
3945                         if (rc) {
3946                                 param.fp_projid = strtoul(optarg, &endptr, 10);
3947                                 if (*endptr != '\0') {
3948                                         fprintf(stderr,
3949                                                 "Invalid project ID: %s",
3950                                                 optarg);
3951                                         ret = -1;
3952                                         goto err;
3953                                 }
3954                         }
3955                         param.fp_exclude_projid = !!neg_opt;
3956                         param.fp_check_projid = 1;
3957                         break;
3958                 case 's':
3959                         if (optarg[0] == '+') {
3960                                 param.fp_size_sign = -1;
3961                                 optarg++;
3962                         } else if (optarg[0] == '-') {
3963                                 param.fp_size_sign =  1;
3964                                 optarg++;
3965                         }
3966
3967                         ret = llapi_parse_size(optarg, &param.fp_size,
3968                                                &param.fp_size_units, 0);
3969                         if (ret) {
3970                                 fprintf(stderr, "error: bad file size '%s'\n",
3971                                         optarg);
3972                                 goto err;
3973                         }
3974                         param.fp_check_size = 1;
3975                         param.fp_exclude_size = !!neg_opt;
3976                         break;
3977                 case 'S':
3978                         if (optarg[0] == '+') {
3979                                 param.fp_stripe_size_sign = -1;
3980                                 optarg++;
3981                         } else if (optarg[0] == '-') {
3982                                 param.fp_stripe_size_sign =  1;
3983                                 optarg++;
3984                         }
3985
3986                         ret = llapi_parse_size(optarg, &param.fp_stripe_size,
3987                                                &param.fp_stripe_size_units, 0);
3988                         if (ret) {
3989                                 fprintf(stderr, "error: bad stripe_size '%s'\n",
3990                                         optarg);
3991                                 goto err;
3992                         }
3993                         param.fp_check_stripe_size = 1;
3994                         param.fp_exclude_stripe_size = !!neg_opt;
3995                         break;
3996                 case 't':
3997                         param.fp_exclude_type = !!neg_opt;
3998                         switch (optarg[0]) {
3999                         case 'b':
4000                                 param.fp_type = S_IFBLK;
4001                                 break;
4002                         case 'c':
4003                                 param.fp_type = S_IFCHR;
4004                                 break;
4005                         case 'd':
4006                                 param.fp_type = S_IFDIR;
4007                                 break;
4008                         case 'f':
4009                                 param.fp_type = S_IFREG;
4010                                 break;
4011                         case 'l':
4012                                 param.fp_type = S_IFLNK;
4013                                 break;
4014                         case 'p':
4015                                 param.fp_type = S_IFIFO;
4016                                 break;
4017                         case 's':
4018                                 param.fp_type = S_IFSOCK;
4019                                 break;
4020                         default:
4021                                 fprintf(stderr, "error: %s: bad type '%s'\n",
4022                                         argv[0], optarg);
4023                                 ret = CMD_HELP;
4024                                 goto err;
4025                         };
4026                         break;
4027                 case 'T':
4028                         if (optarg[0] == '+') {
4029                                 param.fp_mdt_count_sign = -1;
4030                                 optarg++;
4031                         } else if (optarg[0] == '-') {
4032                                 param.fp_mdt_count_sign =  1;
4033                                 optarg++;
4034                         }
4035
4036                         param.fp_mdt_count = strtoul(optarg, &endptr, 0);
4037                         if (*endptr != '\0') {
4038                                 fprintf(stderr, "error: bad mdt_count '%s'\n",
4039                                         optarg);
4040                                 ret = -1;
4041                                 goto err;
4042                         }
4043                         param.fp_check_mdt_count = 1;
4044                         param.fp_exclude_mdt_count = !!neg_opt;
4045                         break;
4046                 default:
4047                         ret = CMD_HELP;
4048                         goto err;
4049                 };
4050         }
4051
4052         if (pathstart == -1) {
4053                 fprintf(stderr, "error: %s: no filename|pathname\n",
4054                         argv[0]);
4055                 ret = CMD_HELP;
4056                 goto err;
4057         } else if (pathend == -1) {
4058                 /* no options */
4059                 pathend = argc;
4060         }
4061
4062         do {
4063                 rc = llapi_find(argv[pathstart], &param);
4064                 if (rc != 0 && ret == 0)
4065                         ret = rc;
4066         } while (++pathstart < pathend);
4067
4068         if (ret)
4069                 fprintf(stderr, "error: %s failed for %s.\n",
4070                         argv[0], argv[optind - 1]);
4071 err:
4072         if (param.fp_obd_uuid && param.fp_num_alloc_obds)
4073                 free(param.fp_obd_uuid);
4074
4075         if (param.fp_mdt_uuid && param.fp_num_alloc_mdts)
4076                 free(param.fp_mdt_uuid);
4077
4078         return ret;
4079 }
4080
4081 static int lfs_getstripe_internal(int argc, char **argv,
4082                                   struct find_param *param)
4083 {
4084         struct option long_opts[] = {
4085 /* find { .val = 'A',   .name = "atime",        .has_arg = required_argument }*/
4086 /* find { .val = 'b',   .name = "blocks",       .has_arg = required_argument }*/
4087         { .val = LFS_COMP_COUNT_OPT,
4088                         .name = "comp-count",   .has_arg = no_argument },
4089         { .val = LFS_COMP_COUNT_OPT,
4090                 .name = "component-count",      .has_arg = no_argument },
4091         { .val = LFS_COMP_FLAGS_OPT,
4092                         .name = "comp-flags",   .has_arg = optional_argument },
4093         { .val = LFS_COMP_FLAGS_OPT,
4094                 .name = "component-flags",      .has_arg = optional_argument },
4095         { .val = LFS_COMP_START_OPT,
4096                         .name = "comp-start",   .has_arg = optional_argument },
4097         { .val = LFS_COMP_START_OPT,
4098                 .name = "component-start",      .has_arg = optional_argument },
4099         { .val = LFS_MIRROR_INDEX_OPT,
4100                 .name = "mirror-index",         .has_arg = required_argument },
4101         { .val = LFS_MIRROR_ID_OPT,
4102                 .name = "mirror-id",            .has_arg = required_argument },
4103         { .val = 'c',   .name = "stripe-count", .has_arg = no_argument },
4104         { .val = 'c',   .name = "stripe_count", .has_arg = no_argument },
4105 /* find { .val = 'C',   .name = "ctime",        .has_arg = required_argument }*/
4106         { .val = 'd',   .name = "directory",    .has_arg = no_argument },
4107         { .val = 'D',   .name = "default",      .has_arg = no_argument },
4108         { .val = 'E',   .name = "comp-end",     .has_arg = optional_argument },
4109         { .val = 'E',   .name = "component-end", .has_arg = optional_argument },
4110         { .val = 'F',   .name = "fid",          .has_arg = no_argument },
4111         { .val = 'g',   .name = "generation",   .has_arg = no_argument },
4112 /* find { .val = 'G',   .name = "group",        .has_arg = required_argument }*/
4113 /* dirstripe { .val = 'H', .name = "mdt-hash",  .has_arg = required_argument }*/
4114         { .val = 'i',   .name = "stripe-index", .has_arg = no_argument },
4115         { .val = 'i',   .name = "stripe_index", .has_arg = no_argument },
4116         { .val = 'I',   .name = "comp-id",      .has_arg = optional_argument },
4117         { .val = 'I',   .name = "component-id", .has_arg = optional_argument },
4118         { .val = 'L',   .name = "layout",       .has_arg = no_argument },
4119         { .val = 'm',   .name = "mdt",          .has_arg = no_argument },
4120         { .val = 'm',   .name = "mdt-index",    .has_arg = no_argument },
4121         { .val = 'm',   .name = "mdt_index",    .has_arg = no_argument },
4122 /* find { .val = 'M',   .name = "mtime",        .has_arg = required_argument }*/
4123 /* find { .val = 'n',   .name = "name",         .has_arg = required_argument }*/
4124         { .val = 'O',   .name = "obd",          .has_arg = required_argument },
4125         { .val = 'O',   .name = "ost",          .has_arg = required_argument },
4126         { .val = 'p',   .name = "pool",         .has_arg = no_argument },
4127 /* find { .val = 'P',   .name = "print",        .has_arg = no_argument }, */
4128         { .val = 'q',   .name = "quiet",        .has_arg = no_argument },
4129         { .val = 'r',   .name = "recursive",    .has_arg = no_argument },
4130         { .val = 'R',   .name = "raw",          .has_arg = no_argument },
4131         { .val = 'S',   .name = "stripe-size",  .has_arg = no_argument },
4132         { .val = 'S',   .name = "stripe_size",  .has_arg = no_argument },
4133 /* find { .val = 't',   .name = "type",         .has_arg = required_argument }*/
4134 /* dirstripe { .val = 'T', .name = "mdt-count", .has_arg = required_argument }*/
4135 /* find { .val = 'u',   .name = "uid",          .has_arg = required_argument }*/
4136 /* find { .val = 'U',   .name = "user",         .has_arg = required_argument }*/
4137         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
4138         { .val = 'y',   .name = "yaml",         .has_arg = no_argument },
4139         { .name = NULL } };
4140         int c, rc;
4141         int neg_opt = 0;
4142         int pathstart = -1, pathend = -1;
4143         int isoption;
4144         char *end, *tmp;
4145
4146         while ((c = getopt_long(argc, argv,
4147                         "-cdDE::FghiI::LmMoO:pqrRsSvy",
4148                         long_opts, NULL)) != -1) {
4149                 if (neg_opt)
4150                         --neg_opt;
4151
4152                 /* '!' is part of option */
4153                 isoption = (c != 1) || (strcmp(optarg, "!") == 0);
4154                 if (!isoption && pathend != -1) {
4155                         fprintf(stderr,
4156                                 "error: %s: filename|dirname must either precede options or follow options\n",
4157                                 argv[0]);
4158                         return CMD_HELP;
4159                 }
4160                 if (!isoption && pathstart == -1)
4161                         pathstart = optind - 1;
4162                 if (isoption && pathstart != -1 && pathend == -1)
4163                         pathend = optind - 2;
4164
4165                 switch (c) {
4166                 case 1:
4167                         /* unknown: opt is "!" */
4168                         if (strcmp(optarg, "!") == 0)
4169                                 neg_opt = 2;
4170                         break;
4171                 case 'c':
4172                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
4173                                 param->fp_verbose |= VERBOSE_COUNT;
4174                                 param->fp_max_depth = 0;
4175                         }
4176                         break;
4177                 case LFS_COMP_COUNT_OPT:
4178                         param->fp_verbose |= VERBOSE_COMP_COUNT;
4179                         param->fp_max_depth = 0;
4180                         break;
4181                 case LFS_COMP_FLAGS_OPT:
4182                         if (optarg != NULL) {
4183                                 rc = comp_str2flags(optarg,
4184                                                     &param->fp_comp_flags,
4185                                                     &param->fp_comp_neg_flags);
4186                                 if (rc != 0) {
4187                                         fprintf(stderr, "error: %s bad "
4188                                                 "component flags '%s'.\n",
4189                                                 argv[0], optarg);
4190                                         return CMD_HELP;
4191                                 }
4192                                 param->fp_check_comp_flags = 1;
4193                         } else {
4194                                 param->fp_verbose |= VERBOSE_COMP_FLAGS;
4195                                 param->fp_max_depth = 0;
4196                         }
4197                         break;
4198                 case LFS_COMP_START_OPT:
4199                         if (optarg != NULL) {
4200                                 tmp = optarg;
4201                                 if (tmp[0] == '+') {
4202                                         param->fp_comp_start_sign = -1;
4203                                         tmp++;
4204                                 } else if (tmp[0] == '-') {
4205                                         param->fp_comp_start_sign = 1;
4206                                         tmp++;
4207                                 }
4208                                 rc = llapi_parse_size(tmp,
4209                                                 &param->fp_comp_start,
4210                                                 &param->fp_comp_start_units, 0);
4211                                 if (rc != 0) {
4212                                         fprintf(stderr, "error: %s bad "
4213                                                 "component start '%s'.\n",
4214                                                 argv[0], tmp);
4215                                         return CMD_HELP;
4216                                 } else {
4217                                         param->fp_check_comp_start = 1;
4218                                 }
4219                         } else {
4220                                 param->fp_verbose |= VERBOSE_COMP_START;
4221                                 param->fp_max_depth = 0;
4222                         }
4223                         break;
4224                 case LFS_MIRROR_INDEX_OPT:
4225                         if (optarg[0] == '+') {
4226                                 param->fp_mirror_index_sign = -1;
4227                                 optarg++;
4228                         } else if (optarg[0] == '-') {
4229                                 param->fp_mirror_index_sign = 1;
4230                                 optarg++;
4231                         }
4232
4233                         param->fp_mirror_index = strtoul(optarg, &end, 0);
4234                         if (*end != '\0' || (param->fp_mirror_index == 0 &&
4235                             param->fp_mirror_index_sign == 0 && neg_opt == 0)) {
4236                                 fprintf(stderr,
4237                                         "%s %s: invalid mirror index '%s'\n",
4238                                         progname, argv[0], optarg);
4239                                 return CMD_HELP;
4240                         }
4241                         if (param->fp_mirror_id != 0) {
4242                                 fprintf(stderr,
4243                                         "%s %s: can't specify both mirror index and mirror ID\n",
4244                                         progname, argv[0]);
4245                                 return CMD_HELP;
4246                         }
4247                         param->fp_check_mirror_index = 1;
4248                         param->fp_exclude_mirror_index = !!neg_opt;
4249                         break;
4250                 case LFS_MIRROR_ID_OPT:
4251                         if (optarg[0] == '+') {
4252                                 param->fp_mirror_id_sign = -1;
4253                                 optarg++;
4254                         } else if (optarg[0] == '-') {
4255                                 param->fp_mirror_id_sign = 1;
4256                                 optarg++;
4257                         }
4258
4259                         param->fp_mirror_id = strtoul(optarg, &end, 0);
4260                         if (*end != '\0' || (param->fp_mirror_id == 0 &&
4261                             param->fp_mirror_id_sign == 0 && neg_opt == 0)) {
4262                                 fprintf(stderr,
4263                                         "%s %s: invalid mirror ID '%s'\n",
4264                                         progname, argv[0], optarg);
4265                                 return CMD_HELP;
4266                         }
4267                         if (param->fp_mirror_index != 0) {
4268                                 fprintf(stderr,
4269                                         "%s %s: can't specify both mirror index and mirror ID\n",
4270                                         progname, argv[0]);
4271                                 return CMD_HELP;
4272                         }
4273                         param->fp_check_mirror_id = 1;
4274                         param->fp_exclude_mirror_id = !!neg_opt;
4275                         break;
4276                 case 'd':
4277                         param->fp_max_depth = 0;
4278                         break;
4279                 case 'D':
4280                         param->fp_get_default_lmv = 1;
4281                         break;
4282                 case 'E':
4283                         if (optarg != NULL) {
4284                                 tmp = optarg;
4285                                 if (tmp[0] == '+') {
4286                                         param->fp_comp_end_sign = -1;
4287                                         tmp++;
4288                                 } else if (tmp[0] == '-') {
4289                                         param->fp_comp_end_sign = 1;
4290                                         tmp++;
4291                                 }
4292
4293                                 if (arg_is_eof(tmp)) {
4294                                         param->fp_comp_end = LUSTRE_EOF;
4295                                         param->fp_comp_end_units = 1;
4296                                         rc = 0;
4297                                 } else {
4298                                         rc = llapi_parse_size(tmp,
4299                                                 &param->fp_comp_end,
4300                                                 &param->fp_comp_end_units, 0);
4301                                 }
4302                                 if (rc != 0) {
4303                                         fprintf(stderr, "error: %s bad "
4304                                                 "component end '%s'.\n",
4305                                                 argv[0], tmp);
4306                                         return CMD_HELP;
4307                                 }
4308                                 param->fp_check_comp_end = 1;
4309                         } else {
4310                                 param->fp_verbose |= VERBOSE_COMP_END;
4311                                 param->fp_max_depth = 0;
4312                         }
4313                         break;
4314                 case 'F':
4315                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
4316                                 param->fp_verbose |= VERBOSE_DFID;
4317                                 param->fp_max_depth = 0;
4318                         }
4319                         break;
4320                 case 'g':
4321                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
4322                                 param->fp_verbose |= VERBOSE_GENERATION;
4323                                 param->fp_max_depth = 0;
4324                         }
4325                         break;
4326                 case 'i':
4327                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
4328                                 param->fp_verbose |= VERBOSE_OFFSET;
4329                                 param->fp_max_depth = 0;
4330                         }
4331                         break;
4332                 case 'I':
4333                         if (optarg != NULL) {
4334                                 param->fp_comp_id = strtoul(optarg, &end, 0);
4335                                 if (*end != '\0' || param->fp_comp_id == 0 ||
4336                                     param->fp_comp_id > LCME_ID_MAX) {
4337                                         fprintf(stderr, "error: %s bad "
4338                                                 "component id '%s'\n",
4339                                                 argv[0], optarg);
4340                                         return CMD_HELP;
4341                                 } else {
4342                                         param->fp_check_comp_id = 1;
4343                                 }
4344                         } else {
4345                                 param->fp_max_depth = 0;
4346                                 param->fp_verbose |= VERBOSE_COMP_ID;
4347                         }
4348                         break;
4349                 case 'L':
4350                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
4351                                 param->fp_verbose |= VERBOSE_LAYOUT;
4352                                 param->fp_max_depth = 0;
4353                         }
4354                         break;
4355 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
4356                 case 'M':
4357                         fprintf(stderr, "warning: '-M' deprecated"
4358                                 ", use '--mdt-index' or '-m' instead\n");
4359 #endif
4360                 case 'm':
4361                         if (!(param->fp_verbose & VERBOSE_DETAIL))
4362                                 param->fp_max_depth = 0;
4363                         param->fp_verbose |= VERBOSE_MDTINDEX;
4364                         break;
4365                 case 'O':
4366                         if (param->fp_obd_uuid) {
4367                                 fprintf(stderr,
4368                                         "error: %s: only one obduuid allowed",
4369                                         argv[0]);
4370                                 return CMD_HELP;
4371                         }
4372                         param->fp_obd_uuid = (struct obd_uuid *)optarg;
4373                         break;
4374                 case 'p':
4375                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
4376                                 param->fp_verbose |= VERBOSE_POOL;
4377                                 param->fp_max_depth = 0;
4378                         }
4379                         break;
4380                 case 'q':
4381                         param->fp_quiet++;
4382                         break;
4383                 case 'r':
4384                         param->fp_recursive = 1;
4385                         break;
4386                 case 'R':
4387                         param->fp_raw = 1;
4388                         break;
4389                 case 'S':
4390                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
4391                                 param->fp_verbose |= VERBOSE_SIZE;
4392                                 param->fp_max_depth = 0;
4393                         }
4394                         break;
4395                 case 'v':
4396                         param->fp_verbose = VERBOSE_DEFAULT | VERBOSE_DETAIL;
4397                         break;
4398                 case 'y':
4399                         param->fp_yaml = 1;
4400                         break;
4401                 default:
4402                         return CMD_HELP;
4403                 }
4404         }
4405
4406         if (pathstart == -1) {
4407                 fprintf(stderr, "error: %s: no filename|pathname\n",
4408                                 argv[0]);
4409                 return CMD_HELP;
4410         } else if (pathend == -1) {
4411                 /* no options */
4412                 pathend = argc;
4413         }
4414
4415         if (pathend > argc)
4416                 return CMD_HELP;
4417
4418         if (param->fp_recursive)
4419                 param->fp_max_depth = -1;
4420         else if (param->fp_verbose & VERBOSE_DETAIL)
4421                 param->fp_max_depth = 1;
4422
4423         if (!param->fp_verbose)
4424                 param->fp_verbose = VERBOSE_DEFAULT;
4425         if (param->fp_quiet)
4426                 param->fp_verbose = VERBOSE_OBJID;
4427
4428         do {
4429                 rc = llapi_getstripe(argv[pathstart], param);
4430         } while (++pathstart < pathend && !rc);
4431
4432         if (rc)
4433                 fprintf(stderr, "error: %s failed for %s.\n",
4434                         argv[0], argv[optind - 1]);
4435         return rc;
4436 }
4437
4438 static int lfs_tgts(int argc, char **argv)
4439 {
4440         char mntdir[PATH_MAX] = {'\0'}, path[PATH_MAX] = {'\0'};
4441         struct find_param param;
4442         int index = 0, rc=0;
4443
4444         if (argc > 2)
4445                 return CMD_HELP;
4446
4447         if (argc == 2 && !realpath(argv[1], path)) {
4448                 rc = -errno;
4449                 fprintf(stderr, "error: invalid path '%s': %s\n",
4450                         argv[1], strerror(-rc));
4451                 return rc;
4452         }
4453
4454         while (!llapi_search_mounts(path, index++, mntdir, NULL)) {
4455                 /* Check if we have a mount point */
4456                 if (mntdir[0] == '\0')
4457                         continue;
4458
4459                 memset(&param, 0, sizeof(param));
4460                 if (!strcmp(argv[0], "mdts"))
4461                         param.fp_get_lmv = 1;
4462
4463                 rc = llapi_ostlist(mntdir, &param);
4464                 if (rc) {
4465                         fprintf(stderr, "error: %s: failed on %s\n",
4466                                 argv[0], mntdir);
4467                 }
4468                 if (path[0] != '\0')
4469                         break;
4470                 memset(mntdir, 0, PATH_MAX);
4471         }
4472
4473         return rc;
4474 }
4475
4476 static int lfs_getstripe(int argc, char **argv)
4477 {
4478         struct find_param param = { 0 };
4479
4480         param.fp_max_depth = 1;
4481         return lfs_getstripe_internal(argc, argv, &param);
4482 }
4483
4484 /* functions */
4485 static int lfs_getdirstripe(int argc, char **argv)
4486 {
4487         struct find_param param = { 0 };
4488         struct option long_opts[] = {
4489         { .val = 'c',   .name = "mdt-count",    .has_arg = no_argument },
4490         { .val = 'D',   .name = "default",      .has_arg = no_argument },
4491         { .val = 'H',   .name = "mdt-hash",     .has_arg = no_argument },
4492         { .val = 'i',   .name = "mdt-index",    .has_arg = no_argument },
4493         { .val = 'm',   .name = "mdt-index",    .has_arg = no_argument },
4494         { .val = 'O',   .name = "obd",          .has_arg = required_argument },
4495         { .val = 'r',   .name = "recursive",    .has_arg = no_argument },
4496         { .val = 'T',   .name = "mdt-count",    .has_arg = no_argument },
4497         { .val = 'y',   .name = "yaml",         .has_arg = no_argument },
4498         { .name = NULL } };
4499         int c, rc;
4500
4501         param.fp_get_lmv = 1;
4502
4503         while ((c = getopt_long(argc, argv,
4504                                 "cDHimO:rtTy", long_opts, NULL)) != -1)
4505         {
4506                 switch (c) {
4507                 case 'c':
4508                 case 'T':
4509                         param.fp_verbose |= VERBOSE_COUNT;
4510                         break;
4511                 case 'D':
4512                         param.fp_get_default_lmv = 1;
4513                         break;
4514                 case 'i':
4515                 case 'm':
4516                         param.fp_verbose |= VERBOSE_OFFSET;
4517                         break;
4518 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
4519                 case 't':
4520                         fprintf(stderr, "warning: '-t' deprecated, "
4521                                 "use '--mdt-hash' or '-H' instead\n");
4522 #endif
4523                 case 'H':
4524                         param.fp_verbose |= VERBOSE_HASH_TYPE;
4525                         break;
4526                 case 'O':
4527                         if (param.fp_obd_uuid) {
4528                                 fprintf(stderr,
4529                                         "error: %s: only one obduuid allowed",
4530                                         argv[0]);
4531                                 return CMD_HELP;
4532                         }
4533                         param.fp_obd_uuid = (struct obd_uuid *)optarg;
4534                         break;
4535                 case 'r':
4536                         param.fp_recursive = 1;
4537                         break;
4538                 case 'y':
4539                         param.fp_yaml = 1;
4540                         break;
4541                 default:
4542                         return CMD_HELP;
4543                 }
4544         }
4545
4546         if (optind >= argc)
4547                 return CMD_HELP;
4548
4549         if (param.fp_recursive)
4550                 param.fp_max_depth = -1;
4551
4552         if (!param.fp_verbose)
4553                 param.fp_verbose = VERBOSE_DEFAULT;
4554
4555         do {
4556                 rc = llapi_getstripe(argv[optind], &param);
4557         } while (++optind < argc && !rc);
4558
4559         if (rc)
4560                 fprintf(stderr, "error: %s failed for %s.\n",
4561                         argv[0], argv[optind - 1]);
4562         return rc;
4563 }
4564
4565 enum mntdf_flags {
4566         MNTDF_INODES    = 0x0001,
4567         MNTDF_COOKED    = 0x0002,
4568         MNTDF_LAZY      = 0x0004,
4569         MNTDF_VERBOSE   = 0x0008,
4570         MNTDF_SHOW      = 0x0010,
4571 };
4572
4573 #define COOK(value)                                             \
4574 ({                                                              \
4575         int radix = 0;                                          \
4576         while (value > 1024) {                                  \
4577                 value /= 1024;                                  \
4578                 radix++;                                        \
4579         }                                                       \
4580         radix;                                                  \
4581 })
4582 #define UUF     "%-20s"
4583 #define CSF     "%11s"
4584 #define CDF     "%11llu"
4585 #define HDF     "%8.1f%c"
4586 #define RSF     "%4s"
4587 #define RDF     "%3d%%"
4588
4589 static inline int obd_statfs_ratio(const struct obd_statfs *st)
4590 {
4591         double avail, used, ratio = 0;
4592
4593         avail = st->os_bavail;
4594         used  = st->os_blocks - st->os_bfree;
4595         if (avail + used > 0)
4596                 ratio = used / (used + avail) * 100 + 0.5;
4597
4598         return (int)ratio;
4599 }
4600
4601 static int showdf(char *mntdir, struct obd_statfs *stat,
4602                   char *uuid, enum mntdf_flags flags,
4603                   char *type, int index, int rc)
4604 {
4605         long long avail, used, total;
4606         int ratio = 0;
4607         char *suffix = "KMGTPEZY";
4608         /* Note if we have >2^64 bytes/fs these buffers will need to be grown */
4609         char tbuf[3 * sizeof(__u64)];
4610         char ubuf[3 * sizeof(__u64)];
4611         char abuf[3 * sizeof(__u64)];
4612         char rbuf[3 * sizeof(__u64)];
4613
4614         if (!uuid || !stat)
4615                 return -EINVAL;
4616
4617         switch (rc) {
4618         case 0:
4619                 if (flags & MNTDF_INODES) {
4620                         avail = stat->os_ffree;
4621                         used = stat->os_files - stat->os_ffree;
4622                         total = stat->os_files;
4623                 } else {
4624                         int shift = flags & MNTDF_COOKED ? 0 : 10;
4625
4626                         avail = (stat->os_bavail * stat->os_bsize) >> shift;
4627                         used  = ((stat->os_blocks - stat->os_bfree) *
4628                                  stat->os_bsize) >> shift;
4629                         total = (stat->os_blocks * stat->os_bsize) >> shift;
4630                 }
4631
4632                 ratio = obd_statfs_ratio(stat);
4633
4634                 if (flags & MNTDF_COOKED) {
4635                         int i;
4636                         double cook_val;
4637
4638                         cook_val = (double)total;
4639                         i = COOK(cook_val);
4640                         if (i > 0)
4641                                 snprintf(tbuf, sizeof(tbuf), HDF, cook_val,
4642                                          suffix[i - 1]);
4643                         else
4644                                 snprintf(tbuf, sizeof(tbuf), CDF, total);
4645
4646                         cook_val = (double)used;
4647                         i = COOK(cook_val);
4648                         if (i > 0)
4649                                 snprintf(ubuf, sizeof(ubuf), HDF, cook_val,
4650                                          suffix[i - 1]);
4651                         else
4652                                 snprintf(ubuf, sizeof(ubuf), CDF, used);
4653
4654                         cook_val = (double)avail;
4655                         i = COOK(cook_val);
4656                         if (i > 0)
4657                                 snprintf(abuf, sizeof(abuf), HDF, cook_val,
4658                                          suffix[i - 1]);
4659                         else
4660                                 snprintf(abuf, sizeof(abuf), CDF, avail);
4661                 } else {
4662                         snprintf(tbuf, sizeof(tbuf), CDF, total);
4663                         snprintf(ubuf, sizeof(tbuf), CDF, used);
4664                         snprintf(abuf, sizeof(tbuf), CDF, avail);
4665                 }
4666
4667                 sprintf(rbuf, RDF, ratio);
4668                 printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s",
4669                        uuid, tbuf, ubuf, abuf, rbuf, mntdir);
4670                 if (type)
4671                         printf("[%s:%d]", type, index);
4672
4673                 if (stat->os_state) {
4674                         /*
4675                          * Each character represents the matching
4676                          * OS_STATE_* bit.
4677                          */
4678                         const char state_names[] = "DRSI";
4679                         __u32      state;
4680                         __u32      i;
4681
4682                         printf(" ");
4683                         for (i = 0, state = stat->os_state;
4684                              state && i < sizeof(state_names); i++) {
4685                                 if (!(state & (1 << i)))
4686                                         continue;
4687                                 printf("%c", state_names[i]);
4688                                 state ^= 1 << i;
4689                         }
4690                 }
4691
4692                 printf("\n");
4693                 break;
4694         case -ENODATA:
4695                 printf(UUF": inactive device\n", uuid);
4696                 break;
4697         default:
4698                 printf(UUF": %s\n", uuid, strerror(-rc));
4699                 break;
4700         }
4701
4702         return 0;
4703 }
4704
4705 struct ll_stat_type {
4706         int   st_op;
4707         char *st_name;
4708 };
4709
4710 #define LL_STATFS_MAX   LOV_MAX_STRIPE_COUNT
4711
4712 struct ll_statfs_data {
4713         int                     sd_index;
4714         struct obd_statfs       sd_st;
4715 };
4716
4717 struct ll_statfs_buf {
4718         int                     sb_count;
4719         struct ll_statfs_data   sb_buf[LL_STATFS_MAX];
4720 };
4721
4722 static int mntdf(char *mntdir, char *fsname, char *pool, enum mntdf_flags flags,
4723                  int ops, struct ll_statfs_buf *lsb)
4724 {
4725         struct obd_statfs stat_buf, sum = { .os_bsize = 1 };
4726         struct obd_uuid uuid_buf;
4727         char *poolname = NULL;
4728         struct ll_stat_type types[] = {
4729                 { .st_op = LL_STATFS_LMV,       .st_name = "MDT" },
4730                 { .st_op = LL_STATFS_LOV,       .st_name = "OST" },
4731                 { .st_name = NULL } };
4732         struct ll_stat_type *tp;
4733         __u64 ost_ffree = 0;
4734         __u32 index;
4735         __u32 type;
4736         int fd;
4737         int rc = 0;
4738         int rc2;
4739
4740         if (pool) {
4741                 poolname = strchr(pool, '.');
4742                 if (poolname != NULL) {
4743                         if (strncmp(fsname, pool, strlen(fsname))) {
4744                                 fprintf(stderr, "filesystem name incorrect\n");
4745                                 return -ENODEV;
4746                         }
4747                         poolname++;
4748                 } else
4749                         poolname = pool;
4750         }
4751
4752         fd = open(mntdir, O_RDONLY);
4753         if (fd < 0) {
4754                 rc = -errno;
4755                 fprintf(stderr, "%s: cannot open '%s': %s\n", progname, mntdir,
4756                         strerror(errno));
4757                 return rc;
4758         }
4759
4760         if (flags & MNTDF_SHOW) {
4761                 if (flags & MNTDF_INODES)
4762                         printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s\n",
4763                                "UUID", "Inodes", "IUsed", "IFree",
4764                                "IUse%", "Mounted on");
4765                 else
4766                         printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s\n",
4767                                "UUID",
4768                                flags & MNTDF_COOKED ? "bytes" : "1K-blocks",
4769                                "Used", "Available", "Use%", "Mounted on");
4770         }
4771
4772         for (tp = types; tp->st_name != NULL; tp++) {
4773                 if (!(tp->st_op & ops))
4774                         continue;
4775
4776                 for (index = 0; ; index++) {
4777                         memset(&stat_buf, 0, sizeof(struct obd_statfs));
4778                         memset(&uuid_buf, 0, sizeof(struct obd_uuid));
4779                         type = flags & MNTDF_LAZY ?
4780                                 tp->st_op | LL_STATFS_NODELAY : tp->st_op;
4781                         rc2 = llapi_obd_fstatfs(fd, type, index,
4782                                                &stat_buf, &uuid_buf);
4783                         if (rc2 == -ENODEV)
4784                                 break;
4785                         if (rc2 == -EAGAIN)
4786                                 continue;
4787                         if (rc2 == -ENODATA) { /* Inactive device, OK. */
4788                                 if (!(flags & MNTDF_VERBOSE))
4789                                         continue;
4790                         } else if (rc2 < 0 && rc == 0) {
4791                                 rc = rc2;
4792                         }
4793
4794                         if (poolname && tp->st_op == LL_STATFS_LOV &&
4795                             llapi_search_ost(fsname, poolname,
4796                                              obd_uuid2str(&uuid_buf)) != 1)
4797                                 continue;
4798
4799                         /* the llapi_obd_statfs() call may have returned with
4800                          * an error, but if it filled in uuid_buf we will at
4801                          * lease use that to print out a message for that OBD.
4802                          * If we didn't get anything in the uuid_buf, then fill
4803                          * it in so that we can print an error message. */
4804                         if (uuid_buf.uuid[0] == '\0')
4805                                 snprintf(uuid_buf.uuid, sizeof(uuid_buf.uuid),
4806                                          "%s%04x", tp->st_name, index);
4807                         if (!rc && lsb) {
4808                                 lsb->sb_buf[lsb->sb_count].sd_index = index;
4809                                 lsb->sb_buf[lsb->sb_count].sd_st = stat_buf;
4810                                 lsb->sb_count++;
4811                         }
4812                         if (flags & MNTDF_SHOW)
4813                                 showdf(mntdir, &stat_buf,
4814                                        obd_uuid2str(&uuid_buf), flags,
4815                                        tp->st_name, index, rc2);
4816
4817                         if (rc2 == 0) {
4818                                 if (tp->st_op == LL_STATFS_LMV) {
4819                                         sum.os_ffree += stat_buf.os_ffree;
4820                                         sum.os_files += stat_buf.os_files;
4821                                 } else /* if (tp->st_op == LL_STATFS_LOV) */ {
4822                                         sum.os_blocks += stat_buf.os_blocks *
4823                                                 stat_buf.os_bsize;
4824                                         sum.os_bfree  += stat_buf.os_bfree *
4825                                                 stat_buf.os_bsize;
4826                                         sum.os_bavail += stat_buf.os_bavail *
4827                                                 stat_buf.os_bsize;
4828                                         ost_ffree += stat_buf.os_ffree;
4829                                 }
4830                         }
4831                 }
4832         }
4833
4834         close(fd);
4835
4836         /* If we don't have as many objects free on the OST as inodes
4837          * on the MDS, we reduce the total number of inodes to
4838          * compensate, so that the "inodes in use" number is correct.
4839          * Matches ll_statfs_internal() so the results are consistent. */
4840         if (ost_ffree < sum.os_ffree) {
4841                 sum.os_files = (sum.os_files - sum.os_ffree) + ost_ffree;
4842                 sum.os_ffree = ost_ffree;
4843         }
4844         if (flags & MNTDF_SHOW) {
4845                 printf("\n");
4846                 showdf(mntdir, &sum, "filesystem_summary:", flags, NULL, 0, 0);
4847                 printf("\n");
4848         }
4849
4850         return rc;
4851 }
4852
4853 static int ll_statfs_data_comp(const void *sd1, const void *sd2)
4854 {
4855         const struct obd_statfs *st1 = &((const struct ll_statfs_data *)sd1)->
4856                                                 sd_st;
4857         const struct obd_statfs *st2 = &((const struct ll_statfs_data *)sd2)->
4858                                                 sd_st;
4859         int r1 = obd_statfs_ratio(st1);
4860         int r2 = obd_statfs_ratio(st2);
4861         int64_t result = r1 - r2;
4862
4863         /* if both space usage are above 90, compare free inodes */
4864         if (r1 > 90 && r2 > 90)
4865                 result = st2->os_ffree - st1->os_ffree;
4866
4867         if (result < 0)
4868                 return -1;
4869         else if (result == 0)
4870                 return 0;
4871         else
4872                 return 1;
4873 }
4874
4875 /* functions */
4876 static int lfs_setdirstripe(int argc, char **argv)
4877 {
4878         char                    *dname;
4879         int                     result;
4880         struct lfs_setstripe_args        lsa = { 0 };
4881         struct llapi_stripe_param       *param = NULL;
4882         __u32                   mdts[LMV_MAX_STRIPE_COUNT] = { 0 };
4883         char                    *end;
4884         int                     c;
4885         char                    *mode_opt = NULL;
4886         bool                    default_stripe = false;
4887         mode_t                  mode = S_IRWXU | S_IRWXG | S_IRWXO;
4888         mode_t                  previous_mode = 0;
4889         bool                    delete = false;
4890         struct ll_statfs_buf    *lsb = NULL;
4891         char                    mntdir[PATH_MAX] = "";
4892         bool                    auto_distributed = false;
4893
4894         struct option long_opts[] = {
4895         { .val = 'c',   .name = "count",        .has_arg = required_argument },
4896         { .val = 'c',   .name = "mdt-count",    .has_arg = required_argument },
4897         { .val = 'd',   .name = "delete",       .has_arg = no_argument },
4898         { .val = 'D',   .name = "default",      .has_arg = no_argument },
4899         { .val = 'D',   .name = "default_stripe", .has_arg = no_argument },
4900         { .val = 'H',   .name = "mdt-hash",     .has_arg = required_argument },
4901         { .val = 'i',   .name = "mdt-index",    .has_arg = required_argument },
4902 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
4903         { .val = 'i',   .name = "index",        .has_arg = required_argument },
4904 #endif
4905         { .val = 'o',   .name = "mode",         .has_arg = required_argument },
4906 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
4907         { .val = 't',   .name = "hash-type",    .has_arg = required_argument },
4908 #endif
4909         { .val = 'T',   .name = "mdt-count",    .has_arg = required_argument },
4910 /* setstripe { .val = 'y', .name = "yaml",      .has_arg = no_argument }, */
4911         { .name = NULL } };
4912
4913         setstripe_args_init(&lsa);
4914
4915         while ((c = getopt_long(argc, argv, "c:dDi:H:m:o:t:T:", long_opts,
4916                                 NULL)) >= 0) {
4917                 switch (c) {
4918                 case 0:
4919                         /* Long options. */
4920                         break;
4921                 case 'c':
4922                 case 'T':
4923                         lsa.lsa_stripe_count = strtoul(optarg, &end, 0);
4924                         if (*end != '\0') {
4925                                 fprintf(stderr,
4926                                         "%s %s: invalid stripe count '%s'\n",
4927                                         progname, argv[0], optarg);
4928                                 return CMD_HELP;
4929                         }
4930                         break;
4931                 case 'd':
4932                         delete = true;
4933                         default_stripe = true;
4934                         break;
4935                 case 'D':
4936                         default_stripe = true;
4937                         break;
4938 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
4939                 case 't':
4940                         fprintf(stderr, "warning: '--hash-type' and '-t' "
4941                               "deprecated, use '--mdt-hash' or '-H' instead\n");
4942 #endif
4943                 case 'H':
4944                         lsa.lsa_pattern = check_hashtype(optarg);
4945                         if (lsa.lsa_pattern == 0) {
4946                                 fprintf(stderr,
4947                                         "%s %s: bad stripe hash type '%s'\n",
4948                                         progname, argv[0], optarg);
4949                                 return CMD_HELP;
4950                         }
4951                         break;
4952                 case 'i':
4953 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
4954                         if (strcmp(argv[optind - 1], "--index") == 0)
4955                                 fprintf(stderr,
4956                                         "%s %s: warning: '--index' deprecated, use '--mdt-index' instead\n",
4957                                         progname, argv[0]);
4958 #endif
4959                         lsa.lsa_nr_tgts = parse_targets(mdts,
4960                                                 sizeof(mdts) / sizeof(__u32),
4961                                                 lsa.lsa_nr_tgts, optarg);
4962                         if (lsa.lsa_nr_tgts < 0) {
4963                                 fprintf(stderr,
4964                                         "%s %s: invalid MDT target(s) '%s'\n",
4965                                         progname, argv[0], optarg);
4966                                 return CMD_HELP;
4967                         }
4968
4969                         lsa.lsa_tgts = mdts;
4970                         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
4971                                 lsa.lsa_stripe_off = mdts[0];
4972                         break;
4973 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 16, 53, 0)
4974                 case 'm':
4975                         fprintf(stderr, "warning: '-m' is deprecated, "
4976                                 "use '--mode' or '-o' instead\n");
4977 #endif
4978                 case 'o':
4979                         mode_opt = optarg;
4980                         break;
4981                 default:
4982                         fprintf(stderr, "%s %s: unrecognized option '%s'\n",
4983                                 progname, argv[0], argv[optind - 1]);
4984                         return CMD_HELP;
4985                 }
4986         }
4987
4988         if (optind == argc) {
4989                 fprintf(stderr, "%s %s: DIR must be specified\n",
4990                         progname, argv[0]);
4991                 return CMD_HELP;
4992         }
4993
4994         if (!delete && lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT &&
4995             lsa.lsa_stripe_count == LLAPI_LAYOUT_DEFAULT) {
4996                 fprintf(stderr,
4997                         "%s %s: stripe offset and count must be specified\n",
4998                         progname, argv[0]);
4999                 return CMD_HELP;
5000         }
5001
5002         if (delete &&
5003             (lsa.lsa_stripe_off != LLAPI_LAYOUT_DEFAULT ||
5004              lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT)) {
5005                 fprintf(stderr,
5006                         "%s %s: cannot specify -d with -c or -i options\n",
5007                         progname, argv[0]);
5008                 return CMD_HELP;
5009         }
5010
5011         if (mode_opt != NULL) {
5012                 mode = strtoul(mode_opt, &end, 8);
5013                 if (*end != '\0') {
5014                         fprintf(stderr,
5015                                 "%s %s: bad MODE '%s'\n",
5016                                 progname, argv[0], mode_opt);
5017                         return CMD_HELP;
5018                 }
5019                 previous_mode = umask(0);
5020         }
5021
5022         /*
5023          * initialize stripe parameters, in case param is converted to specific,
5024          * i.e, 'lfs mkdir -i -1 -c N', always allocate space for lsp_tgts.
5025          */
5026         param = calloc(1, offsetof(typeof(*param),
5027                        lsp_tgts[lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT ?
5028                                 lsa.lsa_stripe_count : lsa.lsa_nr_tgts]));
5029         if (param == NULL) {
5030                 fprintf(stderr,
5031                         "%s %s: cannot allocate memory for parameters: %s\n",
5032                         progname, argv[0], strerror(ENOMEM));
5033                 return CMD_HELP;
5034         }
5035
5036         if (lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT)
5037                 param->lsp_stripe_count = lsa.lsa_stripe_count;
5038         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
5039                 param->lsp_stripe_offset = -1;
5040         else
5041                 param->lsp_stripe_offset = lsa.lsa_stripe_off;
5042         if (lsa.lsa_pattern != LLAPI_LAYOUT_RAID0)
5043                 param->lsp_stripe_pattern = lsa.lsa_pattern;
5044         else
5045                 param->lsp_stripe_pattern = LMV_HASH_TYPE_FNV_1A_64;
5046         param->lsp_pool = lsa.lsa_pool_name;
5047         param->lsp_is_specific = false;
5048         if (lsa.lsa_nr_tgts > 1) {
5049                 if (lsa.lsa_stripe_count > 0 &&
5050                     lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT &&
5051                     lsa.lsa_stripe_count != lsa.lsa_nr_tgts) {
5052                         fprintf(stderr, "error: %s: stripe count %lld doesn't "
5053                                 "match the number of MDTs: %d\n",
5054                                 argv[0], lsa.lsa_stripe_count, lsa.lsa_nr_tgts);
5055                         free(param);
5056                         return CMD_HELP;
5057                 }
5058
5059                 param->lsp_is_specific = true;
5060                 param->lsp_stripe_count = lsa.lsa_nr_tgts;
5061                 memcpy(param->lsp_tgts, mdts, sizeof(*mdts) * lsa.lsa_nr_tgts);
5062         }
5063
5064         dname = argv[optind];
5065         do {
5066                 if (default_stripe) {
5067                         result = llapi_dir_set_default_lmv(dname, param);
5068                 } else {
5069                         /* if current \a dname isn't under the same \a mntdir
5070                          * as the last one, and the last one was
5071                          * auto-distributed, restore \a param.
5072                          */
5073                         if (mntdir[0] != '\0' &&
5074                             strncmp(dname, mntdir, strlen(mntdir)) &&
5075                             auto_distributed) {
5076                                 param->lsp_is_specific = false;
5077                                 param->lsp_stripe_offset = -1;
5078                                 auto_distributed = false;
5079                         }
5080
5081                         if (!param->lsp_is_specific &&
5082                             param->lsp_stripe_offset == -1) {
5083                                 char path[PATH_MAX] = "";
5084
5085                                 if (!lsb) {
5086                                         lsb = malloc(sizeof(*lsb));
5087                                         if (!lsb) {
5088                                                 result = -ENOMEM;
5089                                                 break;
5090                                         }
5091                                 }
5092                                 lsb->sb_count = 0;
5093
5094                                 /* use mntdir for dirname() temporarily */
5095                                 strncpy(mntdir, dname, sizeof(mntdir));
5096                                 if (!realpath(dirname(mntdir), path)) {
5097                                         result = -errno;
5098                                         fprintf(stderr,
5099                                                 "error: invalid path '%s': %s\n",
5100                                                 argv[optind], strerror(errno));
5101                                         break;
5102                                 }
5103                                 mntdir[0] = '\0';
5104
5105                                 result = llapi_search_mounts(path, 0, mntdir,
5106                                                              NULL);
5107                                 if (result < 0 || mntdir[0] == '\0') {
5108                                         fprintf(stderr,
5109                                                 "No suitable Lustre mount found\n");
5110                                         break;
5111                                 }
5112
5113                                 result = mntdf(mntdir, NULL, NULL, 0,
5114                                                LL_STATFS_LMV, lsb);
5115                                 if (result < 0)
5116                                         break;
5117
5118                                 if (param->lsp_stripe_count > lsb->sb_count) {
5119                                         fprintf(stderr,
5120                                                 "error: stripe count %d is too big\n",
5121                                                 param->lsp_stripe_count);
5122                                         result = -ERANGE;
5123                                         break;
5124                                 }
5125
5126                                 qsort(lsb->sb_buf, lsb->sb_count,
5127                                       sizeof(struct ll_statfs_data),
5128                                       ll_statfs_data_comp);
5129
5130                                 auto_distributed = true;
5131                         }
5132
5133                         if (auto_distributed) {
5134                                 int r;
5135                                 int nr = MAX(param->lsp_stripe_count,
5136                                              lsb->sb_count / 2);
5137
5138                                 /* don't use server whose usage is above 90% */
5139                                 while (nr != param->lsp_stripe_count &&
5140                                        obd_statfs_ratio(&lsb->sb_buf[nr].sd_st)
5141                                        > 90)
5142                                         nr = MAX(param->lsp_stripe_count,
5143                                                  nr / 2);
5144
5145                                 /* get \a r between [0, nr) */
5146                                 r = rand() % nr;
5147
5148                                 param->lsp_stripe_offset =
5149                                         lsb->sb_buf[r].sd_index;
5150                                 if (param->lsp_stripe_count > 1) {
5151                                         int i = 0;
5152
5153                                         param->lsp_is_specific = true;
5154                                         for (; i < param->lsp_stripe_count; i++)
5155                                                 param->lsp_tgts[(i + r) % nr] =
5156                                                         lsb->sb_buf[i].sd_index;
5157                                 }
5158                         }
5159
5160                         result = llapi_dir_create(dname, mode, param);
5161                 }
5162
5163                 if (result) {
5164                         fprintf(stderr,
5165                                 "%s setdirstripe: cannot create stripe dir '%s': %s\n",
5166                                 progname, dname, strerror(-result));
5167                         break;
5168                 }
5169                 dname = argv[++optind];
5170         } while (dname != NULL);
5171
5172         if (mode_opt != NULL)
5173                 umask(previous_mode);
5174
5175         free(lsb);
5176         free(param);
5177         return result;
5178 }
5179
5180 /* functions */
5181 static int lfs_rmentry(int argc, char **argv)
5182 {
5183         char *dname;
5184         int   index;
5185         int   result = 0;
5186
5187         if (argc <= 1) {
5188                 fprintf(stderr, "error: %s: missing dirname\n",
5189                         argv[0]);
5190                 return CMD_HELP;
5191         }
5192
5193         index = 1;
5194         dname = argv[index];
5195         while (dname != NULL) {
5196                 result = llapi_direntry_remove(dname);
5197                 if (result) {
5198                         fprintf(stderr, "error: %s: remove dir entry '%s' "
5199                                 "failed\n", argv[0], dname);
5200                         break;
5201                 }
5202                 dname = argv[++index];
5203         }
5204         return result;
5205 }
5206
5207 static int lfs_mv(int argc, char **argv)
5208 {
5209         struct lmv_user_md lmu = { LMV_USER_MAGIC };
5210         struct find_param param = {
5211                 .fp_max_depth = -1,
5212                 .fp_mdt_index = -1,
5213         };
5214         char *end;
5215         int c;
5216         int rc = 0;
5217         struct option long_opts[] = {
5218         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument },
5219         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
5220         { .name = NULL } };
5221
5222         while ((c = getopt_long(argc, argv, "m:M:v", long_opts, NULL)) != -1) {
5223                 switch (c) {
5224 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
5225                 case 'M':
5226                         fprintf(stderr, "warning: '-M' deprecated"
5227                                 ", use '--mdt-index' or '-m' instead\n");
5228 #endif
5229                 case 'm':
5230                         lmu.lum_stripe_offset = strtoul(optarg, &end, 0);
5231                         if (*end != '\0') {
5232                                 fprintf(stderr, "%s mv: bad MDT index '%s'\n",
5233                                         progname, optarg);
5234                                 return CMD_HELP;
5235                         }
5236                         break;
5237                 case 'v':
5238                         param.fp_verbose = VERBOSE_DETAIL;
5239                         break;
5240                 default:
5241                         fprintf(stderr, "%s mv: unrecognized option '%s'\n",
5242                                 progname, argv[optind - 1]);
5243                         return CMD_HELP;
5244                 }
5245         }
5246
5247         if (lmu.lum_stripe_offset == -1) {
5248                 fprintf(stderr, "%s mv: MDT index must be specified\n",
5249                         progname);
5250                 return CMD_HELP;
5251         }
5252
5253         if (optind >= argc) {
5254                 fprintf(stderr, "%s mv: DIR must be specified\n", progname);
5255                 return CMD_HELP;
5256         }
5257
5258
5259         /* initialize migrate mdt parameters */
5260         param.fp_lmv_md = &lmu;
5261         param.fp_migrate = 1;
5262         rc = llapi_migrate_mdt(argv[optind], &param);
5263         if (rc != 0)
5264                 fprintf(stderr, "%s mv: cannot migrate '%s' to MDT%04x: %s\n",
5265                         progname, argv[optind], param.fp_mdt_index,
5266                         strerror(-rc));
5267         return rc;
5268 }
5269
5270 static int lfs_osts(int argc, char **argv)
5271 {
5272         return lfs_tgts(argc, argv);
5273 }
5274
5275 static int lfs_mdts(int argc, char **argv)
5276 {
5277         return lfs_tgts(argc, argv);
5278 }
5279
5280 static int lfs_df(int argc, char **argv)
5281 {
5282         char mntdir[PATH_MAX] = {'\0'}, path[PATH_MAX] = {'\0'};
5283         enum mntdf_flags flags = MNTDF_SHOW;
5284         int ops = LL_STATFS_LMV | LL_STATFS_LOV;
5285         int c, rc = 0, index = 0;
5286         char fsname[PATH_MAX] = "", *pool_name = NULL;
5287         struct option long_opts[] = {
5288         { .val = 'h',   .name = "human-readable",
5289                                                 .has_arg = no_argument },
5290         { .val = 'i',   .name = "inodes",       .has_arg = no_argument },
5291         { .val = 'l',   .name = "lazy",         .has_arg = no_argument },
5292         { .val = 'p',   .name = "pool",         .has_arg = required_argument },
5293         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
5294         { .name = NULL} };
5295
5296         while ((c = getopt_long(argc, argv, "hilp:v", long_opts, NULL)) != -1) {
5297                 switch (c) {
5298                 case 'h':
5299                         flags |= MNTDF_COOKED;
5300                         break;
5301                 case 'i':
5302                         flags |= MNTDF_INODES;
5303                         break;
5304                 case 'l':
5305                         flags |= MNTDF_LAZY;
5306                         break;
5307                 case 'p':
5308                         pool_name = optarg;
5309                         break;
5310                 case 'v':
5311                         flags |= MNTDF_VERBOSE;
5312                         break;
5313                 default:
5314                         return CMD_HELP;
5315                 }
5316         }
5317         if (optind < argc && !realpath(argv[optind], path)) {
5318                 rc = -errno;
5319                 fprintf(stderr, "error: invalid path '%s': %s\n",
5320                         argv[optind], strerror(-rc));
5321                 return rc;
5322         }
5323
5324         while (!llapi_search_mounts(path, index++, mntdir, fsname)) {
5325                 /* Check if we have a mount point */
5326                 if (mntdir[0] == '\0')
5327                         continue;
5328
5329                 rc = mntdf(mntdir, fsname, pool_name, flags, ops, NULL);
5330                 if (rc || path[0] != '\0')
5331                         break;
5332                 fsname[0] = '\0'; /* avoid matching in next loop */
5333                 mntdir[0] = '\0'; /* avoid matching in next loop */
5334         }
5335
5336         return rc;
5337 }
5338
5339 static int lfs_getname(int argc, char **argv)
5340 {
5341         char mntdir[PATH_MAX] = "", path[PATH_MAX] = "", fsname[PATH_MAX] = "";
5342         int rc = 0, index = 0, c;
5343         char buf[sizeof(struct obd_uuid)];
5344
5345         while ((c = getopt(argc, argv, "h")) != -1)
5346                 return CMD_HELP;
5347
5348         if (optind == argc) { /* no paths specified, get all paths. */
5349                 while (!llapi_search_mounts(path, index++, mntdir, fsname)) {
5350                         rc = llapi_getname(mntdir, buf, sizeof(buf));
5351                         if (rc < 0) {
5352                                 fprintf(stderr,
5353                                         "cannot get name for `%s': %s\n",
5354                                         mntdir, strerror(-rc));
5355                                 break;
5356                         }
5357
5358                         printf("%s %s\n", buf, mntdir);
5359
5360                         path[0] = fsname[0] = mntdir[0] = 0;
5361                 }
5362         } else { /* paths specified, only attempt to search these. */
5363                 for (; optind < argc; optind++) {
5364                         rc = llapi_getname(argv[optind], buf, sizeof(buf));
5365                         if (rc < 0) {
5366                                 fprintf(stderr,
5367                                         "cannot get name for `%s': %s\n",
5368                                         argv[optind], strerror(-rc));
5369                                 break;
5370                         }
5371
5372                         printf("%s %s\n", buf, argv[optind]);
5373                 }
5374         }
5375         return rc;
5376 }
5377
5378 static int lfs_check(int argc, char **argv)
5379 {
5380         int rc;
5381         char mntdir[PATH_MAX] = {'\0'};
5382         int num_types = 1;
5383         char *obd_types[2];
5384         char obd_type1[4];
5385         char obd_type2[4];
5386
5387         if (argc != 2) {
5388                 fprintf(stderr, "%s check: server type must be specified\n",
5389                         progname);
5390                 return CMD_HELP;
5391         }
5392
5393         obd_types[0] = obd_type1;
5394         obd_types[1] = obd_type2;
5395
5396         if (strcmp(argv[1], "osts") == 0) {
5397                 strcpy(obd_types[0], "osc");
5398         } else if (strcmp(argv[1], "mds") == 0) {
5399                 strcpy(obd_types[0], "mdc");
5400         } else if (strcmp(argv[1], "servers") == 0) {
5401                 num_types = 2;
5402                 strcpy(obd_types[0], "osc");
5403                 strcpy(obd_types[1], "mdc");
5404         } else {
5405                 fprintf(stderr, "%s check: unrecognized option '%s'\n",
5406                         progname, argv[1]);
5407                 return CMD_HELP;
5408         }
5409
5410         rc = llapi_search_mounts(NULL, 0, mntdir, NULL);
5411         if (rc < 0 || mntdir[0] == '\0') {
5412                 fprintf(stderr,
5413                         "%s check: cannot find mounted Lustre filesystem: %s\n",
5414                         progname, (rc < 0) ? strerror(-rc) : strerror(ENODEV));
5415                 return rc;
5416         }
5417
5418         rc = llapi_target_check(num_types, obd_types, mntdir);
5419         if (rc)
5420                 fprintf(stderr, "%s check: cannot check target '%s': %s\n",
5421                         progname, argv[1], strerror(-rc));
5422
5423         return rc;
5424
5425 }
5426
5427 #ifdef HAVE_SYS_QUOTA_H
5428 #define ARG2INT(nr, str, msg)                                           \
5429 do {                                                                    \
5430         char *endp;                                                     \
5431         nr = strtol(str, &endp, 0);                                     \
5432         if (*endp != '\0') {                                            \
5433                 fprintf(stderr, "%s: bad %s '%s'\n",                    \
5434                         progname, msg, str);                            \
5435                 return CMD_HELP;                                        \
5436         }                                                               \
5437 } while (0)
5438
5439 #define ADD_OVERFLOW(a,b) ((a + b) < a) ? (a = ULONG_MAX) : (a = a + b)
5440
5441 /* Convert format time string "XXwXXdXXhXXmXXs" into seconds value
5442  * returns the value or ULONG_MAX on integer overflow or incorrect format
5443  * Notes:
5444  *        1. the order of specifiers is arbitrary (may be: 5w3s or 3s5w)
5445  *        2. specifiers may be encountered multiple times (2s3s is 5 seconds)
5446  *        3. empty integer value is interpreted as 0
5447  */
5448 static unsigned long str2sec(const char* timestr)
5449 {
5450         const char spec[] = "smhdw";
5451         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
5452         unsigned long val = 0;
5453         char *tail;
5454
5455         if (strpbrk(timestr, spec) == NULL) {
5456                 /* no specifiers inside the time string,
5457                    should treat it as an integer value */
5458                 val = strtoul(timestr, &tail, 10);
5459                 return *tail ? ULONG_MAX : val;
5460         }
5461
5462         /* format string is XXwXXdXXhXXmXXs */
5463         while (*timestr) {
5464                 unsigned long v;
5465                 int ind;
5466                 char* ptr;
5467
5468                 v = strtoul(timestr, &tail, 10);
5469                 if (v == ULONG_MAX || *tail == '\0')
5470                         /* value too large (ULONG_MAX or more)
5471                            or missing specifier */
5472                         goto error;
5473
5474                 ptr = strchr(spec, *tail);
5475                 if (ptr == NULL)
5476                         /* unknown specifier */
5477                         goto error;
5478
5479                 ind = ptr - spec;
5480
5481                 /* check if product will overflow the type */
5482                 if (!(v < ULONG_MAX / mult[ind]))
5483                         goto error;
5484
5485                 ADD_OVERFLOW(val, mult[ind] * v);
5486                 if (val == ULONG_MAX)
5487                         goto error;
5488
5489                 timestr = tail + 1;
5490         }
5491
5492         return val;
5493
5494 error:
5495         return ULONG_MAX;
5496 }
5497
5498 #define ARG2ULL(nr, str, def_units)                                     \
5499 do {                                                                    \
5500         unsigned long long limit, units = def_units;                    \
5501         int rc;                                                         \
5502                                                                         \
5503         rc = llapi_parse_size(str, &limit, &units, 1);                  \
5504         if (rc < 0) {                                                   \
5505                 fprintf(stderr, "%s: invalid limit '%s'\n",             \
5506                         progname, str);                                 \
5507                 return CMD_HELP;                                        \
5508         }                                                               \
5509         nr = limit;                                                     \
5510 } while (0)
5511
5512 static inline int has_times_option(int argc, char **argv)
5513 {
5514         int i;
5515
5516         for (i = 1; i < argc; i++)
5517                 if (!strcmp(argv[i], "-t"))
5518                         return 1;
5519
5520         return 0;
5521 }
5522
5523 int lfs_setquota_times(int argc, char **argv)
5524 {
5525         int c, rc;
5526         struct if_quotactl qctl;
5527         char *mnt, *obd_type = (char *)qctl.obd_type;
5528         struct obd_dqblk *dqb = &qctl.qc_dqblk;
5529         struct obd_dqinfo *dqi = &qctl.qc_dqinfo;
5530         struct option long_opts[] = {
5531         { .val = 'b',   .name = "block-grace",  .has_arg = required_argument },
5532         { .val = 'g',   .name = "group",        .has_arg = no_argument },
5533         { .val = 'i',   .name = "inode-grace",  .has_arg = required_argument },
5534         { .val = 'p',   .name = "projid",       .has_arg = no_argument },
5535         { .val = 't',   .name = "times",        .has_arg = no_argument },
5536         { .val = 'u',   .name = "user",         .has_arg = no_argument },
5537         { .name = NULL } };
5538         int qtype;
5539
5540         memset(&qctl, 0, sizeof(qctl));
5541         qctl.qc_cmd  = LUSTRE_Q_SETINFO;
5542         qctl.qc_type = ALLQUOTA;
5543
5544         while ((c = getopt_long(argc, argv, "b:gi:ptu",
5545                                 long_opts, NULL)) != -1) {
5546                 switch (c) {
5547                 case 'u':
5548                         qtype = USRQUOTA;
5549                         goto quota_type;
5550                 case 'g':
5551                         qtype = GRPQUOTA;
5552                         goto quota_type;
5553                 case 'p':
5554                         qtype = PRJQUOTA;
5555 quota_type:
5556                         if (qctl.qc_type != ALLQUOTA) {
5557                                 fprintf(stderr, "error: -u/g/p can't be used "
5558                                                 "more than once\n");
5559                                 return CMD_HELP;
5560                         }
5561                         qctl.qc_type = qtype;
5562                         break;
5563                 case 'b':
5564                         if ((dqi->dqi_bgrace = str2sec(optarg)) == ULONG_MAX) {
5565                                 fprintf(stderr, "error: bad block-grace: %s\n",
5566                                         optarg);
5567                                 return CMD_HELP;
5568                         }
5569                         dqb->dqb_valid |= QIF_BTIME;
5570                         break;
5571                 case 'i':
5572                         if ((dqi->dqi_igrace = str2sec(optarg)) == ULONG_MAX) {
5573                                 fprintf(stderr, "error: bad inode-grace: %s\n",
5574                                         optarg);
5575                                 return CMD_HELP;
5576                         }
5577                         dqb->dqb_valid |= QIF_ITIME;
5578                         break;
5579                 case 't': /* Yes, of course! */
5580                         break;
5581                 default: /* getopt prints error message for us when opterr != 0 */
5582                         return CMD_HELP;
5583                 }
5584         }
5585
5586         if (qctl.qc_type == ALLQUOTA) {
5587                 fprintf(stderr, "error: neither -u, -g nor -p specified\n");
5588                 return CMD_HELP;
5589         }
5590
5591         if (optind != argc - 1) {
5592                 fprintf(stderr, "error: unexpected parameters encountered\n");
5593                 return CMD_HELP;
5594         }
5595
5596         if ((dqb->dqb_valid | QIF_BTIME && dqi->dqi_bgrace >= UINT_MAX) ||
5597             (dqb->dqb_valid | QIF_ITIME && dqi->dqi_igrace >= UINT_MAX)) {
5598                 fprintf(stderr, "error: grace time is too large\n");
5599                 return CMD_HELP;
5600         }
5601
5602         mnt = argv[optind];
5603         rc = llapi_quotactl(mnt, &qctl);
5604         if (rc) {
5605                 if (*obd_type)
5606                         fprintf(stderr, "%s %s ", obd_type,
5607                                 obd_uuid2str(&qctl.obd_uuid));
5608                 fprintf(stderr, "setquota failed: %s\n", strerror(-rc));
5609                 return rc;
5610         }
5611
5612         return 0;
5613 }
5614
5615 #define BSLIMIT (1 << 0)
5616 #define BHLIMIT (1 << 1)
5617 #define ISLIMIT (1 << 2)
5618 #define IHLIMIT (1 << 3)
5619
5620 int lfs_setquota(int argc, char **argv)
5621 {
5622         int c, rc = 0;
5623         struct if_quotactl qctl;
5624         char *mnt, *obd_type = (char *)qctl.obd_type;
5625         struct obd_dqblk *dqb = &qctl.qc_dqblk;
5626         struct option long_opts[] = {
5627         { .val = 'b',   .name = "block-softlimit",
5628                                                 .has_arg = required_argument },
5629         { .val = 'B',   .name = "block-hardlimit",
5630                                                 .has_arg = required_argument },
5631         { .val = 'd',   .name = "default",      .has_arg = no_argument },
5632         { .val = 'g',   .name = "group",        .has_arg = required_argument },
5633         { .val = 'G',   .name = "default-grp",  .has_arg = no_argument },
5634         { .val = 'i',   .name = "inode-softlimit",
5635                                                 .has_arg = required_argument },
5636         { .val = 'I',   .name = "inode-hardlimit",
5637                                                 .has_arg = required_argument },
5638         { .val = 'p',   .name = "projid",       .has_arg = required_argument },
5639         { .val = 'P',   .name = "default-prj",  .has_arg = no_argument },
5640         { .val = 'u',   .name = "user",         .has_arg = required_argument },
5641         { .val = 'U',   .name = "default-usr",  .has_arg = no_argument },
5642         { .name = NULL } };
5643         unsigned limit_mask = 0;
5644         char *endptr;
5645         bool use_default = false;
5646         int qtype;
5647
5648         if (has_times_option(argc, argv))
5649                 return lfs_setquota_times(argc, argv);
5650
5651         memset(&qctl, 0, sizeof(qctl));
5652         qctl.qc_cmd  = LUSTRE_Q_SETQUOTA;
5653         qctl.qc_type = ALLQUOTA; /* ALLQUOTA makes no sense for setquota,
5654                                   * so it can be used as a marker that qc_type
5655                                   * isn't reinitialized from command line */
5656
5657         while ((c = getopt_long(argc, argv, "b:B:dg:Gi:I:p:Pu:U",
5658                 long_opts, NULL)) != -1) {
5659                 switch (c) {
5660                 case 'U':
5661                         qctl.qc_cmd = LUSTRE_Q_SETDEFAULT;
5662                         qtype = USRQUOTA;
5663                         qctl.qc_id = 0;
5664                         goto quota_type_def;
5665                 case 'u':
5666                         qtype = USRQUOTA;
5667                         rc = name2uid(&qctl.qc_id, optarg);
5668                         goto quota_type;
5669                 case 'G':
5670                         qctl.qc_cmd = LUSTRE_Q_SETDEFAULT;
5671                         qtype = GRPQUOTA;
5672                         qctl.qc_id = 0;
5673                         goto quota_type_def;
5674                 case 'g':
5675                         qtype = GRPQUOTA;
5676                         rc = name2gid(&qctl.qc_id, optarg);
5677                         goto quota_type;
5678                 case 'P':
5679                         qctl.qc_cmd = LUSTRE_Q_SETDEFAULT;
5680                         qtype = PRJQUOTA;
5681                         qctl.qc_id = 0;
5682                         goto quota_type_def;
5683                 case 'p':
5684                         qtype = PRJQUOTA;
5685                         rc = name2projid(&qctl.qc_id, optarg);
5686 quota_type:
5687                         if (rc) {
5688                                 qctl.qc_id = strtoul(optarg, &endptr, 10);
5689                                 if (*endptr != '\0') {
5690                                         fprintf(stderr, "%s setquota: invalid"
5691                                                 " id '%s'\n", progname, optarg);
5692                                         return -1;
5693                                 }
5694                         }
5695
5696                         if (qctl.qc_id == 0) {
5697                                 fprintf(stderr, "%s setquota: can't set quota"
5698                                         " for root usr/group/project.\n",
5699                                         progname);
5700                                 return -1;
5701                         }
5702
5703 quota_type_def:
5704                         if (qctl.qc_type != ALLQUOTA) {
5705                                 fprintf(stderr,
5706                                         "%s setquota: only one of -u, -U, -g,"
5707                                         " -G, -p or -P may be specified\n",
5708                                         progname);
5709                                 return CMD_HELP;
5710                         }
5711                         qctl.qc_type = qtype;
5712                         break;
5713                 case 'd':
5714                         qctl.qc_cmd = LUSTRE_Q_SETDEFAULT;
5715                         use_default = true;
5716                         break;
5717                 case 'b':
5718                         ARG2ULL(dqb->dqb_bsoftlimit, optarg, 1024);
5719                         dqb->dqb_bsoftlimit >>= 10;
5720                         limit_mask |= BSLIMIT;
5721                         if (dqb->dqb_bsoftlimit &&
5722                             dqb->dqb_bsoftlimit <= 1024) /* <= 1M? */
5723                                 fprintf(stderr,
5724                                         "%s setquota: warning: block softlimit '%llu' smaller than minimum qunit size\n"
5725                                         "See '%s help setquota' or Lustre manual for details\n",
5726                                         progname, dqb->dqb_bsoftlimit,
5727                                         progname);
5728                         break;
5729                 case 'B':
5730                         ARG2ULL(dqb->dqb_bhardlimit, optarg, 1024);
5731                         dqb->dqb_bhardlimit >>= 10;
5732                         limit_mask |= BHLIMIT;
5733                         if (dqb->dqb_bhardlimit &&
5734                             dqb->dqb_bhardlimit <= 1024) /* <= 1M? */
5735                                 fprintf(stderr,
5736                                         "%s setquota: warning: block hardlimit '%llu' smaller than minimum qunit size\n"
5737                                         "See '%s help setquota' or Lustre manual for details\n",
5738                                         progname, dqb->dqb_bhardlimit,
5739                                         progname);
5740                         break;
5741                 case 'i':
5742                         ARG2ULL(dqb->dqb_isoftlimit, optarg, 1);
5743                         limit_mask |= ISLIMIT;
5744                         if (dqb->dqb_isoftlimit &&
5745                             dqb->dqb_isoftlimit <= 1024) /* <= 1K inodes? */
5746                                 fprintf(stderr,
5747                                         "%s setquota: warning: inode softlimit '%llu' smaller than minimum qunit size\n"
5748                                         "See '%s help setquota' or Lustre manual for details\n",
5749                                         progname, dqb->dqb_isoftlimit,
5750                                         progname);
5751                         break;
5752                 case 'I':
5753                         ARG2ULL(dqb->dqb_ihardlimit, optarg, 1);
5754                         limit_mask |= IHLIMIT;
5755                         if (dqb->dqb_ihardlimit &&
5756                             dqb->dqb_ihardlimit <= 1024) /* <= 1K inodes? */
5757                                 fprintf(stderr,
5758                                         "%s setquota: warning: inode hardlimit '%llu' smaller than minimum qunit size\n"
5759                                         "See '%s help setquota' or Lustre manual for details\n",
5760                                         progname, dqb->dqb_ihardlimit,
5761                                         progname);
5762                         break;
5763                 default:
5764                         fprintf(stderr,
5765                                 "%s setquota: unrecognized option '%s'\n",
5766                                 progname, argv[optind - 1]);
5767                         return CMD_HELP;
5768                 }
5769         }
5770
5771         if (qctl.qc_type == ALLQUOTA) {
5772                 fprintf(stderr,
5773                         "%s setquota: either -u or -g must be specified\n",
5774                         progname);
5775                 return CMD_HELP;
5776         }
5777
5778         if (!use_default && limit_mask == 0) {
5779                 fprintf(stderr,
5780                         "%s setquota: at least one limit must be specified\n",
5781                         progname);
5782                 return CMD_HELP;
5783         }
5784
5785         if (use_default && limit_mask != 0) {
5786                 fprintf(stderr,
5787                         "%s setquota: limits should not be specified when"
5788                         " using default quota\n",
5789                         progname);
5790                 return CMD_HELP;
5791         }
5792
5793         if (use_default && qctl.qc_id == 0) {
5794                 fprintf(stderr,
5795                         "%s setquota: can not set default quota for root"
5796                         " user/group/project\n",
5797                         progname);
5798                 return CMD_HELP;
5799         }
5800
5801         if (optind != argc - 1) {
5802                 fprintf(stderr,
5803                         "%s setquota: filesystem not specified or unexpected argument '%s'\n",
5804                         progname, argv[optind]);
5805                 return CMD_HELP;
5806         }
5807
5808         mnt = argv[optind];
5809
5810         if (use_default) {
5811                 dqb->dqb_bhardlimit = 0;
5812                 dqb->dqb_bsoftlimit = 0;
5813                 dqb->dqb_ihardlimit = 0;
5814                 dqb->dqb_isoftlimit = 0;
5815                 dqb->dqb_itime = 0;
5816                 dqb->dqb_btime = 0;
5817                 dqb->dqb_valid |= QIF_LIMITS | QIF_TIMES;
5818         } else if ((!(limit_mask & BHLIMIT) ^ !(limit_mask & BSLIMIT)) ||
5819                    (!(limit_mask & IHLIMIT) ^ !(limit_mask & ISLIMIT))) {
5820                 /* sigh, we can't just set blimits/ilimits */
5821                 struct if_quotactl tmp_qctl = {.qc_cmd  = LUSTRE_Q_GETQUOTA,
5822                                                .qc_type = qctl.qc_type,
5823                                                .qc_id   = qctl.qc_id};
5824
5825                 rc = llapi_quotactl(mnt, &tmp_qctl);
5826                 if (rc < 0)
5827                         return rc;
5828
5829                 if (!(limit_mask & BHLIMIT))
5830                         dqb->dqb_bhardlimit = tmp_qctl.qc_dqblk.dqb_bhardlimit;
5831                 if (!(limit_mask & BSLIMIT))
5832                         dqb->dqb_bsoftlimit = tmp_qctl.qc_dqblk.dqb_bsoftlimit;
5833                 if (!(limit_mask & IHLIMIT))
5834                         dqb->dqb_ihardlimit = tmp_qctl.qc_dqblk.dqb_ihardlimit;
5835                 if (!(limit_mask & ISLIMIT))
5836                         dqb->dqb_isoftlimit = tmp_qctl.qc_dqblk.dqb_isoftlimit;
5837
5838                 /* Keep grace times if we have got no softlimit arguments */
5839                 if ((limit_mask & BHLIMIT) && !(limit_mask & BSLIMIT)) {
5840                         dqb->dqb_valid |= QIF_BTIME;
5841                         dqb->dqb_btime = tmp_qctl.qc_dqblk.dqb_btime;
5842                 }
5843
5844                 if ((limit_mask & IHLIMIT) && !(limit_mask & ISLIMIT)) {
5845                         dqb->dqb_valid |= QIF_ITIME;
5846                         dqb->dqb_itime = tmp_qctl.qc_dqblk.dqb_itime;
5847                 }
5848         }
5849
5850         dqb->dqb_valid |= (limit_mask & (BHLIMIT | BSLIMIT)) ? QIF_BLIMITS : 0;
5851         dqb->dqb_valid |= (limit_mask & (IHLIMIT | ISLIMIT)) ? QIF_ILIMITS : 0;
5852
5853         rc = llapi_quotactl(mnt, &qctl);
5854         if (rc) {
5855                 if (*obd_type)
5856                         fprintf(stderr,
5857                                 "%s setquota: cannot quotactl '%s' '%s': %s",
5858                                 progname, obd_type,
5859                                 obd_uuid2str(&qctl.obd_uuid), strerror(-rc));
5860                 return rc;
5861         }
5862
5863         return 0;
5864 }
5865
5866 /* Converts seconds value into format string
5867  * result is returned in buf
5868  * Notes:
5869  *        1. result is in descenting order: 1w2d3h4m5s
5870  *        2. zero fields are not filled (except for p. 3): 5d1s
5871  *        3. zero seconds value is presented as "0s"
5872  */
5873 static char * __sec2str(time_t seconds, char *buf)
5874 {
5875         const char spec[] = "smhdw";
5876         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
5877         unsigned long c;
5878         char *tail = buf;
5879         int i;
5880
5881         for (i = sizeof(mult) / sizeof(mult[0]) - 1 ; i >= 0; i--) {
5882                 c = seconds / mult[i];
5883
5884                 if (c > 0 || (i == 0 && buf == tail))
5885                         tail += snprintf(tail, 40-(tail-buf), "%lu%c", c, spec[i]);
5886
5887                 seconds %= mult[i];
5888         }
5889
5890         return tail;
5891 }
5892
5893 static void sec2str(time_t seconds, char *buf, int rc)
5894 {
5895         char *tail = buf;
5896
5897         if (rc)
5898                 *tail++ = '[';
5899
5900         tail = __sec2str(seconds, tail);
5901
5902         if (rc && tail - buf < 39) {
5903                 *tail++ = ']';
5904                 *tail++ = 0;
5905         }
5906 }
5907
5908 static void diff2str(time_t seconds, char *buf, time_t now)
5909 {
5910
5911         buf[0] = 0;
5912         if (!seconds)
5913                 return;
5914         if (seconds <= now) {
5915                 strcpy(buf, "none");
5916                 return;
5917         }
5918         __sec2str(seconds - now, buf);
5919 }
5920
5921 static void print_quota_title(char *name, struct if_quotactl *qctl,
5922                               bool human_readable, bool show_default)
5923 {
5924         if (show_default) {
5925                 printf("Disk default %s quota:\n", qtype_name(qctl->qc_type));
5926                 printf("%15s %8s%8s%8s %8s%8s%8s\n",
5927                        "Filesystem", "bquota", "blimit", "bgrace",
5928                        "iquota", "ilimit", "igrace");
5929         } else {
5930                 printf("Disk quotas for %s %s (%cid %u):\n",
5931                        qtype_name(qctl->qc_type), name,
5932                        *qtype_name(qctl->qc_type), qctl->qc_id);
5933                 printf("%15s%8s %7s%8s%8s%8s %7s%8s%8s\n",
5934                        "Filesystem", human_readable ? "used" : "kbytes",
5935                        "quota", "limit", "grace",
5936                        "files", "quota", "limit", "grace");
5937         }
5938 }
5939
5940 static void kbytes2str(__u64 num, char *buf, int buflen, bool h)
5941 {
5942         if (!h) {
5943                 snprintf(buf, buflen, "%ju", (uintmax_t)num);
5944         } else {
5945                 if (num >> 40)
5946                         snprintf(buf, buflen, "%5.4gP",
5947                                  (double)num / ((__u64)1 << 40));
5948                 else if (num >> 30)
5949                         snprintf(buf, buflen, "%5.4gT",
5950                                  (double)num / (1 << 30));
5951                 else if (num >> 20)
5952                         snprintf(buf, buflen, "%5.4gG",
5953                                  (double)num / (1 << 20));
5954                 else if (num >> 10)
5955                         snprintf(buf, buflen, "%5.4gM",
5956                                  (double)num / (1 << 10));
5957                 else
5958                         snprintf(buf, buflen, "%ju%s", (uintmax_t)num, "k");
5959         }
5960 }
5961
5962 #define STRBUF_LEN      32
5963 static void print_quota(char *mnt, struct if_quotactl *qctl, int type,
5964                         int rc, bool h, bool show_default)
5965 {
5966         time_t now;
5967
5968         time(&now);
5969
5970         if (qctl->qc_cmd == LUSTRE_Q_GETQUOTA || qctl->qc_cmd == Q_GETOQUOTA ||
5971             qctl->qc_cmd == LUSTRE_Q_GETDEFAULT) {
5972                 int bover = 0, iover = 0;
5973                 struct obd_dqblk *dqb = &qctl->qc_dqblk;
5974                 char numbuf[3][STRBUF_LEN];
5975                 char timebuf[40];
5976                 char strbuf[STRBUF_LEN];
5977
5978                 if (dqb->dqb_bhardlimit &&
5979                     lustre_stoqb(dqb->dqb_curspace) >= dqb->dqb_bhardlimit) {
5980                         bover = 1;
5981                 } else if (dqb->dqb_bsoftlimit && dqb->dqb_btime) {
5982                         if (dqb->dqb_btime > now) {
5983                                 bover = 2;
5984                         } else {
5985                                 bover = 3;
5986                         }
5987                 }
5988
5989                 if (dqb->dqb_ihardlimit &&
5990                     dqb->dqb_curinodes >= dqb->dqb_ihardlimit) {
5991                         iover = 1;
5992                 } else if (dqb->dqb_isoftlimit && dqb->dqb_itime) {
5993                         if (dqb->dqb_itime > now) {
5994                                 iover = 2;
5995                         } else {
5996                                 iover = 3;
5997                         }
5998                 }
5999
6000
6001                 if (strlen(mnt) > 15)
6002                         printf("%s\n%15s", mnt, "");
6003                 else
6004                         printf("%15s", mnt);
6005
6006                 if (bover)
6007                         diff2str(dqb->dqb_btime, timebuf, now);
6008                 else if (show_default)
6009                         snprintf(timebuf, sizeof(timebuf), "%llu",
6010                                  dqb->dqb_btime);
6011
6012                 kbytes2str(lustre_stoqb(dqb->dqb_curspace),
6013                            strbuf, sizeof(strbuf), h);
6014                 if (rc == -EREMOTEIO)
6015                         sprintf(numbuf[0], "%s*", strbuf);
6016                 else
6017                         sprintf(numbuf[0], (dqb->dqb_valid & QIF_SPACE) ?
6018                                 "%s" : "[%s]", strbuf);
6019
6020                 kbytes2str(dqb->dqb_bsoftlimit, strbuf, sizeof(strbuf), h);
6021                 if (type == QC_GENERAL)
6022                         sprintf(numbuf[1], (dqb->dqb_valid & QIF_BLIMITS) ?
6023                                 "%s" : "[%s]", strbuf);
6024                 else
6025                         sprintf(numbuf[1], "%s", "-");
6026
6027                 kbytes2str(dqb->dqb_bhardlimit, strbuf, sizeof(strbuf), h);
6028                 sprintf(numbuf[2], (dqb->dqb_valid & QIF_BLIMITS) ?
6029                         "%s" : "[%s]", strbuf);
6030
6031                 if (show_default)
6032                         printf(" %6s %7s %7s", numbuf[1], numbuf[2], timebuf);
6033                 else
6034                         printf(" %7s%c %6s %7s %7s",
6035                                numbuf[0], bover ? '*' : ' ', numbuf[1],
6036                                numbuf[2], bover > 1 ? timebuf : "-");
6037
6038
6039                 if (iover)
6040                         diff2str(dqb->dqb_itime, timebuf, now);
6041                 else if (show_default)
6042                         snprintf(timebuf, sizeof(timebuf), "%llu",
6043                                  dqb->dqb_itime);
6044
6045                 snprintf(numbuf[0], sizeof(numbuf),
6046                          (dqb->dqb_valid & QIF_INODES) ? "%ju" : "[%ju]",
6047                          (uintmax_t)dqb->dqb_curinodes);
6048
6049                 if (type == QC_GENERAL)
6050                         sprintf(numbuf[1], (dqb->dqb_valid & QIF_ILIMITS) ?
6051                                 "%ju" : "[%ju]",
6052                                 (uintmax_t)dqb->dqb_isoftlimit);
6053                 else
6054                         sprintf(numbuf[1], "%s", "-");
6055
6056                 sprintf(numbuf[2], (dqb->dqb_valid & QIF_ILIMITS) ?
6057                         "%ju" : "[%ju]", (uintmax_t)dqb->dqb_ihardlimit);
6058
6059                 if (show_default)
6060                         printf(" %6s %7s %7s", numbuf[1], numbuf[2], timebuf);
6061                 else if (type != QC_OSTIDX)
6062                         printf(" %7s%c %6s %7s %7s",
6063                                numbuf[0], iover ? '*' : ' ', numbuf[1],
6064                                numbuf[2], iover > 1 ? timebuf : "-");
6065                 else
6066                         printf(" %7s %7s %7s %7s", "-", "-", "-", "-");
6067                 printf("\n");
6068
6069         } else if (qctl->qc_cmd == LUSTRE_Q_GETINFO ||
6070                    qctl->qc_cmd == Q_GETOINFO) {
6071                 char bgtimebuf[40];
6072                 char igtimebuf[40];
6073
6074                 sec2str(qctl->qc_dqinfo.dqi_bgrace, bgtimebuf, rc);
6075                 sec2str(qctl->qc_dqinfo.dqi_igrace, igtimebuf, rc);
6076                 printf("Block grace time: %s; Inode grace time: %s\n",
6077                        bgtimebuf, igtimebuf);
6078         }
6079 }
6080
6081 static int print_obd_quota(char *mnt, struct if_quotactl *qctl, int is_mdt,
6082                            bool h, __u64 *total)
6083 {
6084         int rc = 0, rc1 = 0, count = 0;
6085         __u32 valid = qctl->qc_valid;
6086
6087         rc = llapi_get_obd_count(mnt, &count, is_mdt);
6088         if (rc) {
6089                 fprintf(stderr, "can not get %s count: %s\n",
6090                         is_mdt ? "mdt": "ost", strerror(-rc));
6091                 return rc;
6092         }
6093
6094         for (qctl->qc_idx = 0; qctl->qc_idx < count; qctl->qc_idx++) {
6095                 qctl->qc_valid = is_mdt ? QC_MDTIDX : QC_OSTIDX;
6096                 rc = llapi_quotactl(mnt, qctl);
6097                 if (rc) {
6098                         /* It is remote client case. */
6099                         if (rc == -EOPNOTSUPP) {
6100                                 rc = 0;
6101                                 goto out;
6102                         }
6103
6104                         if (!rc1)
6105                                 rc1 = rc;
6106                         fprintf(stderr, "quotactl %s%d failed.\n",
6107                                 is_mdt ? "mdt": "ost", qctl->qc_idx);
6108                         continue;
6109                 }
6110
6111                 print_quota(obd_uuid2str(&qctl->obd_uuid), qctl,
6112                             qctl->qc_valid, 0, h, false);
6113                 *total += is_mdt ? qctl->qc_dqblk.dqb_ihardlimit :
6114                                    qctl->qc_dqblk.dqb_bhardlimit;
6115         }
6116 out:
6117         qctl->qc_valid = valid;
6118         return rc ? : rc1;
6119 }
6120
6121 static int get_print_quota(char *mnt, char *name, struct if_quotactl *qctl,
6122                            int verbose, int quiet, bool human_readable,
6123                            bool show_default)
6124 {
6125         int rc1 = 0, rc2 = 0, rc3 = 0;
6126         char *obd_type = (char *)qctl->obd_type;
6127         char *obd_uuid = (char *)qctl->obd_uuid.uuid;
6128         __u64 total_ialloc = 0, total_balloc = 0;
6129         bool use_default_for_blk = false;
6130         bool use_default_for_file = false;
6131         int inacc;
6132
6133         rc1 = llapi_quotactl(mnt, qctl);
6134         if (rc1 < 0) {
6135                 switch (rc1) {
6136                 case -ESRCH:
6137                         fprintf(stderr, "%s quotas are not enabled.\n",
6138                                 qtype_name(qctl->qc_type));
6139                         goto out;
6140                 case -EPERM:
6141                         fprintf(stderr, "Permission denied.\n");
6142                 case -ENODEV:
6143                 case -ENOENT:
6144                         /* We already got error message. */
6145                         goto out;
6146                 default:
6147                         fprintf(stderr, "Unexpected quotactl error: %s\n",
6148                                 strerror(-rc1));
6149                 }
6150         }
6151
6152         if (!show_default && qctl->qc_id == 0) {
6153                 qctl->qc_dqblk.dqb_bhardlimit = 0;
6154                 qctl->qc_dqblk.dqb_bsoftlimit = 0;
6155                 qctl->qc_dqblk.dqb_ihardlimit = 0;
6156                 qctl->qc_dqblk.dqb_isoftlimit = 0;
6157                 qctl->qc_dqblk.dqb_btime = 0;
6158                 qctl->qc_dqblk.dqb_itime = 0;
6159                 qctl->qc_dqblk.dqb_valid |= QIF_LIMITS | QIF_TIMES;
6160         }
6161
6162         if (qctl->qc_dqblk.dqb_valid & QIF_BTIME &&
6163             LQUOTA_FLAG(qctl->qc_dqblk.dqb_btime) & LQUOTA_FLAG_DEFAULT) {
6164                 use_default_for_blk = true;
6165                 qctl->qc_dqblk.dqb_btime &= LQUOTA_GRACE_MASK;
6166         }
6167
6168         if (qctl->qc_dqblk.dqb_valid & QIF_ITIME &&
6169             LQUOTA_FLAG(qctl->qc_dqblk.dqb_itime) & LQUOTA_FLAG_DEFAULT) {
6170                 use_default_for_file = true;
6171                 qctl->qc_dqblk.dqb_itime &= LQUOTA_GRACE_MASK;
6172         }
6173
6174         if ((qctl->qc_cmd == LUSTRE_Q_GETQUOTA ||
6175              qctl->qc_cmd == LUSTRE_Q_GETDEFAULT) && !quiet)
6176                 print_quota_title(name, qctl, human_readable, show_default);
6177
6178         if (rc1 && *obd_type)
6179                 fprintf(stderr, "%s %s ", obd_type, obd_uuid);
6180
6181         if (qctl->qc_valid != QC_GENERAL)
6182                 mnt = "";
6183
6184         inacc = (qctl->qc_cmd == LUSTRE_Q_GETQUOTA) &&
6185                 ((qctl->qc_dqblk.dqb_valid & (QIF_LIMITS|QIF_USAGE)) !=
6186                  (QIF_LIMITS|QIF_USAGE));
6187
6188         print_quota(mnt, qctl, QC_GENERAL, rc1, human_readable, show_default);
6189
6190         if (!show_default && verbose &&
6191             qctl->qc_valid == QC_GENERAL && qctl->qc_cmd != LUSTRE_Q_GETINFO) {
6192                 char strbuf[STRBUF_LEN];
6193
6194                 rc2 = print_obd_quota(mnt, qctl, 1, human_readable,
6195                                       &total_ialloc);
6196                 rc3 = print_obd_quota(mnt, qctl, 0, human_readable,
6197                                       &total_balloc);
6198                 kbytes2str(total_balloc, strbuf, sizeof(strbuf),
6199                            human_readable);
6200                 printf("Total allocated inode limit: %ju, total "
6201                        "allocated block limit: %s\n", (uintmax_t)total_ialloc,
6202                        strbuf);
6203         }
6204
6205         if (use_default_for_blk)
6206                 printf("%cid %u is using default block quota setting\n",
6207                        *qtype_name(qctl->qc_type), qctl->qc_id);
6208
6209         if (use_default_for_file)
6210                 printf("%cid %u is using default file quota setting\n",
6211                        *qtype_name(qctl->qc_type), qctl->qc_id);
6212
6213         if (rc1 || rc2 || rc3 || inacc)
6214                 printf("Some errors happened when getting quota info. "
6215                        "Some devices may be not working or deactivated. "
6216                        "The data in \"[]\" is inaccurate.\n");
6217 out:
6218         return rc1;
6219
6220 }
6221
6222 static int lfs_project(int argc, char **argv)
6223 {
6224         int ret = 0, err = 0, c, i;
6225         struct project_handle_control phc = { 0 };
6226         enum lfs_project_ops_t op;
6227
6228         phc.newline = true;
6229         phc.assign_projid = false;
6230         /* default action */
6231         op = LFS_PROJECT_LIST;
6232
6233         while ((c = getopt(argc, argv, "p:cCsdkr0")) != -1) {
6234                 switch (c) {
6235                 case 'c':
6236                         if (op != LFS_PROJECT_LIST) {
6237                                 fprintf(stderr,
6238                                         "%s: cannot specify '-c' '-C' '-s' together\n",
6239                                         progname);
6240                                 return CMD_HELP;
6241                         }
6242
6243                         op = LFS_PROJECT_CHECK;
6244                         break;
6245                 case 'C':
6246                         if (op != LFS_PROJECT_LIST) {
6247                                 fprintf(stderr,
6248                                         "%s: cannot specify '-c' '-C' '-s' together\n",
6249                                         progname);
6250                                 return CMD_HELP;
6251                         }
6252
6253                         op = LFS_PROJECT_CLEAR;
6254                         break;
6255                 case 's':
6256                         if (op != LFS_PROJECT_LIST) {
6257                                 fprintf(stderr,
6258                                         "%s: cannot specify '-c' '-C' '-s' together\n",
6259                                         progname);
6260                                 return CMD_HELP;
6261                         }
6262
6263                         phc.set_inherit = true;
6264                         op = LFS_PROJECT_SET;
6265                         break;
6266                 case 'd':
6267                         phc.dironly = true;
6268                         break;
6269                 case 'k':
6270                         phc.keep_projid = true;
6271                         break;
6272                 case 'r':
6273                         phc.recursive = true;
6274                         break;
6275                 case 'p':
6276                         phc.projid = strtoul(optarg, NULL, 0);
6277                         phc.assign_projid = true;
6278
6279                         break;
6280                 case '0':
6281                         phc.newline = false;
6282                         break;
6283                 default:
6284                         fprintf(stderr, "%s: invalid option '%c'\n",
6285                                 progname, optopt);
6286                         return CMD_HELP;
6287                 }
6288         }
6289
6290         if (phc.assign_projid && op == LFS_PROJECT_LIST) {
6291                 op = LFS_PROJECT_SET;
6292                 phc.set_projid = true;
6293         } else if (phc.assign_projid && op == LFS_PROJECT_SET) {
6294                 phc.set_projid = true;
6295         }
6296
6297         switch (op) {
6298         case LFS_PROJECT_CHECK:
6299                 if (phc.keep_projid) {
6300                         fprintf(stderr,
6301                                 "%s: '-k' is useless together with '-c'\n",
6302                                 progname);
6303                         return CMD_HELP;
6304                 }
6305                 break;
6306         case LFS_PROJECT_CLEAR:
6307                 if (!phc.newline) {
6308                         fprintf(stderr,
6309                                 "%s: '-0' is useless together with '-C'\n",
6310                                 progname);
6311                         return CMD_HELP;
6312                 }
6313                 if (phc.assign_projid) {
6314                         fprintf(stderr,
6315                                 "%s: '-p' is useless together with '-C'\n",
6316                                 progname);
6317                         return CMD_HELP;
6318                 }
6319                 break;
6320         case LFS_PROJECT_SET:
6321                 if (!phc.newline) {
6322                         fprintf(stderr,
6323                                 "%s: '-0' is useless together with '-s'\n",
6324                                 progname);
6325                         return CMD_HELP;
6326                 }
6327                 if (phc.keep_projid) {
6328                         fprintf(stderr,
6329                                 "%s: '-k' is useless together with '-s'\n",
6330                                 progname);
6331                         return CMD_HELP;
6332                 }
6333                 break;
6334         default:
6335                 if (!phc.newline) {
6336                         fprintf(stderr,
6337                                 "%s: '-0' is useless for list operations\n",
6338                                 progname);
6339                         return CMD_HELP;
6340                 }
6341                 break;
6342         }
6343
6344         argv += optind;
6345         argc -= optind;
6346         if (argc == 0) {
6347                 fprintf(stderr, "%s: missing file or directory target(s)\n",
6348                         progname);
6349                 return CMD_HELP;
6350         }
6351
6352         for (i = 0; i < argc; i++) {
6353                 switch (op) {
6354                 case LFS_PROJECT_CHECK:
6355                         err = lfs_project_check(argv[i], &phc);
6356                         break;
6357                 case LFS_PROJECT_LIST:
6358                         err = lfs_project_list(argv[i], &phc);
6359                         break;
6360                 case LFS_PROJECT_CLEAR:
6361                         err = lfs_project_clear(argv[i], &phc);
6362                         break;
6363                 case LFS_PROJECT_SET:
6364                         err = lfs_project_set(argv[i], &phc);
6365                         break;
6366                 default:
6367                         break;
6368                 }
6369                 if (err && !ret)
6370                         ret = err;
6371         }
6372
6373         return ret;
6374 }
6375
6376 static int lfs_quota(int argc, char **argv)
6377 {
6378         int c;
6379         char *mnt, *name = NULL;
6380         struct if_quotactl qctl = { .qc_cmd = LUSTRE_Q_GETQUOTA,
6381                                     .qc_type = ALLQUOTA };
6382         char *obd_uuid = (char *)qctl.obd_uuid.uuid;
6383         int rc = 0, rc1 = 0, verbose = 0, quiet = 0;
6384         char *endptr;
6385         __u32 valid = QC_GENERAL, idx = 0;
6386         bool human_readable = false;
6387         bool show_default = false;
6388         int qtype;
6389
6390         while ((c = getopt(argc, argv, "gGi:I:o:pPqtuUvh")) != -1) {
6391                 switch (c) {
6392                 case 'U':
6393                         show_default = true;
6394                 case 'u':
6395                         qtype = USRQUOTA;
6396                         goto quota_type;
6397                 case 'G':
6398                         show_default = true;
6399                 case 'g':
6400                         qtype = GRPQUOTA;
6401                         goto quota_type;
6402                 case 'P':
6403                         show_default = true;
6404                 case 'p':
6405                         qtype = PRJQUOTA;
6406 quota_type:
6407                         if (qctl.qc_type != ALLQUOTA) {
6408                                 fprintf(stderr,
6409                                         "%s quota: only one of -u, -g, or -p may be specified\n",
6410                                         progname);
6411                                 return CMD_HELP;
6412                         }
6413                         qctl.qc_type = qtype;
6414                         break;
6415                 case 't':
6416                         qctl.qc_cmd = LUSTRE_Q_GETINFO;
6417                         break;
6418                 case 'o':
6419                         valid = qctl.qc_valid = QC_UUID;
6420                         snprintf(obd_uuid, sizeof(qctl.obd_uuid), "%s", optarg);
6421                         break;
6422                 case 'i':
6423                         valid = qctl.qc_valid = QC_MDTIDX;
6424                         idx = qctl.qc_idx = atoi(optarg);
6425                         if (idx == 0 && *optarg != '0') {
6426                                 fprintf(stderr,
6427                                         "%s quota: invalid MDT index '%s'\n",
6428                                         progname, optarg);
6429                                 return CMD_HELP;
6430                         }
6431                         break;
6432                 case 'I':
6433                         valid = qctl.qc_valid = QC_OSTIDX;
6434                         idx = qctl.qc_idx = atoi(optarg);
6435                         if (idx == 0 && *optarg != '0') {
6436                                 fprintf(stderr,
6437                                         "%s quota: invalid OST index '%s'\n",
6438                                         progname, optarg);
6439                                 return CMD_HELP;
6440                         }
6441                         break;
6442                 case 'v':
6443                         verbose = 1;
6444                         break;
6445                 case 'q':
6446                         quiet = 1;
6447                         break;
6448                 case 'h':
6449                         human_readable = true;
6450                         break;
6451                 default:
6452                         fprintf(stderr, "%s quota: unrecognized option '%s'\n",
6453                                 progname, argv[optind - 1]);
6454                         return CMD_HELP;
6455                 }
6456         }
6457
6458         /* current uid/gid info for "lfs quota /path/to/lustre/mount" */
6459         if (qctl.qc_cmd == LUSTRE_Q_GETQUOTA && qctl.qc_type == ALLQUOTA &&
6460             optind == argc - 1 && !show_default) {
6461
6462                 qctl.qc_cmd = LUSTRE_Q_GETQUOTA;
6463                 qctl.qc_valid = valid;
6464                 qctl.qc_idx = idx;
6465
6466                 for (qtype = USRQUOTA; qtype <= GRPQUOTA; qtype++) {
6467                         qctl.qc_type = qtype;
6468                         if (qtype == USRQUOTA) {
6469                                 qctl.qc_id = geteuid();
6470                                 rc = uid2name(&name, qctl.qc_id);
6471                         } else {
6472                                 qctl.qc_id = getegid();
6473                                 rc = gid2name(&name, qctl.qc_id);
6474                         }
6475                         if (rc)
6476                                 name = "<unknown>";
6477                         mnt = argv[optind];
6478                         rc1 = get_print_quota(mnt, name, &qctl, verbose, quiet,
6479                                               human_readable, show_default);
6480                         if (rc1 && !rc)
6481                                 rc = rc1;
6482                 }
6483                 return rc;
6484         /* lfs quota -u username /path/to/lustre/mount */
6485         } else if (qctl.qc_cmd == LUSTRE_Q_GETQUOTA) {
6486                 /* options should be followed by u/g-name and mntpoint */
6487                 if ((!show_default && optind + 2 != argc) ||
6488                     (show_default && optind + 1 != argc) ||
6489                     qctl.qc_type == ALLQUOTA) {
6490                         fprintf(stderr,
6491                                 "%s quota: name and mount point must be specified\n",
6492                                 progname);
6493                         return CMD_HELP;
6494                 }
6495
6496                 if (!show_default) {
6497                         name = argv[optind++];
6498                         switch (qctl.qc_type) {
6499                         case USRQUOTA:
6500                                 rc = name2uid(&qctl.qc_id, name);
6501                                 break;
6502                         case GRPQUOTA:
6503                                 rc = name2gid(&qctl.qc_id, name);
6504                                 break;
6505                         case PRJQUOTA:
6506                                 rc = name2projid(&qctl.qc_id, name);
6507                                 break;
6508                         default:
6509                                 rc = -ENOTSUP;
6510                                 break;
6511                         }
6512                 } else {
6513                         qctl.qc_valid = QC_GENERAL;
6514                         qctl.qc_cmd = LUSTRE_Q_GETDEFAULT;
6515                         qctl.qc_id = 0;
6516                 }
6517
6518                 if (rc) {
6519                         qctl.qc_id = strtoul(name, &endptr, 10);
6520                         if (*endptr != '\0') {
6521                                 fprintf(stderr, "%s quota: invalid id '%s'\n",
6522                                         progname, name);
6523                                 return CMD_HELP;
6524                         }
6525                 }
6526         } else if (optind + 1 != argc || qctl.qc_type == ALLQUOTA) {
6527                 fprintf(stderr, "%s quota: missing quota info argument(s)\n",
6528                         progname);
6529                 return CMD_HELP;
6530         }
6531
6532         mnt = argv[optind];
6533         rc = get_print_quota(mnt, name, &qctl, verbose, quiet,
6534                              human_readable, show_default);
6535         return rc;
6536 }
6537 #endif /* HAVE_SYS_QUOTA_H! */
6538
6539 static int flushctx_ioctl(char *mp)
6540 {
6541         int fd, rc;
6542
6543         fd = open(mp, O_RDONLY);
6544         if (fd == -1) {
6545                 fprintf(stderr, "flushctx: error open %s: %s\n",
6546                         mp, strerror(errno));
6547                 return -1;
6548         }
6549
6550         rc = ioctl(fd, LL_IOC_FLUSHCTX);
6551         if (rc == -1)
6552                 fprintf(stderr, "flushctx: error ioctl %s: %s\n",
6553                         mp, strerror(errno));
6554
6555         close(fd);
6556         return rc;
6557 }
6558
6559 static int lfs_flushctx(int argc, char **argv)
6560 {
6561         int     kdestroy = 0, c;
6562         char    mntdir[PATH_MAX] = {'\0'};
6563         int     index = 0;
6564         int     rc = 0;
6565
6566         while ((c = getopt(argc, argv, "k")) != -1) {
6567                 switch (c) {
6568                 case 'k':
6569                         kdestroy = 1;
6570                         break;
6571                 default:
6572                         fprintf(stderr, "error: %s: option '-%c' "
6573                                         "unrecognized\n", argv[0], c);
6574                         return CMD_HELP;
6575                 }
6576         }
6577
6578         if (kdestroy) {
6579             if ((rc = system("kdestroy > /dev/null")) != 0) {
6580                 rc = WEXITSTATUS(rc);
6581                 fprintf(stderr, "error destroying tickets: %d, continuing\n", rc);
6582             }
6583         }
6584
6585         if (optind >= argc) {
6586                 /* flush for all mounted lustre fs. */
6587                 while (!llapi_search_mounts(NULL, index++, mntdir, NULL)) {
6588                         /* Check if we have a mount point */
6589                         if (mntdir[0] == '\0')
6590                                 continue;
6591
6592                         if (flushctx_ioctl(mntdir))
6593                                 rc = -1;
6594
6595                         mntdir[0] = '\0'; /* avoid matching in next loop */
6596                 }
6597         } else {
6598                 /* flush fs as specified */
6599                 while (optind < argc) {
6600                         if (flushctx_ioctl(argv[optind++]))
6601                                 rc = -1;
6602                 }
6603         }
6604         return rc;
6605 }
6606
6607 static int lfs_cp(int argc, char **argv)
6608 {
6609         fprintf(stderr, "remote client copy file(s).\n"
6610                 "obsolete, does not support it anymore.\n");
6611         return 0;
6612 }
6613
6614 static int lfs_ls(int argc, char **argv)
6615 {
6616         fprintf(stderr, "remote client lists directory contents.\n"
6617                 "obsolete, does not support it anymore.\n");
6618         return 0;
6619 }
6620
6621 static int lfs_changelog(int argc, char **argv)
6622 {
6623         void *changelog_priv;
6624         struct changelog_rec *rec;
6625         long long startrec = 0, endrec = 0;
6626         char *mdd;
6627         struct option long_opts[] = {
6628                 { .val = 'f', .name = "follow", .has_arg = no_argument },
6629                 { .name = NULL } };
6630         char short_opts[] = "f";
6631         int rc, follow = 0;
6632
6633         while ((rc = getopt_long(argc, argv, short_opts,
6634                 long_opts, NULL)) != -1) {
6635                 switch (rc) {
6636                 case 'f':
6637                         follow++;
6638                         break;
6639                 default:
6640                         fprintf(stderr,
6641                                 "%s changelog: unrecognized option '%s'\n",
6642                                 progname, argv[optind - 1]);
6643                         return CMD_HELP;
6644                 }
6645         }
6646         if (optind >= argc) {
6647                 fprintf(stderr, "%s changelog: mdtname must be specified\n",
6648                         progname);
6649                 return CMD_HELP;
6650         }
6651
6652         mdd = argv[optind++];
6653         if (argc > optind)
6654                 startrec = strtoll(argv[optind++], NULL, 10);
6655         if (argc > optind)
6656                 endrec = strtoll(argv[optind++], NULL, 10);
6657
6658         rc = llapi_changelog_start(&changelog_priv,
6659                                    CHANGELOG_FLAG_BLOCK |
6660                                    CHANGELOG_FLAG_JOBID |
6661                                    CHANGELOG_FLAG_EXTRA_FLAGS |
6662                                    (follow ? CHANGELOG_FLAG_FOLLOW : 0),
6663                                    mdd, startrec);
6664         if (rc < 0) {
6665                 fprintf(stderr, "%s changelog: cannot start changelog: %s\n",
6666                         progname, strerror(errno = -rc));
6667                 return rc;
6668         }
6669
6670         rc = llapi_changelog_set_xflags(changelog_priv,
6671                                         CHANGELOG_EXTRA_FLAG_UIDGID |
6672                                         CHANGELOG_EXTRA_FLAG_NID |
6673                                         CHANGELOG_EXTRA_FLAG_OMODE |
6674                                         CHANGELOG_EXTRA_FLAG_XATTR);
6675         if (rc < 0) {
6676                 fprintf(stderr,
6677                         "%s changelog: cannot set xflags for changelog: %s\n",
6678                         progname, strerror(errno = -rc));
6679                 return rc;
6680         }
6681
6682         while ((rc = llapi_changelog_recv(changelog_priv, &rec)) == 0) {
6683                 time_t secs;
6684                 struct tm ts;
6685
6686                 if (endrec && rec->cr_index > endrec) {
6687                         llapi_changelog_free(&rec);
6688                         break;
6689                 }
6690                 if (rec->cr_index < startrec) {
6691                         llapi_changelog_free(&rec);
6692                         continue;
6693                 }
6694
6695                 secs = rec->cr_time >> 30;
6696                 gmtime_r(&secs, &ts);
6697                 printf("%ju %02d%-5s %02d:%02d:%02d.%09d %04d.%02d.%02d "
6698                        "0x%x t="DFID, (uintmax_t)rec->cr_index, rec->cr_type,
6699                        changelog_type2str(rec->cr_type),
6700                        ts.tm_hour, ts.tm_min, ts.tm_sec,
6701                        (int)(rec->cr_time & ((1 << 30) - 1)),
6702                        ts.tm_year + 1900, ts.tm_mon + 1, ts.tm_mday,
6703                        rec->cr_flags & CLF_FLAGMASK, PFID(&rec->cr_tfid));
6704
6705                 if (rec->cr_flags & CLF_JOBID) {
6706                         struct changelog_ext_jobid *jid =
6707                                 changelog_rec_jobid(rec);
6708
6709                         if (jid->cr_jobid[0] != '\0')
6710                                 printf(" j=%s", jid->cr_jobid);
6711                 }
6712
6713                 if (rec->cr_flags & CLF_EXTRA_FLAGS) {
6714                         struct changelog_ext_extra_flags *ef =
6715                                 changelog_rec_extra_flags(rec);
6716
6717                         printf(" ef=0x%llx", ef->cr_extra_flags);
6718
6719                         if (ef->cr_extra_flags & CLFE_UIDGID) {
6720                                 struct changelog_ext_uidgid *uidgid =
6721                                         changelog_rec_uidgid(rec);
6722
6723                                 printf(" u=%llu:%llu",
6724                                        uidgid->cr_uid, uidgid->cr_gid);
6725                         }
6726                         if (ef->cr_extra_flags & CLFE_NID) {
6727                                 struct changelog_ext_nid *nid =
6728                                         changelog_rec_nid(rec);
6729
6730                                 printf(" nid=%s",
6731                                        libcfs_nid2str(nid->cr_nid));
6732                         }
6733
6734                         if (ef->cr_extra_flags & CLFE_OPEN) {
6735                                 struct changelog_ext_openmode *omd =
6736                                         changelog_rec_openmode(rec);
6737                                 char mode[] = "---";
6738
6739                                 /* exec mode must be exclusive */
6740                                 if (omd->cr_openflags & MDS_FMODE_EXEC) {
6741                                         mode[2] = 'x';
6742                                 } else {
6743                                         if (omd->cr_openflags & MDS_FMODE_READ)
6744                                                 mode[0] = 'r';
6745                                         if (omd->cr_openflags &
6746                                             (MDS_FMODE_WRITE |
6747                                              MDS_OPEN_TRUNC |
6748                                              MDS_OPEN_APPEND))
6749                                                 mode[1] = 'w';
6750                                 }
6751
6752                                 if (strcmp(mode, "---") != 0)
6753                                         printf(" m=%s", mode);
6754
6755                         }
6756
6757                         if (ef->cr_extra_flags & CLFE_XATTR) {
6758                                 struct changelog_ext_xattr *xattr =
6759                                         changelog_rec_xattr(rec);
6760
6761                                 if (xattr->cr_xattr[0] != '\0')
6762                                         printf(" x=%s", xattr->cr_xattr);
6763                         }
6764                 }
6765
6766                 if (rec->cr_namelen)
6767                         printf(" p="DFID" %.*s", PFID(&rec->cr_pfid),
6768                                rec->cr_namelen, changelog_rec_name(rec));
6769
6770                 if (rec->cr_flags & CLF_RENAME) {
6771                         struct changelog_ext_rename *rnm =
6772                                 changelog_rec_rename(rec);
6773
6774                         if (!fid_is_zero(&rnm->cr_sfid))
6775                                 printf(" s="DFID" sp="DFID" %.*s",
6776                                        PFID(&rnm->cr_sfid),
6777                                        PFID(&rnm->cr_spfid),
6778                                        (int)changelog_rec_snamelen(rec),
6779                                        changelog_rec_sname(rec));
6780                 }
6781                 printf("\n");
6782
6783                 llapi_changelog_free(&rec);
6784         }
6785
6786         llapi_changelog_fini(&changelog_priv);
6787
6788         if (rc < 0)
6789                 fprintf(stderr, "%s changelog: cannot access changelog: %s\n",
6790                         progname, strerror(errno = -rc));
6791
6792         return (rc == 1 ? 0 : rc);
6793 }
6794
6795 static int lfs_changelog_clear(int argc, char **argv)
6796 {
6797         long long endrec;
6798         int rc;
6799
6800         if (argc != 4)
6801                 return CMD_HELP;
6802
6803         endrec = strtoll(argv[3], NULL, 10);
6804
6805         rc = llapi_changelog_clear(argv[1], argv[2], endrec);
6806
6807         if (rc == -EINVAL)
6808                 fprintf(stderr, "%s: record out of range: %llu\n",
6809                         argv[0], endrec);
6810         else if (rc == -ENOENT)
6811                 fprintf(stderr, "%s: no changelog user: %s\n",
6812                         argv[0], argv[2]);
6813         else if (rc)
6814                 fprintf(stderr, "%s error: %s\n", argv[0],
6815                         strerror(-rc));
6816
6817         if (rc)
6818                 errno = -rc;
6819
6820         return rc;
6821 }
6822
6823 static int lfs_fid2path(int argc, char **argv)
6824 {
6825         struct option long_opts[] = {
6826                 { .val = 'c',   .name = "cur",  .has_arg = no_argument },
6827                 { .val = 'l',   .name = "link", .has_arg = required_argument },
6828                 { .val = 'r',   .name = "rec",  .has_arg = required_argument },
6829                 { .name = NULL } };
6830         char  short_opts[] = "cl:r:";
6831         char *device, *fid, *path;
6832         long long recno = -1;
6833         int linkno = -1;
6834         int lnktmp;
6835         int printcur = 0;
6836         int rc = 0;
6837         char *endptr = NULL;
6838
6839         while ((rc = getopt_long(argc, argv, short_opts,
6840                 long_opts, NULL)) != -1) {
6841                 switch (rc) {
6842                 case 'c':
6843                         printcur++;
6844                         break;
6845                 case 'l':
6846                         linkno = strtol(optarg, &endptr, 10);
6847                         if (*endptr != '\0') {
6848                                 fprintf(stderr,
6849                                         "%s fid2path: invalid linkno '%s'\n",
6850                                         progname, optarg);
6851                                 return CMD_HELP;
6852                         }
6853                         break;
6854                 case 'r':
6855                         recno = strtoll(optarg, &endptr, 10);
6856                         if (*endptr != '\0') {
6857                                 fprintf(stderr,
6858                                         "%s fid2path: invalid recno '%s'\n",
6859                                         progname, optarg);
6860                                 return CMD_HELP;
6861                         }
6862                         break;
6863                 default:
6864                         fprintf(stderr,
6865                                 "%s fid2path: unrecognized option '%s'\n",
6866                                 progname, argv[optind - 1]);
6867                         return CMD_HELP;
6868                 }
6869         }
6870
6871         if (argc < 3) {
6872                 fprintf(stderr,
6873                         "%s fid2path: <fsname|rootpath> and <fid>... must be specified\n",
6874                         progname);
6875                 return CMD_HELP;
6876         }
6877
6878         device = argv[optind++];
6879         path = calloc(1, PATH_MAX);
6880         if (path == NULL) {
6881                 rc = -errno;
6882                 fprintf(stderr,
6883                         "%s fid2path: cannot allocate memory for path: %s\n",
6884                         progname, strerror(-rc));
6885                 return rc;
6886         }
6887
6888         rc = 0;
6889         while (optind < argc) {
6890                 fid = argv[optind++];
6891
6892                 lnktmp = (linkno >= 0) ? linkno : 0;
6893                 while (1) {
6894                         int oldtmp = lnktmp;
6895                         long long rectmp = recno;
6896                         int rc2;
6897                         rc2 = llapi_fid2path(device, fid, path, PATH_MAX,
6898                                              &rectmp, &lnktmp);
6899                         if (rc2 < 0) {
6900                                 fprintf(stderr,
6901                                         "%s fid2path: cannot find '%s': %s\n",
6902                                         progname, fid, strerror(errno = -rc2));
6903                                 if (rc == 0)
6904                                         rc = rc2;
6905                                 break;
6906                         }
6907
6908                         if (printcur)
6909                                 fprintf(stdout, "%lld ", rectmp);
6910                         if (device[0] == '/') {
6911                                 fprintf(stdout, "%s", device);
6912                                 if (device[strlen(device) - 1] != '/')
6913                                         fprintf(stdout, "/");
6914                         } else if (path[0] == '\0') {
6915                                 fprintf(stdout, "/");
6916                         }
6917                         fprintf(stdout, "%s\n", path);
6918
6919                         if (linkno >= 0)
6920                                 /* specified linkno */
6921                                 break;
6922                         if (oldtmp == lnktmp)
6923                                 /* no more links */
6924                                 break;
6925                 }
6926         }
6927
6928         free(path);
6929         return rc;
6930 }
6931
6932 static int lfs_path2fid(int argc, char **argv)
6933 {
6934         struct option long_opts[] = {
6935                 { .val = 'p', .name = "parents", .has_arg = no_argument },
6936                 { .name = NULL } };
6937         char            **path;
6938         const char        short_opts[] = "p";
6939         const char       *sep = "";
6940         struct lu_fid     fid;
6941         int               rc = 0;
6942         bool              show_parents = false;
6943
6944         while ((rc = getopt_long(argc, argv, short_opts,
6945                                  long_opts, NULL)) != -1) {
6946                 switch (rc) {
6947                 case 'p':
6948                         show_parents = true;
6949                         break;
6950                 default:
6951                         fprintf(stderr,
6952                                 "%s path2fid: unrecognized option '%s'\n",
6953                                 progname, argv[optind - 1]);
6954                         return CMD_HELP;
6955                 }
6956         }
6957
6958         if (optind > argc - 1) {
6959                 fprintf(stderr, "%s path2fid: FILE... must be specified\n",
6960                         progname);
6961                 return CMD_HELP;
6962         }
6963         else if (optind < argc - 1)
6964                 sep = ": ";
6965
6966         rc = 0;
6967         for (path = argv + optind; *path != NULL; path++) {
6968                 int err = 0;
6969                 if (!show_parents) {
6970                         err = llapi_path2fid(*path, &fid);
6971                         if (!err)
6972                                 printf("%s%s"DFID"\n",
6973                                        *sep != '\0' ? *path : "", sep,
6974                                        PFID(&fid));
6975                 } else {
6976                         char            name[NAME_MAX + 1];
6977                         unsigned int    linkno = 0;
6978
6979                         while ((err = llapi_path2parent(*path, linkno, &fid,
6980                                                 name, sizeof(name))) == 0) {
6981                                 if (*sep != '\0' && linkno == 0)
6982                                         printf("%s%s", *path, sep);
6983
6984                                 printf("%s"DFID"/%s", linkno != 0 ? "\t" : "",
6985                                        PFID(&fid), name);
6986                                 linkno++;
6987                         }
6988
6989                         /* err == -ENODATA is end-of-loop */
6990                         if (linkno > 0 && err == -ENODATA) {
6991                                 printf("\n");
6992                                 err = 0;
6993                         }
6994                 }
6995
6996                 if (err) {
6997                         fprintf(stderr,
6998                                 "%s path2fid: cannot get %sfid for '%s': %s\n",
6999                                 progname, show_parents ? "parent " : "", *path,
7000                                 strerror(-err));
7001                         if (rc == 0) {
7002                                 rc = err;
7003                                 errno = -err;
7004                         }
7005                 }
7006         }
7007
7008         return rc;
7009 }
7010
7011 static int lfs_data_version(int argc, char **argv)
7012 {
7013         char *path;
7014         __u64 data_version;
7015         int fd;
7016         int rc;
7017         int c;
7018         int data_version_flags = LL_DV_RD_FLUSH; /* Read by default */
7019
7020         if (argc < 2) {
7021                 fprintf(stderr, "%s data_version: FILE must be specified\n",
7022                         progname);
7023                 return CMD_HELP;
7024         }
7025
7026         while ((c = getopt(argc, argv, "nrw")) != -1) {
7027                 switch (c) {
7028                 case 'n':
7029                         data_version_flags = 0;
7030                         break;
7031                 case 'r':
7032                         data_version_flags |= LL_DV_RD_FLUSH;
7033                         break;
7034                 case 'w':
7035                         data_version_flags |= LL_DV_WR_FLUSH;
7036                         break;
7037                 default:
7038                         fprintf(stderr,
7039                                 "%s data_version: unrecognized option '%s'\n",
7040                                 progname, argv[optind - 1]);
7041                         return CMD_HELP;
7042                 }
7043         }
7044         if (optind == argc) {
7045                 fprintf(stderr, "%s data_version: FILE must be specified\n",
7046                         progname);
7047                 return CMD_HELP;
7048         }
7049
7050         path = argv[optind];
7051         fd = open(path, O_RDONLY);
7052         if (fd < 0) {
7053                 rc = -errno;
7054                 fprintf(stderr, "%s data_version: cannot open file '%s': %s\n",
7055                         progname, path, strerror(-rc));
7056                 return rc;
7057         }
7058
7059         rc = llapi_get_data_version(fd, &data_version, data_version_flags);
7060         if (rc < 0)
7061                 fprintf(stderr,
7062                         "%s data_version: cannot get version for '%s': %s\n",
7063                         progname, path, strerror(-rc));
7064         else
7065                 printf("%ju" "\n", (uintmax_t)data_version);
7066
7067         close(fd);
7068         return rc;
7069 }
7070
7071 static int lfs_hsm_state(int argc, char **argv)
7072 {
7073         int rc;
7074         int i = 1;
7075         char *path;
7076         struct hsm_user_state hus;
7077
7078         if (argc < 2)
7079                 return CMD_HELP;
7080
7081         do {
7082                 path = argv[i];
7083
7084                 rc = llapi_hsm_state_get(path, &hus);
7085                 if (rc) {
7086                         fprintf(stderr, "can't get hsm state for %s: %s\n",
7087                                 path, strerror(errno = -rc));
7088                         return rc;
7089                 }
7090
7091                 /* Display path name and status flags */
7092                 printf("%s: (0x%08x)", path, hus.hus_states);
7093
7094                 if (hus.hus_states & HS_RELEASED)
7095                         printf(" released");
7096                 if (hus.hus_states & HS_EXISTS)
7097                         printf(" exists");
7098                 if (hus.hus_states & HS_DIRTY)
7099                         printf(" dirty");
7100                 if (hus.hus_states & HS_ARCHIVED)
7101                         printf(" archived");
7102                 /* Display user-settable flags */
7103                 if (hus.hus_states & HS_NORELEASE)
7104                         printf(" never_release");
7105                 if (hus.hus_states & HS_NOARCHIVE)
7106                         printf(" never_archive");
7107                 if (hus.hus_states & HS_LOST)
7108                         printf(" lost_from_hsm");
7109
7110                 if (hus.hus_archive_id != 0)
7111                         printf(", archive_id:%d", hus.hus_archive_id);
7112                 printf("\n");
7113
7114         } while (++i < argc);
7115
7116         return 0;
7117 }
7118
7119 #define LFS_HSM_SET   0
7120 #define LFS_HSM_CLEAR 1
7121
7122 /**
7123  * Generic function to set or clear HSM flags.
7124  * Used by hsm_set and hsm_clear.
7125  *
7126  * @mode  if LFS_HSM_SET, set the flags, if LFS_HSM_CLEAR, clear the flags.
7127  */
7128 static int lfs_hsm_change_flags(int argc, char **argv, int mode)
7129 {
7130         struct option long_opts[] = {
7131         { .val = 'A',   .name = "archived",     .has_arg = no_argument },
7132         { .val = 'a',   .name = "noarchive",    .has_arg = no_argument },
7133         { .val = 'd',   .name = "dirty",        .has_arg = no_argument },
7134         { .val = 'e',   .name = "exists",       .has_arg = no_argument },
7135         { .val = 'l',   .name = "lost",         .has_arg = no_argument },
7136         { .val = 'r',   .name = "norelease",    .has_arg = no_argument },
7137         { .val = 'i',   .name = "archive-id",   .has_arg = required_argument },
7138         { .name = NULL } };
7139         char short_opts[] = "lraAdei:";
7140         __u64 mask = 0;
7141         int c, rc;
7142         char *path;
7143         __u32 archive_id = 0;
7144         char *end = NULL;
7145
7146         if (argc < 3)
7147                 return CMD_HELP;
7148
7149         while ((c = getopt_long(argc, argv, short_opts,
7150                                 long_opts, NULL)) != -1) {
7151                 switch (c) {
7152                 case 'l':
7153                         mask |= HS_LOST;
7154                         break;
7155                 case 'a':
7156                         mask |= HS_NOARCHIVE;
7157                         break;
7158                 case 'A':
7159                         mask |= HS_ARCHIVED;
7160                         break;
7161                 case 'r':
7162                         mask |= HS_NORELEASE;
7163                         break;
7164                 case 'd':
7165                         mask |= HS_DIRTY;
7166                         break;
7167                 case 'e':
7168                         mask |= HS_EXISTS;
7169                         break;
7170                 case 'i':
7171                         archive_id = strtol(optarg, &end, 10);
7172                         if (*end != '\0') {
7173                                 fprintf(stderr, "invalid archive_id: '%s'\n",
7174                                         end);
7175                                 return CMD_HELP;
7176                         }
7177                         break;
7178                 case '?':
7179                         return CMD_HELP;
7180                 default:
7181                         fprintf(stderr, "error: %s: option '%s' unrecognized\n",
7182                                 argv[0], argv[optind - 1]);
7183                         return CMD_HELP;
7184                 }
7185         }
7186
7187         /* User should have specified a flag */
7188         if (mask == 0)
7189                 return CMD_HELP;
7190
7191         while (optind < argc) {
7192
7193                 path = argv[optind];
7194
7195                 /* If mode == 0, this means we apply the mask. */
7196                 if (mode == LFS_HSM_SET)
7197                         rc = llapi_hsm_state_set(path, mask, 0, archive_id);
7198                 else
7199                         rc = llapi_hsm_state_set(path, 0, mask, 0);
7200
7201                 if (rc != 0) {
7202                         fprintf(stderr, "Can't change hsm flags for %s: %s\n",
7203                                 path, strerror(errno = -rc));
7204                         return rc;
7205                 }
7206                 optind++;
7207         }
7208
7209         return 0;
7210 }
7211
7212 static int lfs_hsm_action(int argc, char **argv)
7213 {
7214         int                              rc;
7215         int                              i = 1;
7216         char                            *path;
7217         struct hsm_current_action        hca;
7218         struct hsm_extent                he;
7219         enum hsm_user_action             hua;
7220         enum hsm_progress_states         hps;
7221
7222         if (argc < 2)
7223                 return CMD_HELP;
7224
7225         do {
7226                 path = argv[i];
7227
7228                 rc = llapi_hsm_current_action(path, &hca);
7229                 if (rc) {
7230                         fprintf(stderr, "can't get hsm action for %s: %s\n",
7231                                 path, strerror(errno = -rc));
7232                         return rc;
7233                 }
7234                 he = hca.hca_location;
7235                 hua = hca.hca_action;
7236                 hps = hca.hca_state;
7237
7238                 printf("%s: %s", path, hsm_user_action2name(hua));
7239
7240                 /* Skip file without action */
7241                 if (hca.hca_action == HUA_NONE) {
7242                         printf("\n");
7243                         continue;
7244                 }
7245
7246                 printf(" %s ", hsm_progress_state2name(hps));
7247
7248                 if ((hps == HPS_RUNNING) &&
7249                     (hua == HUA_ARCHIVE || hua == HUA_RESTORE))
7250                         printf("(%llu bytes moved)\n",
7251                                (unsigned long long)he.length);
7252                 else if ((he.offset + he.length) == LUSTRE_EOF)
7253                         printf("(from %llu to EOF)\n",
7254                                (unsigned long long)he.offset);
7255                 else
7256                         printf("(from %llu to %llu)\n",
7257                                (unsigned long long)he.offset,
7258                                (unsigned long long)(he.offset + he.length));
7259
7260         } while (++i < argc);
7261
7262         return 0;
7263 }
7264
7265 static int lfs_hsm_set(int argc, char **argv)
7266 {
7267         return lfs_hsm_change_flags(argc, argv, LFS_HSM_SET);
7268 }
7269
7270 static int lfs_hsm_clear(int argc, char **argv)
7271 {
7272         return lfs_hsm_change_flags(argc, argv, LFS_HSM_CLEAR);
7273 }
7274
7275 /**
7276  * Check file state and return its fid, to be used by lfs_hsm_request().
7277  *
7278  * \param[in]     file      Path to file to check
7279  * \param[in,out] fid       Pointer to allocated lu_fid struct.
7280  * \param[in,out] last_dev  Pointer to last device id used.
7281  *
7282  * \return 0 on success.
7283  */
7284 static int lfs_hsm_prepare_file(const char *file, struct lu_fid *fid,
7285                                 dev_t *last_dev)
7286 {
7287         struct stat     st;
7288         int             rc;
7289
7290         rc = lstat(file, &st);
7291         if (rc) {
7292                 fprintf(stderr, "Cannot stat %s: %s\n", file, strerror(errno));
7293                 return -errno;
7294         }
7295         /* Checking for regular file as archiving as posix copytool
7296          * rejects archiving files other than regular files
7297          */
7298         if (!S_ISREG(st.st_mode)) {
7299                 fprintf(stderr, "error: \"%s\" is not a regular file\n", file);
7300                 return CMD_HELP;
7301         }
7302         /* A request should be ... */
7303         if (*last_dev != st.st_dev && *last_dev != 0) {
7304                 fprintf(stderr, "All files should be "
7305                         "on the same filesystem: %s\n", file);
7306                 return -EINVAL;
7307         }
7308         *last_dev = st.st_dev;
7309
7310         rc = llapi_path2fid(file, fid);
7311         if (rc) {
7312                 fprintf(stderr, "Cannot read FID of %s: %s\n",
7313                         file, strerror(-rc));
7314                 return rc;
7315         }
7316         return 0;
7317 }
7318
7319 /* Fill an HSM HUR item with a given file name.
7320  *
7321  * If mntpath is set, then the filename is actually a FID, and no
7322  * lookup on the filesystem will be performed.
7323  *
7324  * \param[in]  hur         the user request to fill
7325  * \param[in]  idx         index of the item inside the HUR to fill
7326  * \param[in]  mntpath     mountpoint of Lustre
7327  * \param[in]  fname       filename (if mtnpath is NULL)
7328  *                         or FID (if mntpath is set)
7329  * \param[in]  last_dev    pointer to last device id used
7330  *
7331  * \retval 0 on success
7332  * \retval CMD_HELP or a negative errno on error
7333  */
7334 static int fill_hur_item(struct hsm_user_request *hur, unsigned int idx,
7335                          const char *mntpath, const char *fname,
7336                          dev_t *last_dev)
7337 {
7338         struct hsm_user_item *hui = &hur->hur_user_item[idx];
7339         int rc;
7340
7341         hui->hui_extent.length = -1;
7342
7343         if (mntpath != NULL) {
7344                 if (*fname == '[')
7345                         fname++;
7346                 rc = sscanf(fname, SFID, RFID(&hui->hui_fid));
7347                 if (rc == 3) {
7348                         rc = 0;
7349                 } else {
7350                         fprintf(stderr, "hsm: '%s' is not a valid FID\n",
7351                                 fname);
7352                         rc = -EINVAL;
7353                 }
7354         } else {
7355                 rc = lfs_hsm_prepare_file(fname, &hui->hui_fid, last_dev);
7356         }
7357
7358         if (rc == 0)
7359                 hur->hur_request.hr_itemcount++;
7360
7361         return rc;
7362 }
7363
7364 static int lfs_hsm_request(int argc, char **argv, int action)
7365 {
7366         struct option long_opts[] = {
7367         { .val = 'a',   .name = "archive",      .has_arg = required_argument },
7368         { .val = 'D',   .name = "data",         .has_arg = required_argument },
7369         { .val = 'l',   .name = "filelist",     .has_arg = required_argument },
7370         { .val = 'm',   .name = "mntpath",      .has_arg = required_argument },
7371         { .name = NULL } };
7372         dev_t                    last_dev = 0;
7373         char                     short_opts[] = "l:D:a:m:";
7374         struct hsm_user_request *hur, *oldhur;
7375         int                      c, i;
7376         size_t                   len;
7377         int                      nbfile;
7378         char                    *line = NULL;
7379         char                    *filelist = NULL;
7380         char                     fullpath[PATH_MAX];
7381         char                    *opaque = NULL;
7382         int                      opaque_len = 0;
7383         int                      archive_id = 0;
7384         FILE                    *fp;
7385         int                      nbfile_alloc = 0;
7386         char                    *some_file = NULL;
7387         char                    *mntpath = NULL;
7388         int                      rc;
7389
7390         if (argc < 2)
7391                 return CMD_HELP;
7392
7393         while ((c = getopt_long(argc, argv, short_opts,
7394                                 long_opts, NULL)) != -1) {
7395                 switch (c) {
7396                 case 'l':
7397                         filelist = optarg;
7398                         break;
7399                 case 'D':
7400                         opaque = optarg;
7401                         break;
7402                 case 'a':
7403                         if (action != HUA_ARCHIVE &&
7404                             action != HUA_REMOVE) {
7405                                 fprintf(stderr,
7406                                         "error: -a is supported only "
7407                                         "when archiving or removing\n");
7408                                 return CMD_HELP;
7409                         }
7410                         archive_id = atoi(optarg);
7411                         break;
7412                 case 'm':
7413                         if (some_file == NULL) {
7414                                 mntpath = optarg;
7415                                 some_file = strdup(optarg);
7416                         }
7417                         break;
7418                 case '?':
7419                         return CMD_HELP;
7420                 default:
7421                         fprintf(stderr, "error: %s: option '%s' unrecognized\n",
7422                                 argv[0], argv[optind - 1]);
7423                         return CMD_HELP;
7424                 }
7425         }
7426
7427         /* All remaining args are files, so we have at least nbfile */
7428         nbfile = argc - optind;
7429
7430         if ((nbfile == 0) && (filelist == NULL))
7431                 return CMD_HELP;
7432
7433         if (opaque != NULL)
7434                 opaque_len = strlen(opaque);
7435
7436         /* Alloc the request structure with enough place to store all files
7437          * from command line. */
7438         hur = llapi_hsm_user_request_alloc(nbfile, opaque_len);
7439         if (hur == NULL) {
7440                 fprintf(stderr, "Cannot create the request: %s\n",
7441                         strerror(errno));
7442                 return errno;
7443         }
7444         nbfile_alloc = nbfile;
7445
7446         hur->hur_request.hr_action = action;
7447         hur->hur_request.hr_archive_id = archive_id;
7448         hur->hur_request.hr_flags = 0;
7449
7450         /* All remaining args are files, add them */
7451         if (nbfile != 0 && some_file == NULL)
7452                 some_file = strdup(argv[optind]);
7453
7454         for (i = 0; i < nbfile; i++) {
7455                 rc = fill_hur_item(hur, i, mntpath, argv[optind + i],
7456                                    &last_dev);
7457                 if (rc)
7458                         goto out_free;
7459         }
7460
7461         /* from here stop using nb_file, use hur->hur_request.hr_itemcount */
7462
7463         /* If a filelist was specified, read the filelist from it. */
7464         if (filelist != NULL) {
7465                 fp = fopen(filelist, "r");
7466                 if (fp == NULL) {
7467                         fprintf(stderr, "Cannot read the file list %s: %s\n",
7468                                 filelist, strerror(errno));
7469                         rc = -errno;
7470                         goto out_free;
7471                 }
7472
7473                 while ((rc = getline(&line, &len, fp)) != -1) {
7474                         /* If allocated buffer was too small, get something
7475                          * larger */
7476                         if (nbfile_alloc <= hur->hur_request.hr_itemcount) {
7477                                 ssize_t size;
7478
7479                                 nbfile_alloc = nbfile_alloc * 2 + 1;
7480                                 oldhur = hur;
7481                                 hur = llapi_hsm_user_request_alloc(nbfile_alloc,
7482                                                                    opaque_len);
7483                                 if (hur == NULL) {
7484                                         fprintf(stderr, "hsm: cannot allocate "
7485                                                 "the request: %s\n",
7486                                                 strerror(errno));
7487                                         hur = oldhur;
7488                                         rc = -errno;
7489                                         fclose(fp);
7490                                         goto out_free;
7491                                 }
7492                                 size = hur_len(oldhur);
7493                                 if (size < 0) {
7494                                         fprintf(stderr, "hsm: cannot allocate "
7495                                                 "%u files + %u bytes data\n",
7496                                             oldhur->hur_request.hr_itemcount,
7497                                             oldhur->hur_request.hr_data_len);
7498                                         free(hur);
7499                                         hur = oldhur;
7500                                         rc = -E2BIG;
7501                                         fclose(fp);
7502                                         goto out_free;
7503                                 }
7504                                 memcpy(hur, oldhur, size);
7505                                 free(oldhur);
7506                         }
7507
7508                         /* Chop CR */
7509                         if (line[strlen(line) - 1] == '\n')
7510                                 line[strlen(line) - 1] = '\0';
7511
7512                         rc = fill_hur_item(hur, hur->hur_request.hr_itemcount,
7513                                            mntpath, line, &last_dev);
7514                         if (rc) {
7515                                 fclose(fp);
7516                                 goto out_free;
7517                         }
7518
7519                         if (some_file == NULL) {
7520                                 some_file = line;
7521                                 line = NULL;
7522                         }
7523                 }
7524
7525                 rc = fclose(fp);
7526                 free(line);
7527         }
7528
7529         /* If a --data was used, add it to the request */
7530         hur->hur_request.hr_data_len = opaque_len;
7531         if (opaque != NULL)
7532                 memcpy(hur_data(hur), opaque, opaque_len);
7533
7534         /* Send the HSM request */
7535         if (realpath(some_file, fullpath) == NULL) {
7536                 fprintf(stderr, "Could not find path '%s': %s\n",
7537                         some_file, strerror(errno));
7538         }
7539         rc = llapi_hsm_request(fullpath, hur);
7540         if (rc) {
7541                 fprintf(stderr, "Cannot send HSM request (use of %s): %s\n",
7542                         some_file, strerror(-rc));
7543                 goto out_free;
7544         }
7545
7546 out_free:
7547         free(some_file);
7548         free(hur);
7549         return rc;
7550 }
7551
7552 static int lfs_hsm_archive(int argc, char **argv)
7553 {
7554         return lfs_hsm_request(argc, argv, HUA_ARCHIVE);
7555 }
7556
7557 static int lfs_hsm_restore(int argc, char **argv)
7558 {
7559         return lfs_hsm_request(argc, argv, HUA_RESTORE);
7560 }
7561
7562 static int lfs_hsm_release(int argc, char **argv)
7563 {
7564         return lfs_hsm_request(argc, argv, HUA_RELEASE);
7565 }
7566
7567 static int lfs_hsm_remove(int argc, char **argv)
7568 {
7569         return lfs_hsm_request(argc, argv, HUA_REMOVE);
7570 }
7571
7572 static int lfs_hsm_cancel(int argc, char **argv)
7573 {
7574         return lfs_hsm_request(argc, argv, HUA_CANCEL);
7575 }
7576
7577 static int lfs_swap_layouts(int argc, char **argv)
7578 {
7579         if (argc != 3)
7580                 return CMD_HELP;
7581
7582         return llapi_swap_layouts(argv[1], argv[2], 0, 0,
7583                                   SWAP_LAYOUTS_KEEP_MTIME |
7584                                   SWAP_LAYOUTS_KEEP_ATIME);
7585 }
7586
7587 static const char *const ladvise_names[] = LU_LADVISE_NAMES;
7588
7589 static const char *const lock_mode_names[] = LOCK_MODE_NAMES;
7590
7591 int lfs_get_mode(const char *string)
7592 {
7593         enum lock_mode_user mode;
7594
7595         for (mode = 0; mode < ARRAY_SIZE(lock_mode_names); mode++) {
7596                 if (lock_mode_names[mode] == NULL)
7597                         continue;
7598                 if (strcmp(string, lock_mode_names[mode]) == 0)
7599                         return mode;
7600         }
7601
7602         return -EINVAL;
7603 }
7604
7605 static enum lu_ladvise_type lfs_get_ladvice(const char *string)
7606 {
7607         enum lu_ladvise_type advice;
7608
7609         for (advice = 0;
7610              advice < ARRAY_SIZE(ladvise_names); advice++) {
7611                 if (ladvise_names[advice] == NULL)
7612                         continue;
7613                 if (strcmp(string, ladvise_names[advice]) == 0)
7614                         return advice;
7615         }
7616
7617         return LU_LADVISE_INVALID;
7618 }
7619
7620 static int lfs_ladvise(int argc, char **argv)
7621 {
7622         struct option long_opts[] = {
7623         { .val = 'a',   .name = "advice",       .has_arg = required_argument },
7624         { .val = 'b',   .name = "background",   .has_arg = no_argument },
7625         { .val = 'e',   .name = "end",          .has_arg = required_argument },
7626         { .val = 'l',   .name = "length",       .has_arg = required_argument },
7627         { .val = 'm',   .name = "mode",         .has_arg = required_argument },
7628         { .val = 's',   .name = "start",        .has_arg = required_argument },
7629         { .val = 'u',   .name = "unset",        .has_arg = no_argument },
7630         { .name = NULL } };
7631         char                     short_opts[] = "a:be:l:m:s:u";
7632         int                      c;
7633         int                      rc = 0;
7634         const char              *path;
7635         int                      fd;
7636         struct llapi_lu_ladvise  advice;
7637         enum lu_ladvise_type     advice_type = LU_LADVISE_INVALID;
7638         unsigned long long       start = 0;
7639         unsigned long long       end = LUSTRE_EOF;
7640         unsigned long long       length = 0;
7641         unsigned long long       size_units;
7642         unsigned long long       flags = 0;
7643         int                      mode = 0;
7644
7645         optind = 0;
7646         while ((c = getopt_long(argc, argv, short_opts,
7647                                 long_opts, NULL)) != -1) {
7648                 switch (c) {
7649                 case 'a':
7650                         advice_type = lfs_get_ladvice(optarg);
7651                         if (advice_type == LU_LADVISE_INVALID) {
7652                                 fprintf(stderr, "%s: invalid advice type "
7653                                         "'%s'\n", argv[0], optarg);
7654                                 fprintf(stderr, "Valid types:");
7655
7656                                 for (advice_type = 0;
7657                                      advice_type < ARRAY_SIZE(ladvise_names);
7658                                      advice_type++) {
7659                                         if (ladvise_names[advice_type] == NULL)
7660                                                 continue;
7661                                         fprintf(stderr, " %s",
7662                                                 ladvise_names[advice_type]);
7663                                 }
7664                                 fprintf(stderr, "\n");
7665
7666                                 return CMD_HELP;
7667                         }
7668                         break;
7669                 case 'b':
7670                         flags |= LF_ASYNC;
7671                         break;
7672                 case 'u':
7673                         flags |= LF_UNSET;
7674                         break;
7675                 case 'e':
7676                         size_units = 1;
7677                         rc = llapi_parse_size(optarg, &end,
7678                                               &size_units, 0);
7679                         if (rc) {
7680                                 fprintf(stderr, "%s: bad end offset '%s'\n",
7681                                         argv[0], optarg);
7682                                 return CMD_HELP;
7683                         }
7684                         break;
7685                 case 's':
7686                         size_units = 1;
7687                         rc = llapi_parse_size(optarg, &start,
7688                                               &size_units, 0);
7689                         if (rc) {
7690                                 fprintf(stderr, "%s: bad start offset "
7691                                         "'%s'\n", argv[0], optarg);
7692                                 return CMD_HELP;
7693                         }
7694                         break;
7695                 case 'l':
7696                         size_units = 1;
7697                         rc = llapi_parse_size(optarg, &length,
7698                                               &size_units, 0);
7699                         if (rc) {
7700                                 fprintf(stderr, "%s: bad length '%s'\n",
7701                                         argv[0], optarg);
7702                                 return CMD_HELP;
7703                         }
7704                         break;
7705                 case 'm':
7706                         mode = lfs_get_mode(optarg);
7707                         if (mode < 0) {
7708                                 fprintf(stderr, "%s: bad mode '%s', valid "
7709                                                  "modes are READ or WRITE\n",
7710                                         argv[0], optarg);
7711                                 return CMD_HELP;
7712                         }
7713                         break;
7714                 case '?':
7715                         return CMD_HELP;
7716                 default:
7717                         fprintf(stderr, "%s: option '%s' unrecognized\n",
7718                                 argv[0], argv[optind - 1]);
7719                         return CMD_HELP;
7720                 }
7721         }
7722
7723         if (advice_type == LU_LADVISE_INVALID) {
7724                 fprintf(stderr, "%s: please give an advice type\n", argv[0]);
7725                 fprintf(stderr, "Valid types:");
7726                 for (advice_type = 0; advice_type < ARRAY_SIZE(ladvise_names);
7727                      advice_type++) {
7728                         if (ladvise_names[advice_type] == NULL)
7729                                 continue;
7730                         fprintf(stderr, " %s", ladvise_names[advice_type]);
7731                 }
7732                 fprintf(stderr, "\n");
7733                 return CMD_HELP;
7734         }
7735
7736         if (advice_type == LU_LADVISE_LOCKNOEXPAND) {
7737                 fprintf(stderr, "%s: Lock no expand advice is a per file "
7738                                  "descriptor advice, so when called from lfs, "
7739                                  "it does nothing.\n", argv[0]);
7740                 return CMD_HELP;
7741         }
7742
7743         if (argc <= optind) {
7744                 fprintf(stderr, "%s: please give one or more file names\n",
7745                         argv[0]);
7746                 return CMD_HELP;
7747         }
7748
7749         if (end != LUSTRE_EOF && length != 0 && end != start + length) {
7750                 fprintf(stderr, "%s: conflicting arguments of -l and -e\n",
7751                         argv[0]);
7752                 return CMD_HELP;
7753         }
7754
7755         if (end == LUSTRE_EOF && length != 0)
7756                 end = start + length;
7757
7758         if (end <= start) {
7759                 fprintf(stderr, "%s: range [%llu, %llu] is invalid\n",
7760                         argv[0], start, end);
7761                 return CMD_HELP;
7762         }
7763
7764         if (advice_type != LU_LADVISE_LOCKAHEAD && mode != 0) {
7765                 fprintf(stderr, "%s: mode is only valid with lockahead\n",
7766                         argv[0]);
7767                 return CMD_HELP;
7768         }
7769
7770         if (advice_type == LU_LADVISE_LOCKAHEAD && mode == 0) {
7771                 fprintf(stderr, "%s: mode is required with lockahead\n",
7772                         argv[0]);
7773                 return CMD_HELP;
7774         }
7775
7776         while (optind < argc) {
7777                 int rc2;
7778
7779                 path = argv[optind++];
7780
7781                 fd = open(path, O_RDONLY);
7782                 if (fd < 0) {
7783                         fprintf(stderr, "%s: cannot open file '%s': %s\n",
7784                                 argv[0], path, strerror(errno));
7785                         rc2 = -errno;
7786                         goto next;
7787                 }
7788
7789                 advice.lla_start = start;
7790                 advice.lla_end = end;
7791                 advice.lla_advice = advice_type;
7792                 advice.lla_value1 = 0;
7793                 advice.lla_value2 = 0;
7794                 advice.lla_value3 = 0;
7795                 advice.lla_value4 = 0;
7796                 if (advice_type == LU_LADVISE_LOCKAHEAD) {
7797                         advice.lla_lockahead_mode = mode;
7798                         advice.lla_peradvice_flags = flags;
7799                 }
7800
7801                 rc2 = llapi_ladvise(fd, flags, 1, &advice);
7802                 close(fd);
7803                 if (rc2 < 0) {
7804                         fprintf(stderr, "%s: cannot give advice '%s' to file "
7805                                 "'%s': %s\n", argv[0],
7806                                 ladvise_names[advice_type],
7807                                 path, strerror(errno));
7808
7809                         goto next;
7810                 }
7811
7812 next:
7813                 if (rc == 0 && rc2 < 0)
7814                         rc = rc2;
7815         }
7816         return rc;
7817 }
7818
7819 /** The input string contains a comma delimited list of component ids and
7820  * ranges, for example "1,2-4,7".
7821  */
7822 static int parse_mirror_ids(__u16 *ids, int size, char *arg)
7823 {
7824         bool end_of_loop = false;
7825         char *ptr = NULL;
7826         int nr = 0;
7827         int rc;
7828
7829         if (arg == NULL)
7830                 return -EINVAL;
7831
7832         while (!end_of_loop) {
7833                 int start_index;
7834                 int end_index;
7835                 int i;
7836                 char *endptr = NULL;
7837
7838                 rc = -EINVAL;
7839                 ptr = strchrnul(arg, ',');
7840                 end_of_loop = *ptr == '\0';
7841                 *ptr = '\0';
7842
7843                 start_index = strtol(arg, &endptr, 0);
7844                 if (endptr == arg) /* no data at all */
7845                         break;
7846                 if (*endptr != '-' && *endptr != '\0') /* has invalid data */
7847                         break;
7848                 if (start_index < 0)
7849                         break;
7850
7851                 end_index = start_index;
7852                 if (*endptr == '-') {
7853                         end_index = strtol(endptr + 1, &endptr, 0);
7854                         if (*endptr != '\0')
7855                                 break;
7856                         if (end_index < start_index)
7857                                 break;
7858                 }
7859
7860                 for (i = start_index; i <= end_index && size > 0; i++) {
7861                         int j;
7862
7863                         /* remove duplicate */
7864                         for (j = 0; j < nr; j++) {
7865                                 if (ids[j] == i)
7866                                         break;
7867                         }
7868                         if (j == nr) { /* no duplicate */
7869                                 ids[nr++] = i;
7870                                 --size;
7871                         }
7872                 }
7873
7874                 if (size == 0 && i < end_index)
7875                         break;
7876
7877                 *ptr = ',';
7878                 arg = ++ptr;
7879                 rc = 0;
7880         }
7881         if (!end_of_loop && ptr != NULL)
7882                 *ptr = ',';
7883
7884         return rc < 0 ? rc : nr;
7885 }
7886
7887 /**
7888  * struct verify_mirror_id - Mirror id to be verified.
7889  * @mirror_id:   A specified mirror id.
7890  * @is_valid_id: @mirror_id is valid or not in the mirrored file.
7891  */
7892 struct verify_mirror_id {
7893         __u16 mirror_id;
7894         bool is_valid_id;
7895 };
7896
7897 /**
7898  * compare_mirror_ids() - Compare mirror ids.
7899  * @layout: Mirror component list.
7900  * @cbdata: Callback data in verify_mirror_id structure.
7901  *
7902  * This is a callback function called by llapi_layout_comp_iterate()
7903  * to compare the specified mirror id with the one in the current
7904  * component of @layout. If they are the same, then the specified
7905  * mirror id is valid.
7906  *
7907  * Return: a negative error code on failure or
7908  *         LLAPI_LAYOUT_ITER_CONT: Proceed iteration
7909  *         LLAPI_LAYOUT_ITER_STOP: Stop iteration
7910  */
7911 static inline
7912 int compare_mirror_ids(struct llapi_layout *layout, void *cbdata)
7913 {
7914         struct verify_mirror_id *mirror_id_cbdata =
7915                                  (struct verify_mirror_id *)cbdata;
7916         uint32_t mirror_id;
7917         int rc = 0;
7918
7919         rc = llapi_layout_mirror_id_get(layout, &mirror_id);
7920         if (rc < 0) {
7921                 rc = -errno;
7922                 fprintf(stderr,
7923                         "%s: llapi_layout_mirror_id_get failed: %s.\n",
7924                         progname, strerror(errno));
7925                 return rc;
7926         }
7927
7928         if (mirror_id_cbdata->mirror_id == mirror_id) {
7929                 mirror_id_cbdata->is_valid_id = true;
7930                 return LLAPI_LAYOUT_ITER_STOP;
7931         }
7932
7933         return LLAPI_LAYOUT_ITER_CONT;
7934 }
7935
7936 /**
7937  * verify_mirror_ids() - Verify specified mirror ids.
7938  * @fname:      Mirrored file name.
7939  * @mirror_ids: Specified mirror ids to be verified.
7940  * @ids_nr:     Number of specified mirror ids.
7941  *
7942  * This function verifies that specified @mirror_ids are valid
7943  * in the mirrored file @fname.
7944  *
7945  * Return: 0 on success or a negative error code on failure.
7946  */
7947 static inline
7948 int verify_mirror_ids(const char *fname, __u16 *mirror_ids, int ids_nr)
7949 {
7950         struct llapi_layout *layout = NULL;
7951         struct verify_mirror_id mirror_id_cbdata = { 0 };
7952         struct stat stbuf;
7953         uint32_t flr_state;
7954         int i;
7955         int fd;
7956         int rc = 0;
7957         int rc2 = 0;
7958
7959         if (ids_nr <= 0)
7960                 return -EINVAL;
7961
7962         if (stat(fname, &stbuf) < 0) {
7963                 fprintf(stderr, "%s: cannot stat file '%s': %s.\n",
7964                         progname, fname, strerror(errno));
7965                 rc = -errno;
7966                 goto error;
7967         }
7968
7969         if (!S_ISREG(stbuf.st_mode)) {
7970                 fprintf(stderr, "%s: '%s' is not a regular file.\n",
7971                         progname, fname);
7972                 rc = -EINVAL;
7973                 goto error;
7974         }
7975
7976         fd = open(fname, O_DIRECT | O_RDONLY);
7977         if (fd < 0) {
7978                 fprintf(stderr, "%s: cannot open '%s': %s.\n",
7979                         progname, fname, strerror(errno));
7980                 rc = -errno;
7981                 goto error;
7982         }
7983
7984         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
7985         if (rc < 0) {
7986                 fprintf(stderr, "%s: '%s' llapi_lease_acquire failed: %s.\n",
7987                         progname, fname, strerror(errno));
7988                 goto close_fd;
7989         }
7990
7991         layout = llapi_layout_get_by_fd(fd, 0);
7992         if (layout == NULL) {
7993                 fprintf(stderr, "%s: '%s' llapi_layout_get_by_fd failed: %s.\n",
7994                         progname, fname, strerror(errno));
7995                 rc = -errno;
7996                 llapi_lease_release(fd);
7997                 goto close_fd;
7998         }
7999
8000         rc = llapi_layout_flags_get(layout, &flr_state);
8001         if (rc < 0) {
8002                 fprintf(stderr, "%s: '%s' llapi_layout_flags_get failed: %s.\n",
8003                         progname, fname, strerror(errno));
8004                 rc = -errno;
8005                 goto free_layout;
8006         }
8007
8008         flr_state &= LCM_FL_FLR_MASK;
8009         switch (flr_state) {
8010         case LCM_FL_NONE:
8011                 rc = -EINVAL;
8012                 fprintf(stderr, "%s: '%s' file state error: %s.\n",
8013                         progname, fname, llapi_layout_flags_string(flr_state));
8014                 goto free_layout;
8015         default:
8016                 break;
8017         }
8018
8019         rc2 = 0;
8020         for (i = 0; i < ids_nr; i++) {
8021                 mirror_id_cbdata.mirror_id = mirror_ids[i];
8022                 mirror_id_cbdata.is_valid_id = false;
8023
8024                 rc = llapi_layout_comp_iterate(layout, compare_mirror_ids,
8025                                                &mirror_id_cbdata);
8026                 if (rc < 0) {
8027                         rc = -errno;
8028                         fprintf(stderr,
8029                                 "%s: '%s' failed to verify mirror id: %u.\n",
8030                                 progname, fname, mirror_ids[i]);
8031                         goto free_layout;
8032                 }
8033
8034                 if (!mirror_id_cbdata.is_valid_id) {
8035                         rc2 = -EINVAL;
8036                         fprintf(stderr,
8037                                 "%s: '%s' invalid specified mirror id: %u.\n",
8038                                 progname, fname, mirror_ids[i]);
8039                 }
8040         }
8041         rc = rc2;
8042
8043 free_layout:
8044         llapi_layout_free(layout);
8045         llapi_lease_release(fd);
8046 close_fd:
8047         close(fd);
8048 error:
8049         return rc;
8050 }
8051
8052 static inline
8053 int lfs_mirror_resync_file(const char *fname, struct ll_ioc_lease *ioc,
8054                            __u16 *mirror_ids, int ids_nr)
8055 {
8056         struct llapi_resync_comp comp_array[1024] = { { 0 } };
8057         struct llapi_layout *layout;
8058         struct stat stbuf;
8059         uint32_t flr_state;
8060         uint64_t start;
8061         uint64_t end;
8062         int comp_size = 0;
8063         int idx;
8064         int fd;
8065         int rc;
8066
8067         if (stat(fname, &stbuf) < 0) {
8068                 fprintf(stderr, "%s: cannot stat file '%s': %s.\n",
8069                         progname, fname, strerror(errno));
8070                 rc = -errno;
8071                 goto error;
8072         }
8073         if (!S_ISREG(stbuf.st_mode)) {
8074                 fprintf(stderr, "%s: '%s' is not a regular file.\n",
8075                         progname, fname);
8076                 rc = -EINVAL;
8077                 goto error;
8078         }
8079
8080         fd = open(fname, O_DIRECT | O_RDWR);
8081         if (fd < 0) {
8082                 fprintf(stderr, "%s: cannot open '%s': %s.\n",
8083                         progname, fname, strerror(errno));
8084                 rc = -errno;
8085                 goto error;
8086         }
8087
8088         layout = llapi_layout_get_by_fd(fd, 0);
8089         if (layout == NULL) {
8090                 fprintf(stderr, "%s: '%s' llapi_layout_get_by_fd failed: %s.\n",
8091                         progname, fname, strerror(errno));
8092                 rc = -errno;
8093                 goto close_fd;
8094         }
8095
8096         rc = llapi_layout_flags_get(layout, &flr_state);
8097         if (rc) {
8098                 fprintf(stderr, "%s: '%s' llapi_layout_flags_get failed: %s.\n",
8099                         progname, fname, strerror(errno));
8100                 rc = -errno;
8101                 goto free_layout;
8102         }
8103
8104         flr_state &= LCM_FL_FLR_MASK;
8105         if (flr_state == LCM_FL_NONE) {
8106                 rc = -EINVAL;
8107                 fprintf(stderr, "%s: '%s' is not a FLR file.\n",
8108                         progname, fname);
8109                 goto free_layout;
8110         }
8111
8112         /* get stale component info */
8113         comp_size = llapi_mirror_find_stale(layout, comp_array,
8114                                             ARRAY_SIZE(comp_array),
8115                                             mirror_ids, ids_nr);
8116         if (comp_size <= 0) {
8117                 rc = comp_size;
8118                 goto free_layout;
8119         }
8120
8121         ioc->lil_mode = LL_LEASE_WRLCK;
8122         ioc->lil_flags = LL_LEASE_RESYNC;
8123         rc = llapi_lease_set(fd, ioc);
8124         if (rc < 0) {
8125                 if (rc == -EALREADY)
8126                         rc = 0;
8127                 else
8128                         fprintf(stderr,
8129                             "%s: '%s' llapi_lease_get_ext resync failed: %s.\n",
8130                                 progname, fname, strerror(errno));
8131                 goto free_layout;
8132         }
8133
8134         /* get the read range [start, end) */
8135         start = comp_array[0].lrc_start;
8136         end = comp_array[0].lrc_end;
8137         for (idx = 1; idx < comp_size; idx++) {
8138                 if (comp_array[idx].lrc_start < start)
8139                         start = comp_array[idx].lrc_start;
8140                 if (end < comp_array[idx].lrc_end)
8141                         end = comp_array[idx].lrc_end;
8142         }
8143
8144         rc = llapi_lease_check(fd);
8145         if (rc != LL_LEASE_WRLCK) {
8146                 fprintf(stderr, "%s: '%s' lost lease lock.\n",
8147                         progname, fname);
8148                 goto free_layout;
8149         }
8150
8151         rc = llapi_mirror_resync_many(fd, layout, comp_array, comp_size,
8152                                       start, end);
8153         if (rc < 0)
8154                 fprintf(stderr, "%s: '%s' llapi_mirror_resync_many: %d.\n",
8155                         progname, fname, rc);
8156
8157         /* prepare ioc for lease put */
8158         ioc->lil_mode = LL_LEASE_UNLCK;
8159         ioc->lil_flags = LL_LEASE_RESYNC_DONE;
8160         ioc->lil_count = 0;
8161         for (idx = 0; idx < comp_size; idx++) {
8162                 if (comp_array[idx].lrc_synced) {
8163                         ioc->lil_ids[ioc->lil_count] = comp_array[idx].lrc_id;
8164                         ioc->lil_count++;
8165                 }
8166         }
8167
8168         rc = llapi_lease_set(fd, ioc);
8169         if (rc <= 0) {
8170                 if (rc == 0) /* lost lease lock */
8171                         rc = -EBUSY;
8172                 fprintf(stderr, "%s: resync file '%s' failed: %s.\n",
8173                         progname, fname, strerror(errno));
8174                 goto free_layout;
8175         }
8176         /**
8177          * llapi_lease_set returns lease mode when it request to unlock
8178          * the lease lock
8179          */
8180         rc = 0;
8181
8182 free_layout:
8183         llapi_layout_free(layout);
8184 close_fd:
8185         close(fd);
8186 error:
8187         return rc;
8188 }
8189
8190 static inline int lfs_mirror_resync(int argc, char **argv)
8191 {
8192         struct ll_ioc_lease *ioc = NULL;
8193         __u16 mirror_ids[128] = { 0 };
8194         int ids_nr = 0;
8195         int c;
8196         int rc = 0;
8197
8198         struct option long_opts[] = {
8199         { .val = 'o',   .name = "only",         .has_arg = required_argument },
8200         { .name = NULL } };
8201
8202         while ((c = getopt_long(argc, argv, "o:", long_opts, NULL)) >= 0) {
8203                 switch (c) {
8204                 case 'o':
8205                         rc = parse_mirror_ids(mirror_ids,
8206                                         sizeof(mirror_ids) / sizeof(__u16),
8207                                         optarg);
8208                         if (rc < 0) {
8209                                 fprintf(stderr,
8210                                         "%s: bad mirror ids '%s'.\n",
8211                                         argv[0], optarg);
8212                                 goto error;
8213                         }
8214                         ids_nr = rc;
8215                         break;
8216                 default:
8217                         fprintf(stderr, "%s: options '%s' unrecognized.\n",
8218                                 argv[0], argv[optind - 1]);
8219                         rc = -EINVAL;
8220                         goto error;
8221                 }
8222         }
8223
8224         if (argc == optind) {
8225                 fprintf(stderr, "%s: no file name given.\n", argv[0]);
8226                 rc = CMD_HELP;
8227                 goto error;
8228         }
8229
8230         if (ids_nr > 0 && argc > optind + 1) {
8231                 fprintf(stderr,
8232                     "%s: option '--only' cannot be used upon multiple files.\n",
8233                         argv[0]);
8234                 rc = CMD_HELP;
8235                 goto error;
8236
8237         }
8238
8239         if (ids_nr > 0) {
8240                 rc = verify_mirror_ids(argv[optind], mirror_ids, ids_nr);
8241                 if (rc < 0)
8242                         goto error;
8243         }
8244
8245         /* set the lease on the file */
8246         ioc = calloc(sizeof(*ioc) + sizeof(__u32) * 4096, 1);
8247         if (ioc == NULL) {
8248                 fprintf(stderr, "%s: cannot alloc id array for ioc: %s.\n",
8249                         argv[0], strerror(errno));
8250                 rc = -errno;
8251                 goto error;
8252         }
8253
8254         for (; optind < argc; optind++) {
8255                 rc = lfs_mirror_resync_file(argv[optind], ioc,
8256                                             mirror_ids, ids_nr);
8257                 /* ignore previous file's error, continue with next file */
8258
8259                 /* reset ioc */
8260                 memset(ioc, 0, sizeof(__u32) * 4096);
8261         }
8262
8263         free(ioc);
8264 error:
8265         return rc;
8266 }
8267
8268 static inline int lfs_mirror_dump(int argc, char **argv)
8269 {
8270         int rc = CMD_HELP;
8271         __u16 mirror_id = 0;
8272         const char *outfile = NULL;
8273         char *fname;
8274         struct stat stbuf;
8275         int fd = 0;
8276         struct llapi_layout *layout;
8277         int outfd;
8278         int c;
8279         const size_t buflen = 4 << 20;
8280         void *buf;
8281         off_t pos;
8282
8283         struct option long_opts[] = {
8284         { .val = 'N',   .name = "mirror-id",    .has_arg = required_argument },
8285         { .val = 'o',   .name = "outfile",      .has_arg = required_argument },
8286         { .name = NULL } };
8287
8288         while ((c = getopt_long(argc, argv, "N:o:", long_opts, NULL)) >= 0) {
8289                 char *end;
8290
8291                 switch (c) {
8292                 case 'N':
8293                         mirror_id = strtoul(optarg, &end, 0);
8294                         if (*end != '\0' || mirror_id == 0) {
8295                                 fprintf(stderr,
8296                                         "%s %s: invalid mirror ID '%s'\n",
8297                                         progname, argv[0], optarg);
8298                                 return rc;
8299                         }
8300                         break;
8301                 case 'o':
8302                         outfile = optarg;
8303                         break;
8304                 }
8305         }
8306
8307         if (argc == optind) {
8308                 fprintf(stderr, "%s %s: no mirrored file provided\n",
8309                         progname, argv[0]);
8310                 return rc;
8311         } else if (argc > optind + 1) {
8312                 fprintf(stderr, "%s %s: too many files\n", progname, argv[0]);
8313                 return rc;
8314         }
8315
8316         if (mirror_id == 0) {
8317                 fprintf(stderr, "%s %s: no valid mirror ID is provided\n",
8318                         progname, argv[0]);
8319                 return rc;
8320         }
8321
8322         /* open mirror file */
8323         fname = argv[optind];
8324
8325         if (stat(fname, &stbuf) < 0) {
8326                 fprintf(stderr, "%s %s: cannot stat file '%s': %s.\n",
8327                         progname, argv[0], fname, strerror(errno));
8328                 return rc;
8329         }
8330
8331         if (!S_ISREG(stbuf.st_mode)) {
8332                 fprintf(stderr, "%s %s: '%s' is not a regular file.\n",
8333                         progname, argv[0], fname);
8334                 return rc;
8335         }
8336
8337         fd = open(fname, O_DIRECT | O_RDONLY);
8338         if (fd < 0) {
8339                 fprintf(stderr, "%s %s: cannot open '%s': %s.\n",
8340                         progname, argv[0], fname, strerror(errno));
8341                 return rc;
8342         }
8343
8344         /* verify mirror id */
8345         layout = llapi_layout_get_by_fd(fd, 0);
8346         if (layout == NULL) {
8347                 fprintf(stderr, "%s %s: could not get layout of file '%s'.\n",
8348                         progname, argv[0], fname);
8349                 rc = -EINVAL;
8350                 goto close_fd;
8351         }
8352
8353         rc = llapi_layout_comp_iterate(layout, find_mirror_id, &mirror_id);
8354         if (rc < 0) {
8355                 fprintf(stderr, "%s %s: failed to iterate layout of '%s'.\n",
8356                         progname, argv[0], fname);
8357                 llapi_layout_free(layout);
8358                 goto close_fd;
8359         } else if (rc == LLAPI_LAYOUT_ITER_CONT) {
8360                 fprintf(stderr,
8361                         "%s %s: file '%s' does not contain mirror with ID %u\n",
8362                         progname, argv[0], fname, mirror_id);
8363                 llapi_layout_free(layout);
8364
8365                 rc = -EINVAL;
8366                 goto close_fd;
8367         }
8368         llapi_layout_free(layout);
8369
8370         /* open output file */
8371         if (outfile) {
8372                 outfd = open(outfile, O_EXCL | O_WRONLY | O_CREAT, 0644);
8373                 if (outfd < 0) {
8374                         fprintf(stderr, "%s %s: cannot create file '%s':%s.\n",
8375                                 progname, argv[0], outfile, strerror(errno));
8376                         rc = -errno;
8377                         goto close_fd;
8378                 }
8379         } else {
8380                 outfd = STDOUT_FILENO;
8381         }
8382
8383         /* allocate buffer */
8384         rc = posix_memalign(&buf, sysconf(_SC_PAGESIZE), buflen);
8385         if (rc) {
8386                 fprintf(stderr, "%s %s: posix_memalign returns %d.\n",
8387                                 progname, argv[0], rc);
8388                 goto close_outfd;
8389         }
8390
8391         pos = 0;
8392         while (1) {
8393                 ssize_t bytes_read;
8394                 ssize_t written = 0;
8395
8396                 bytes_read = llapi_mirror_read(fd, mirror_id, buf, buflen, pos);
8397                 if (bytes_read < 0) {
8398                         rc = bytes_read;
8399                         fprintf(stderr,
8400                                 "%s %s: fail to read data from mirror %u:%s.\n",
8401                                 progname, argv[0], mirror_id, strerror(-rc));
8402                         goto free_buf;
8403                 }
8404
8405                 /* EOF reached */
8406                 if (bytes_read == 0)
8407                         break;
8408
8409                 while (written < bytes_read) {
8410                         ssize_t written2;
8411
8412                         written2 = write(outfd, buf + written,
8413                                          bytes_read - written);
8414                         if (written2 < 0) {
8415                                 fprintf(stderr,
8416                                         "%s %s: fail to write %s:%s.\n",
8417                                         progname, argv[0], outfile ? : "STDOUT",
8418                                         strerror(errno));
8419                                 rc = -errno;
8420                                 goto free_buf;
8421                         }
8422                         written += written2;
8423                 }
8424
8425                 if (written != bytes_read) {
8426                         fprintf(stderr,
8427                 "%s %s: written %ld bytes does not match with %ld read.\n",
8428                                 progname, argv[0], written, bytes_read);
8429                         rc = -EIO;
8430                         goto free_buf;
8431                 }
8432
8433                 pos += bytes_read;
8434         }
8435
8436         fsync(outfd);
8437         rc = 0;
8438
8439 free_buf:
8440         free(buf);
8441 close_outfd:
8442         if (outfile)
8443                 close(outfd);
8444 close_fd:
8445         close(fd);
8446
8447         return rc;
8448 }
8449
8450 /**
8451  * struct verify_chunk - Mirror chunk to be verified.
8452  * @chunk:        [start, end) of the chunk.
8453  * @mirror_count: Number of mirror ids in @mirror_id array.
8454  * @mirror_id:    Array of valid mirror ids that cover the chunk.
8455  */
8456 struct verify_chunk {
8457         struct lu_extent chunk;
8458         unsigned int mirror_count;
8459         __u16 mirror_id[LUSTRE_MIRROR_COUNT_MAX];
8460 };
8461
8462 /**
8463  * print_chunks() - Print chunk information.
8464  * @fname:       Mirrored file name.
8465  * @chunks:      Array of chunks.
8466  * @chunk_count: Number of chunks in @chunks array.
8467  *
8468  * This function prints [start, end) of each chunk in @chunks
8469  * for mirrored file @fname, and also prints the valid mirror ids
8470  * that cover the chunk.
8471  *
8472  * Return: void.
8473  */
8474 static inline
8475 void print_chunks(const char *fname, struct verify_chunk *chunks,
8476                   int chunk_count)
8477 {
8478         int i;
8479         int j;
8480
8481         fprintf(stdout, "Chunks to be verified in %s:\n", fname);
8482         for (i = 0; i < chunk_count; i++) {
8483                 fprintf(stdout, DEXT, PEXT(&chunks[i].chunk));
8484
8485                 if (chunks[i].mirror_count == 0)
8486                         fprintf(stdout, "\t[");
8487                 else {
8488                         fprintf(stdout, "\t[%u", chunks[i].mirror_id[0]);
8489                         for (j = 1; j < chunks[i].mirror_count; j++)
8490                                 fprintf(stdout, ", %u", chunks[i].mirror_id[j]);
8491                 }
8492                 fprintf(stdout, "]\t%u\n", chunks[i].mirror_count);
8493         }
8494         fprintf(stdout, "\n");
8495 }
8496
8497 /**
8498  * print_checksums() - Print CRC-32 checksum values.
8499  * @chunk: A chunk and its corresponding valid mirror ids.
8500  * @crc:   CRC-32 checksum values on the chunk for each valid mirror.
8501  *
8502  * This function prints CRC-32 checksum values on @chunk for
8503  * each valid mirror that covers it.
8504  *
8505  * Return: void.
8506  */
8507 static inline
8508 void print_checksums(struct verify_chunk *chunk, unsigned long *crc)
8509 {
8510         int i;
8511
8512         fprintf(stdout,
8513                 "CRC-32 checksum value for chunk "DEXT":\n",
8514                 PEXT(&chunk->chunk));
8515         for (i = 0; i < chunk->mirror_count; i++)
8516                 fprintf(stdout, "Mirror %u:\t%#lx\n",
8517                         chunk->mirror_id[i], crc[i]);
8518         fprintf(stdout, "\n");
8519 }
8520
8521 /**
8522  * filter_mirror_id() - Filter specified mirror ids.
8523  * @chunks:      Array of chunks.
8524  * @chunk_count: Number of chunks in @chunks array.
8525  * @mirror_ids:  Specified mirror ids to be verified.
8526  * @ids_nr:      Number of specified mirror ids.
8527  *
8528  * This function scans valid mirror ids that cover each chunk in @chunks
8529  * and filters specified mirror ids.
8530  *
8531  * Return: void.
8532  */
8533 static inline
8534 void filter_mirror_id(struct verify_chunk *chunks, int chunk_count,
8535                       __u16 *mirror_ids, int ids_nr)
8536 {
8537         int i;
8538         int j;
8539         int k;
8540         __u16 valid_id[LUSTRE_MIRROR_COUNT_MAX] = { 0 };
8541         unsigned int valid_count = 0;
8542
8543         for (i = 0; i < chunk_count; i++) {
8544                 if (chunks[i].mirror_count == 0)
8545                         continue;
8546
8547                 valid_count = 0;
8548                 for (j = 0; j < ids_nr; j++) {
8549                         for (k = 0; k < chunks[i].mirror_count; k++) {
8550                                 if (chunks[i].mirror_id[k] == mirror_ids[j]) {
8551                                         valid_id[valid_count] = mirror_ids[j];
8552                                         valid_count++;
8553                                         break;
8554                                 }
8555                         }
8556                 }
8557
8558                 memcpy(chunks[i].mirror_id, valid_id,
8559                        sizeof(__u16) * valid_count);
8560                 chunks[i].mirror_count = valid_count;
8561         }
8562 }
8563
8564 /**
8565  * lfs_mirror_prepare_chunk() - Find mirror chunks to be verified.
8566  * @layout:      Mirror component list.
8567  * @chunks:      Array of chunks.
8568  * @chunks_size: Array size of @chunks.
8569  *
8570  * This function scans the components in @layout from offset 0 to LUSTRE_EOF
8571  * to find out chunk segments and store them in @chunks array.
8572  *
8573  * The @mirror_id array in each element of @chunks will store the valid
8574  * mirror ids that cover the chunk. If a mirror component covering the
8575  * chunk has LCME_FL_STALE or LCME_FL_OFFLINE flag, then the mirror id
8576  * will not be stored into the @mirror_id array, and the chunk for that
8577  * mirror will not be verified.
8578  *
8579  * The @mirror_count in each element of @chunks will store the number of
8580  * mirror ids in @mirror_id array. If @mirror_count is 0, it indicates the
8581  * chunk is invalid in all of the mirrors. And if @mirror_count is 1, it
8582  * indicates the chunk is valid in only one mirror. In both cases, the
8583  * chunk will not be verified.
8584  *
8585  * Here is an example:
8586  *
8587  *  0      1M     2M     3M     4M           EOF
8588  *  +------+-------------+--------------------+
8589  *  |      |             |      S             |       mirror1
8590  *  +------+------+------+------+-------------+
8591  *  |             |   S  |   S  |             |       mirror2
8592  *  +-------------+------+------+-------------+
8593  *
8594  * prepared @chunks array will contain 5 elements:
8595  * (([0, 1M), [1, 2], 2),
8596  *  ([1M, 2M), [1, 2], 2),
8597  *  ([2M, 3M), [1], 1),
8598  *  ([3M, 4M], [], 0),
8599  *  ([4M, EOF), [2], 1))
8600  *
8601  * Return: the actual array size of @chunks on success
8602  *         or a negative error code on failure.
8603  */
8604 static inline
8605 int lfs_mirror_prepare_chunk(struct llapi_layout *layout,
8606                              struct verify_chunk *chunks,
8607                              size_t chunks_size)
8608 {
8609         uint64_t start;
8610         uint64_t end;
8611         uint32_t mirror_id;
8612         uint32_t flags;
8613         int idx = 0;
8614         int i = 0;
8615         int rc = 0;
8616
8617         memset(chunks, 0, sizeof(*chunks) * chunks_size);
8618
8619         while (1) {
8620                 rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_FIRST);
8621                 if (rc < 0) {
8622                         fprintf(stderr,
8623                                 "%s: move to the first layout component: %s.\n",
8624                                 progname, strerror(errno));
8625                         goto error;
8626                 }
8627
8628                 i = 0;
8629                 rc = 0;
8630                 chunks[idx].chunk.e_end = LUSTRE_EOF;
8631                 while (rc == 0) {
8632                         rc = llapi_layout_comp_extent_get(layout, &start, &end);
8633                         if (rc < 0) {
8634                                 fprintf(stderr,
8635                                         "%s: llapi_layout_comp_extent_get failed: %s.\n",
8636                                         progname, strerror(errno));
8637                                 goto error;
8638                         }
8639
8640                         if (start > chunks[idx].chunk.e_start ||
8641                             end <= chunks[idx].chunk.e_start)
8642                                 goto next;
8643
8644                         if (end < chunks[idx].chunk.e_end)
8645                                 chunks[idx].chunk.e_end = end;
8646
8647                         rc = llapi_layout_comp_flags_get(layout, &flags);
8648                         if (rc < 0) {
8649                                 fprintf(stderr,
8650                                         "%s: llapi_layout_comp_flags_get failed: %s.\n",
8651                                         progname, strerror(errno));
8652                                 goto error;
8653                         }
8654
8655                         if (flags & LCME_FL_STALE || flags & LCME_FL_OFFLINE)
8656                                 goto next;
8657
8658                         rc = llapi_layout_mirror_id_get(layout, &mirror_id);
8659                         if (rc < 0) {
8660                                 fprintf(stderr,
8661                                         "%s: llapi_layout_mirror_id_get failed: %s.\n",
8662                                         progname, strerror(errno));
8663                                 goto error;
8664                         }
8665
8666                         chunks[idx].mirror_id[i] = mirror_id;
8667                         i++;
8668                         if (i >= ARRAY_SIZE(chunks[idx].mirror_id)) {
8669                                 fprintf(stderr,
8670                                         "%s: mirror_id array is too small.\n",
8671                                         progname);
8672                                 rc = -EINVAL;
8673                                 goto error;
8674                         }
8675
8676                 next:
8677                         rc = llapi_layout_comp_use(layout,
8678                                                    LLAPI_LAYOUT_COMP_USE_NEXT);
8679                         if (rc < 0) {
8680                                 fprintf(stderr,
8681                                         "%s: move to the next layout component: %s.\n",
8682                                         progname, strerror(errno));
8683                                 goto error;
8684                         }
8685                 } /* loop through all components */
8686
8687                 chunks[idx].mirror_count = i;
8688
8689                 if (chunks[idx].chunk.e_end == LUSTRE_EOF)
8690                         break;
8691
8692                 idx++;
8693                 if (idx >= chunks_size) {
8694                         fprintf(stderr, "%s: chunks array is too small.\n",
8695                                 progname);
8696                         rc = -EINVAL;
8697                         goto error;
8698                 }
8699
8700                 chunks[idx].chunk.e_start = chunks[idx - 1].chunk.e_end;
8701         }
8702
8703 error:
8704         return rc < 0 ? rc : idx + 1;
8705 }
8706
8707 /**
8708  * lfs_mirror_verify_chunk() - Verify a chunk.
8709  * @fd:        File descriptor of the mirrored file.
8710  * @file_size: Size of the mirrored file.
8711  * @chunk:     A chunk and its corresponding valid mirror ids.
8712  * @verbose:   Verbose mode.
8713  *
8714  * This function verifies a @chunk contains exactly the same data
8715  * ammong the mirrors that cover it.
8716  *
8717  * If @verbose is specified, then the function will print where the
8718  * differences are if the data do not match. Otherwise, it will
8719  * just return an error in that case.
8720  *
8721  * Return: 0 on success or a negative error code on failure.
8722  */
8723 static inline
8724 int lfs_mirror_verify_chunk(int fd, size_t file_size,
8725                             struct verify_chunk *chunk, int verbose)
8726 {
8727         const size_t buflen = 4 * 1024 * 1024; /* 4M */
8728         void *buf;
8729         size_t page_size = sysconf(_SC_PAGESIZE);
8730         ssize_t bytes_read;
8731         ssize_t bytes_done;
8732         size_t count;
8733         off_t pos;
8734         unsigned long crc;
8735         unsigned long crc_array[LUSTRE_MIRROR_COUNT_MAX] = { 0 };
8736         int i;
8737         int rc = 0;
8738
8739         if (file_size == 0)
8740                 return 0;
8741
8742         rc = posix_memalign(&buf, page_size, buflen);
8743         if (rc) /* error code is returned directly */
8744                 return -rc;
8745
8746         if (verbose > 1) {
8747                 fprintf(stdout, "Verifying chunk "DEXT" on mirror:",
8748                         PEXT(&chunk->chunk));
8749                 for (i = 0; i < chunk->mirror_count; i++)
8750                         fprintf(stdout, " %u", chunk->mirror_id[i]);
8751                 fprintf(stdout, "\n");
8752         }
8753
8754         bytes_done = 0;
8755         count = MIN(chunk->chunk.e_end, file_size) - chunk->chunk.e_start;
8756         pos = chunk->chunk.e_start;
8757         while (bytes_done < count) {
8758                 /* compute initial CRC-32 checksum */
8759                 crc = crc32(0L, Z_NULL, 0);
8760                 memset(crc_array, 0, sizeof(crc_array));
8761
8762                 bytes_read = 0;
8763                 for (i = 0; i < chunk->mirror_count; i++) {
8764                         bytes_read = llapi_mirror_read(fd, chunk->mirror_id[i],
8765                                                        buf, buflen, pos);
8766                         if (bytes_read < 0) {
8767                                 rc = bytes_read;
8768                                 fprintf(stderr,
8769                                         "%s: failed to read data from mirror %u: %s.\n",
8770                                         progname, chunk->mirror_id[i],
8771                                         strerror(-rc));
8772                                 goto error;
8773                         }
8774
8775                         /* compute new CRC-32 checksum */
8776                         crc_array[i] = crc32(crc, buf, bytes_read);
8777                 }
8778
8779                 if (verbose)
8780                         print_checksums(chunk, crc_array);
8781
8782                 /* compare CRC-32 checksum values */
8783                 for (i = 1; i < chunk->mirror_count; i++) {
8784                         if (crc_array[i] != crc_array[0]) {
8785                                 rc = -EINVAL;
8786                                 if (!verbose)
8787                                         goto error;
8788
8789                                 fprintf(stderr,
8790                                         "%s: chunk "DEXT" has different checksum value on mirror %u and mirror %u.\n",
8791                                         progname, PEXT(&chunk->chunk),
8792                                         chunk->mirror_id[0],
8793                                         chunk->mirror_id[i]);
8794                         }
8795                 }
8796
8797                 pos += bytes_read;
8798                 bytes_done += bytes_read;
8799         }
8800
8801         if (verbose > 1 && rc == 0) {
8802                 fprintf(stdout, "Verifying chunk "DEXT" on mirror:",
8803                         PEXT(&chunk->chunk));
8804                 for (i = 0; i < chunk->mirror_count; i++)
8805                         fprintf(stdout, " %u", chunk->mirror_id[i]);
8806                 fprintf(stdout, " PASS\n\n");
8807         }
8808
8809 error:
8810         free(buf);
8811         return rc;
8812 }
8813
8814 /**
8815  * lfs_mirror_verify_file() - Verify a mirrored file.
8816  * @fname:      Mirrored file name.
8817  * @mirror_ids: Specified mirror ids to be verified.
8818  * @ids_nr:     Number of specified mirror ids.
8819  * @verbose:    Verbose mode.
8820  *
8821  * This function verifies that each SYNC mirror of a mirrored file
8822  * specified by @fname contains exactly the same data.
8823  *
8824  * If @mirror_ids is specified, then the function will verify the
8825  * mirrors specified by @mirror_ids contain exactly the same data.
8826  *
8827  * If @verbose is specified, then the function will print where the
8828  * differences are if the data do not match. Otherwise, it will
8829  * just return an error in that case.
8830  *
8831  * Return: 0 on success or a negative error code on failure.
8832  */
8833 static inline
8834 int lfs_mirror_verify_file(const char *fname, __u16 *mirror_ids, int ids_nr,
8835                            int verbose)
8836 {
8837         struct verify_chunk chunks_array[1024] = { };
8838         struct llapi_layout *layout = NULL;
8839         struct stat stbuf;
8840         uint32_t flr_state;
8841         int fd;
8842         int chunk_count = 0;
8843         int idx = 0;
8844         int rc = 0;
8845         int rc1 = 0;
8846         int rc2 = 0;
8847
8848         if (stat(fname, &stbuf) < 0) {
8849                 fprintf(stderr, "%s: cannot stat file '%s': %s.\n",
8850                         progname, fname, strerror(errno));
8851                 rc = -errno;
8852                 goto error;
8853         }
8854
8855         if (!S_ISREG(stbuf.st_mode)) {
8856                 fprintf(stderr, "%s: '%s' is not a regular file.\n",
8857                         progname, fname);
8858                 rc = -EINVAL;
8859                 goto error;
8860         }
8861
8862         if (stbuf.st_size == 0) {
8863                 if (verbose)
8864                         fprintf(stdout, "%s: '%s' file size is 0.\n",
8865                                 progname, fname);
8866                 rc = 0;
8867                 goto error;
8868         }
8869
8870         fd = open(fname, O_DIRECT | O_RDONLY);
8871         if (fd < 0) {
8872                 fprintf(stderr, "%s: cannot open '%s': %s.\n",
8873                         progname, fname, strerror(errno));
8874                 rc = -errno;
8875                 goto error;
8876         }
8877
8878         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
8879         if (rc < 0) {
8880                 fprintf(stderr, "%s: '%s' llapi_lease_acquire failed: %s.\n",
8881                         progname, fname, strerror(errno));
8882                 goto close_fd;
8883         }
8884
8885         layout = llapi_layout_get_by_fd(fd, 0);
8886         if (layout == NULL) {
8887                 fprintf(stderr, "%s: '%s' llapi_layout_get_by_fd failed: %s.\n",
8888                         progname, fname, strerror(errno));
8889                 rc = -errno;
8890                 llapi_lease_release(fd);
8891                 goto close_fd;
8892         }
8893
8894         rc = llapi_layout_flags_get(layout, &flr_state);
8895         if (rc < 0) {
8896                 fprintf(stderr, "%s: '%s' llapi_layout_flags_get failed: %s.\n",
8897                         progname, fname, strerror(errno));
8898                 rc = -errno;
8899                 goto free_layout;
8900         }
8901
8902         flr_state &= LCM_FL_FLR_MASK;
8903         switch (flr_state) {
8904         case LCM_FL_NONE:
8905                 rc = -EINVAL;
8906                 fprintf(stderr, "%s: '%s' file state error: %s.\n",
8907                         progname, fname, llapi_layout_flags_string(flr_state));
8908                 goto free_layout;
8909         default:
8910                 break;
8911         }
8912
8913         /* find out mirror chunks to be verified */
8914         chunk_count = lfs_mirror_prepare_chunk(layout, chunks_array,
8915                                                ARRAY_SIZE(chunks_array));
8916         if (chunk_count < 0) {
8917                 rc = chunk_count;
8918                 goto free_layout;
8919         }
8920
8921         if (ids_nr > 0)
8922                 /* filter specified mirror ids */
8923                 filter_mirror_id(chunks_array, chunk_count, mirror_ids, ids_nr);
8924
8925         if (verbose > 2)
8926                 print_chunks(fname, chunks_array, chunk_count);
8927
8928         for (idx = 0; idx < chunk_count; idx++) {
8929                 if (chunks_array[idx].chunk.e_start >= stbuf.st_size) {
8930                         if (verbose)
8931                                 fprintf(stdout,
8932                                         "%s: '%s' chunk "DEXT" exceeds file size %#llx: skipped\n",
8933                                         progname, fname,
8934                                         PEXT(&chunks_array[idx].chunk),
8935                                         (unsigned long long)stbuf.st_size);
8936                         break;
8937                 }
8938
8939                 if (chunks_array[idx].mirror_count == 0) {
8940                         fprintf(stderr,
8941                                 "%s: '%s' chunk "DEXT" is invalid in all of the mirrors: ",
8942                                 progname, fname,
8943                                 PEXT(&chunks_array[idx].chunk));
8944                         if (verbose) {
8945                                 fprintf(stderr, "skipped\n");
8946                                 continue;
8947                         }
8948                         rc = -EINVAL;
8949                         fprintf(stderr, "failed\n");
8950                         goto free_layout;
8951                 }
8952
8953                 if (chunks_array[idx].mirror_count == 1) {
8954                         if (verbose)
8955                                 fprintf(stdout,
8956                                         "%s: '%s' chunk "DEXT" is only valid in mirror %u: skipped\n",
8957                                         progname, fname,
8958                                         PEXT(&chunks_array[idx].chunk),
8959                                         chunks_array[idx].mirror_id[0]);
8960                         continue;
8961                 }
8962
8963                 rc = llapi_lease_check(fd);
8964                 if (rc != LL_LEASE_RDLCK) {
8965                         fprintf(stderr, "%s: '%s' lost lease lock.\n",
8966                                 progname, fname);
8967                         goto free_layout;
8968                 }
8969
8970                 /* verify one chunk */
8971                 rc1 = lfs_mirror_verify_chunk(fd, stbuf.st_size,
8972                                               &chunks_array[idx], verbose);
8973                 if (rc1 < 0) {
8974                         rc2 = rc1;
8975                         if (!verbose) {
8976                                 rc = rc1;
8977                                 goto free_layout;
8978                         }
8979                 }
8980         }
8981
8982         if (rc2 < 0)
8983                 rc = rc2;
8984
8985 free_layout:
8986         llapi_layout_free(layout);
8987         llapi_lease_release(fd);
8988 close_fd:
8989         close(fd);
8990 error:
8991         return rc;
8992 }
8993
8994 /**
8995  * lfs_mirror_verify() - Parse and execute lfs mirror verify command.
8996  * @argc: The count of lfs mirror verify command line arguments.
8997  * @argv: Array of strings for lfs mirror verify command line arguments.
8998  *
8999  * This function parses lfs mirror verify command and verifies the
9000  * specified mirrored file(s).
9001  *
9002  * Return: 0 on success or a negative error code on failure.
9003  */
9004 static inline int lfs_mirror_verify(int argc, char **argv)
9005 {
9006         __u16 mirror_ids[LUSTRE_MIRROR_COUNT_MAX] = { 0 };
9007         int ids_nr = 0;
9008         int c;
9009         int verbose = 0;
9010         int rc = 0;
9011         int rc1 = 0;
9012         char cmd[PATH_MAX];
9013
9014         struct option long_opts[] = {
9015         { .val = 'o',   .name = "only",         .has_arg = required_argument },
9016         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
9017         { .name = NULL } };
9018
9019         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
9020         progname = cmd;
9021         while ((c = getopt_long(argc, argv, "o:v", long_opts, NULL)) >= 0) {
9022                 switch (c) {
9023                 case 'o':
9024                         rc = parse_mirror_ids(mirror_ids,
9025                                               ARRAY_SIZE(mirror_ids),
9026                                               optarg);
9027                         if (rc < 0) {
9028                                 fprintf(stderr,
9029                                         "%s: bad mirror ids '%s'.\n",
9030                                         progname, optarg);
9031                                 goto error;
9032                         }
9033                         ids_nr = rc;
9034                         if (ids_nr < 2) {
9035                                 fprintf(stderr,
9036                                         "%s: at least 2 mirror ids needed with '--only' option.\n",
9037                                         progname);
9038                                 rc = CMD_HELP;
9039                                 goto error;
9040                         }
9041                         break;
9042                 case 'v':
9043                         verbose++;
9044                         break;
9045                 default:
9046                         fprintf(stderr, "%s: options '%s' unrecognized.\n",
9047                                 progname, argv[optind - 1]);
9048                         rc = -EINVAL;
9049                         goto error;
9050                 }
9051         }
9052
9053         if (argc == optind) {
9054                 fprintf(stderr, "%s: no file name given.\n", progname);
9055                 rc = CMD_HELP;
9056                 goto error;
9057         }
9058
9059         if (ids_nr > 0 && argc > optind + 1) {
9060                 fprintf(stderr,
9061                         "%s: '--only' cannot be used upon multiple files.\n",
9062                         progname);
9063                 rc = CMD_HELP;
9064                 goto error;
9065
9066         }
9067
9068         if (ids_nr > 0) {
9069                 rc = verify_mirror_ids(argv[optind], mirror_ids, ids_nr);
9070                 if (rc < 0)
9071                         goto error;
9072         }
9073
9074         rc = 0;
9075         for (; optind < argc; optind++) {
9076                 rc1 = lfs_mirror_verify_file(argv[optind], mirror_ids, ids_nr,
9077                                              verbose);
9078                 if (rc1 < 0)
9079                         rc = rc1;
9080         }
9081 error:
9082         return rc;
9083 }
9084
9085 /**
9086  * lfs_mirror() - Parse and execute lfs mirror commands.
9087  * @argc: The count of lfs mirror command line arguments.
9088  * @argv: Array of strings for lfs mirror command line arguments.
9089  *
9090  * This function parses lfs mirror commands and performs the
9091  * corresponding functions specified in mirror_cmdlist[].
9092  *
9093  * Return: 0 on success or an error code on failure.
9094  */
9095 static int lfs_mirror(int argc, char **argv)
9096 {
9097         char cmd[PATH_MAX];
9098         int rc = 0;
9099
9100         setlinebuf(stdout);
9101
9102         Parser_init("lfs-mirror > ", mirror_cmdlist);
9103
9104         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
9105         progname = cmd;
9106         program_invocation_short_name = cmd;
9107         if (argc > 1)
9108                 rc = Parser_execarg(argc - 1, argv + 1, mirror_cmdlist);
9109         else
9110                 rc = Parser_commands();
9111
9112         return rc < 0 ? -rc : rc;
9113 }
9114
9115 static void lustre_som_swab(struct lustre_som_attrs *attrs)
9116 {
9117 #if __BYTE_ORDER == __BIG_ENDIAN
9118         __swab16s(&attrs->lsa_valid);
9119         __swab64s(&attrs->lsa_size);
9120         __swab64s(&attrs->lsa_blocks);
9121 #endif
9122 }
9123
9124 enum lfs_som_type {
9125         LFS_SOM_SIZE = 0x1,
9126         LFS_SOM_BLOCKS = 0x2,
9127         LFS_SOM_FLAGS = 0x4,
9128         LFS_SOM_ATTR_ALL = LFS_SOM_SIZE | LFS_SOM_BLOCKS |
9129                            LFS_SOM_FLAGS,
9130 };
9131
9132 static int lfs_getsom(int argc, char **argv)
9133 {
9134         const char *path;
9135         struct lustre_som_attrs *attrs;
9136         char buf[sizeof(*attrs) + 64];
9137         enum lfs_som_type type = LFS_SOM_ATTR_ALL;
9138         int rc = 0, c;
9139
9140         while ((c = getopt(argc, argv, "sbf")) != -1) {
9141                 switch (c) {
9142                 case 's':
9143                         type = LFS_SOM_SIZE;
9144                         break;
9145                 case 'b':
9146                         type = LFS_SOM_BLOCKS;
9147                         break;
9148                 case 'f':
9149                         type = LFS_SOM_FLAGS;
9150                         break;
9151                 default:
9152                         fprintf(stderr, "%s: invalid option '%c'\n",
9153                                 progname, optopt);
9154                         return CMD_HELP;
9155                 }
9156         }
9157
9158         argc -= optind;
9159         argv += optind;
9160
9161         if (argc != 1) {
9162                 fprintf(stderr, "%s: %s\n",
9163                         progname, argc == 0 ? "miss file target" :
9164                         "input more than 2 files");
9165                 return CMD_HELP;
9166         }
9167
9168         path = argv[0];
9169         attrs = (void *)buf;
9170         rc = lgetxattr(path, "trusted.som", attrs, sizeof(buf));
9171         if (rc < 0) {
9172                 fprintf(stderr, "%s failed to get som xattr: %s\n", argv[0],
9173                         strerror(-rc));
9174                 return rc;
9175         }
9176
9177         lustre_som_swab(attrs);
9178
9179         switch (type) {
9180         case LFS_SOM_ATTR_ALL:
9181                 printf("file: %s size: %llu blocks: %llu flags: %x\n",
9182                        path, attrs->lsa_size, attrs->lsa_blocks,
9183                        attrs->lsa_valid);
9184                 break;
9185         case LFS_SOM_SIZE:
9186                 printf("%llu\n", attrs->lsa_size);
9187                 break;
9188         case LFS_SOM_BLOCKS:
9189                 printf("%llu\n", attrs->lsa_blocks);
9190                 break;
9191         case LFS_SOM_FLAGS:
9192                 printf("%x\n", attrs->lsa_valid);
9193                 break;
9194         default:
9195                 fprintf(stderr, "%s: unknown option\n", progname);
9196                 return CMD_HELP;
9197         }
9198
9199         return rc;
9200 }
9201
9202 /**
9203  * lfs_mirror_list_commands() - List lfs mirror commands.
9204  * @argc: The count of command line arguments.
9205  * @argv: Array of strings for command line arguments.
9206  *
9207  * This function lists lfs mirror commands defined in mirror_cmdlist[].
9208  *
9209  * Return: 0 on success.
9210  */
9211 static int lfs_mirror_list_commands(int argc, char **argv)
9212 {
9213         char buffer[81] = "";
9214
9215         Parser_list_commands(mirror_cmdlist, buffer, sizeof(buffer),
9216                              NULL, 0, 4);
9217
9218         return 0;
9219 }
9220
9221 static int lfs_list_commands(int argc, char **argv)
9222 {
9223         char buffer[81] = ""; /* 80 printable chars + terminating NUL */
9224
9225         Parser_list_commands(cmdlist, buffer, sizeof(buffer), NULL, 0, 4);
9226
9227         return 0;
9228 }
9229
9230 int main(int argc, char **argv)
9231 {
9232         int rc;
9233
9234         /* Ensure that liblustreapi constructor has run */
9235         if (!llapi_liblustreapi_initialized())
9236                 fprintf(stderr, "liblustreapi was not properly initialized\n");
9237
9238         setlinebuf(stdout);
9239         opterr = 0;
9240
9241         Parser_init("lfs > ", cmdlist);
9242
9243         progname = program_invocation_short_name; /* Used in error messages */
9244         if (argc > 1) {
9245                 llapi_set_command_name(argv[1]);
9246                 rc = Parser_execarg(argc - 1, argv + 1, cmdlist);
9247                 llapi_clear_command_name();
9248         } else {
9249                 rc = Parser_commands();
9250         }
9251
9252         return rc < 0 ? -rc : rc;
9253 }
9254
9255 #ifdef _LUSTRE_IDL_H_
9256 /* Everything we need here should be included by lustreapi.h. */
9257 # error "lfs should not depend on lustre_idl.h"
9258 #endif /* _LUSTRE_IDL_H_ */