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