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