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