Whamcloud - gitweb
123afede60b9090a29696d4874115be440de5313
[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_nr_tgts = parse_targets(mdts,
5328                                                 sizeof(mdts) / sizeof(__u32),
5329                                                 lsa.lsa_nr_tgts, optarg, NULL);
5330                         if (lsa.lsa_nr_tgts < 0) {
5331                                 fprintf(stderr,
5332                                         "%s %s: invalid MDT target(s) '%s'\n",
5333                                         progname, argv[0], optarg);
5334                                 return CMD_HELP;
5335                         }
5336
5337                         lsa.lsa_tgts = mdts;
5338                         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
5339                                 lsa.lsa_stripe_off = mdts[0];
5340                         break;
5341 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 15, 53, 0)
5342                 case 'm':
5343                         fprintf(stderr, "warning: '-m' is deprecated, "
5344                                 "use '--mode' or '-o' instead\n");
5345 #endif
5346                 case 'o':
5347                         mode_opt = optarg;
5348                         break;
5349                 case 'x':
5350                         xattr = optarg;
5351                         break;
5352                 default:
5353                         fprintf(stderr, "%s %s: unrecognized option '%s'\n",
5354                                 progname, argv[0], argv[optind - 1]);
5355                         return CMD_HELP;
5356                 }
5357         }
5358
5359         if (optind == argc) {
5360                 fprintf(stderr, "%s %s: DIR must be specified\n",
5361                         progname, argv[0]);
5362                 return CMD_HELP;
5363         }
5364
5365         if (xattr && !foreign_mode) {
5366                 /* only print a warning as this is armless and will be
5367                  * ignored
5368                  */
5369                 fprintf(stderr,
5370                         "%s %s: xattr has been specified for non-foreign layout\n",
5371                         progname, argv[0]);
5372         } else if (foreign_mode && !xattr) {
5373                 fprintf(stderr,
5374                         "%s %s: xattr must be provided in foreign mode\n",
5375                         progname, argv[0]);
5376                 return CMD_HELP;
5377         }
5378
5379         if (foreign_mode && (delete || default_stripe || lsa.lsa_nr_tgts ||
5380             lsa.lsa_tgts || setstripe_args_specified(&lsa))) {
5381                 fprintf(stderr,
5382                         "%s %s: only --xattr/--flags/--mode options are valid with --foreign\n",
5383                         progname, argv[0]);
5384                 return CMD_HELP;
5385         }
5386
5387         if (!delete && lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT &&
5388             lsa.lsa_stripe_count == LLAPI_LAYOUT_DEFAULT && !foreign_mode) {
5389                 fprintf(stderr,
5390                         "%s %s: stripe offset and count must be specified\n",
5391                         progname, argv[0]);
5392                 return CMD_HELP;
5393         }
5394
5395         if (delete &&
5396             (lsa.lsa_stripe_off != LLAPI_LAYOUT_DEFAULT ||
5397              lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT)) {
5398                 fprintf(stderr,
5399                         "%s %s: cannot specify -d with -c or -i options\n",
5400                         progname, argv[0]);
5401                 return CMD_HELP;
5402         }
5403
5404         if (mode_opt != NULL) {
5405                 mode = strtoul(mode_opt, &end, 8);
5406                 if (*end != '\0') {
5407                         fprintf(stderr,
5408                                 "%s %s: bad MODE '%s'\n",
5409                                 progname, argv[0], mode_opt);
5410                         return CMD_HELP;
5411                 }
5412                 previous_mode = umask(0);
5413         }
5414
5415         /* foreign LMV/dir case */
5416         if (foreign_mode) {
5417                 if (argc > optind + 1) {
5418                         fprintf(stderr,
5419                                 "%s %s: cannot specify multiple foreign dirs\n",
5420                                 progname, argv[0]);
5421                         return CMD_HELP;
5422                 }
5423
5424                 dname = argv[optind];
5425                 result = llapi_dir_create_foreign(dname, mode, type, flags,
5426                                                   xattr);
5427                 if (result != 0)
5428                         fprintf(stderr,
5429                                 "%s mkdir: can't create foreign dir '%s': %s\n",
5430                                 progname, dname, strerror(-result));
5431                 return result;
5432         }
5433
5434         /*
5435          * initialize stripe parameters, in case param is converted to specific,
5436          * i.e, 'lfs mkdir -i -1 -c N', always allocate space for lsp_tgts.
5437          */
5438         param = calloc(1, offsetof(typeof(*param),
5439                        lsp_tgts[lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT ?
5440                                 lsa.lsa_stripe_count : lsa.lsa_nr_tgts]));
5441         if (param == NULL) {
5442                 fprintf(stderr,
5443                         "%s %s: cannot allocate memory for parameters: %s\n",
5444                         progname, argv[0], strerror(ENOMEM));
5445                 return CMD_HELP;
5446         }
5447
5448         if (lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT)
5449                 param->lsp_stripe_count = lsa.lsa_stripe_count;
5450         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
5451                 param->lsp_stripe_offset = -1;
5452         else
5453                 param->lsp_stripe_offset = lsa.lsa_stripe_off;
5454         if (lsa.lsa_pattern != LLAPI_LAYOUT_RAID0)
5455                 param->lsp_stripe_pattern = lsa.lsa_pattern;
5456         else
5457                 param->lsp_stripe_pattern = LMV_HASH_TYPE_FNV_1A_64;
5458         param->lsp_pool = lsa.lsa_pool_name;
5459         param->lsp_is_specific = false;
5460         if (lsa.lsa_nr_tgts > 1) {
5461                 if (lsa.lsa_stripe_count > 0 &&
5462                     lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT &&
5463                     lsa.lsa_stripe_count != lsa.lsa_nr_tgts) {
5464                         fprintf(stderr, "error: %s: stripe count %lld doesn't "
5465                                 "match the number of MDTs: %d\n",
5466                                 argv[0], lsa.lsa_stripe_count, lsa.lsa_nr_tgts);
5467                         free(param);
5468                         return CMD_HELP;
5469                 }
5470
5471                 param->lsp_is_specific = true;
5472                 param->lsp_stripe_count = lsa.lsa_nr_tgts;
5473                 memcpy(param->lsp_tgts, mdts, sizeof(*mdts) * lsa.lsa_nr_tgts);
5474         }
5475
5476         if (!default_stripe && lsa.lsa_pattern == LMV_HASH_TYPE_SPACE) {
5477                 fprintf(stderr, "%s %s: can only specify -H space with -D\n",
5478                         progname, argv[0]);
5479                 free(param);
5480                 return CMD_HELP;
5481         }
5482
5483         dname = argv[optind];
5484         do {
5485                 if (default_stripe) {
5486                         result = llapi_dir_set_default_lmv(dname, param);
5487                         if (result)
5488                                 fprintf(stderr,
5489                                         "%s setdirstripe: cannot set default stripe on dir '%s': %s\n",
5490                                         progname, dname, strerror(-result));
5491                         continue;
5492                 }
5493
5494                 /*
5495                  * if current \a dname isn't under the same \a mntdir as the
5496                  * last one, and the last one was auto-distributed, restore
5497                  * \a param.
5498                  */
5499                 if (mntdir[0] != '\0' &&
5500                     strncmp(dname, mntdir, strlen(mntdir)) &&
5501                     auto_distributed) {
5502                         param->lsp_is_specific = false;
5503                         param->lsp_stripe_offset = -1;
5504                         auto_distributed = false;
5505                 }
5506
5507                 /*
5508                  * TODO: when MDT can allocate object with QoS (LU-9435), below
5509                  * code should be removed, instead we should let LMV to allocate
5510                  * the starting MDT object, and then let LOD allocate other MDT
5511                  * objects.
5512                  */
5513                 if (!param->lsp_is_specific && param->lsp_stripe_offset == -1) {
5514                         char path[PATH_MAX] = "";
5515
5516                         if (!lsb) {
5517                                 lsb = malloc(sizeof(*lsb));
5518                                 if (!lsb) {
5519                                         result = -ENOMEM;
5520                                         break;
5521                                 }
5522                         }
5523                         lsb->sb_count = 0;
5524
5525                         /* use mntdir for dirname() temporarily */
5526                         strncpy(mntdir, dname, sizeof(mntdir));
5527                         if (!realpath(dirname(mntdir), path)) {
5528                                 result = -errno;
5529                                 fprintf(stderr,
5530                                         "error: invalid path '%s': %s\n",
5531                                         argv[optind], strerror(errno));
5532                                 break;
5533                         }
5534                         mntdir[0] = '\0';
5535
5536                         result = llapi_search_mounts(path, 0, mntdir, NULL);
5537                         if (result < 0 || mntdir[0] == '\0') {
5538                                 fprintf(stderr,
5539                                         "No suitable Lustre mount found\n");
5540                                 break;
5541                         }
5542
5543                         result = mntdf(mntdir, NULL, NULL, 0, LL_STATFS_LMV,
5544                                        lsb);
5545                         if (result < 0)
5546                                 break;
5547
5548                         if (param->lsp_stripe_count > lsb->sb_count) {
5549                                 fprintf(stderr,
5550                                         "error: stripe count %d is too big\n",
5551                                         param->lsp_stripe_count);
5552                                 result = -ERANGE;
5553                                 break;
5554                         }
5555
5556                         qsort(lsb->sb_buf, lsb->sb_count,
5557                               sizeof(struct ll_statfs_data),
5558                               ll_statfs_data_comp);
5559
5560                         auto_distributed = true;
5561                 }
5562
5563                 if (auto_distributed) {
5564                         int r;
5565                         int nr = MAX(param->lsp_stripe_count,
5566                                      lsb->sb_count / 2);
5567
5568                         /* don't use server whose usage is above 90% */
5569                         while (nr != param->lsp_stripe_count &&
5570                                obd_statfs_ratio(&lsb->sb_buf[nr].sd_st, false) >
5571                                90)
5572                                 nr = MAX(param->lsp_stripe_count, nr / 2);
5573
5574                         /* get \a r between [0, nr) */
5575                         r = rand() % nr;
5576
5577                         param->lsp_stripe_offset = lsb->sb_buf[r].sd_index;
5578                         if (param->lsp_stripe_count > 1) {
5579                                 int i = 0;
5580
5581                                 param->lsp_is_specific = true;
5582                                 for (; i < param->lsp_stripe_count; i++)
5583                                         param->lsp_tgts[(i + r) % nr] =
5584                                                 lsb->sb_buf[i].sd_index;
5585                         }
5586                 }
5587
5588                 result = llapi_dir_create(dname, mode, param);
5589                 if (result)
5590                         fprintf(stderr,
5591                                 "%s setdirstripe: cannot create dir '%s': %s\n",
5592                                 progname, dname, strerror(-result));
5593         } while (!result && (dname = argv[++optind]));
5594
5595         if (mode_opt != NULL)
5596                 umask(previous_mode);
5597
5598         free(lsb);
5599         free(param);
5600         return result;
5601 }
5602
5603 /* functions */
5604 static int lfs_rmentry(int argc, char **argv)
5605 {
5606         char *dname;
5607         int   index;
5608         int   result = 0;
5609
5610         if (argc <= 1) {
5611                 fprintf(stderr, "error: %s: missing dirname\n",
5612                         argv[0]);
5613                 return CMD_HELP;
5614         }
5615
5616         index = 1;
5617         dname = argv[index];
5618         while (dname != NULL) {
5619                 result = llapi_direntry_remove(dname);
5620                 if (result) {
5621                         fprintf(stderr, "error: %s: remove dir entry '%s' "
5622                                 "failed\n", argv[0], dname);
5623                         break;
5624                 }
5625                 dname = argv[++index];
5626         }
5627         return result;
5628 }
5629
5630 static int lfs_mv(int argc, char **argv)
5631 {
5632         struct lmv_user_md lmu = { LMV_USER_MAGIC };
5633         struct find_param param = {
5634                 .fp_max_depth = -1,
5635                 .fp_mdt_index = -1,
5636         };
5637         char *end;
5638         int c;
5639         int rc = 0;
5640         struct option long_opts[] = {
5641         { .val = 'm',   .name = "mdt",          .has_arg = required_argument },
5642         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument },
5643         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
5644         { .name = NULL } };
5645
5646         while ((c = getopt_long(argc, argv, "m:M:v", long_opts, NULL)) != -1) {
5647                 switch (c) {
5648 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
5649                 case 'M':
5650                         fprintf(stderr, "warning: '-M' deprecated"
5651                                 ", use '--mdt-index' or '-m' instead\n");
5652 #endif
5653                 case 'm':
5654                         lmu.lum_stripe_offset = strtoul(optarg, &end, 0);
5655                         if (*end != '\0') {
5656                                 fprintf(stderr, "%s mv: bad MDT index '%s'\n",
5657                                         progname, optarg);
5658                                 return CMD_HELP;
5659                         }
5660                         break;
5661                 case 'v':
5662                         param.fp_verbose = VERBOSE_DETAIL;
5663                         break;
5664                 default:
5665                         fprintf(stderr, "%s mv: unrecognized option '%s'\n",
5666                                 progname, argv[optind - 1]);
5667                         return CMD_HELP;
5668                 }
5669         }
5670
5671         if (lmu.lum_stripe_offset == -1) {
5672                 fprintf(stderr, "%s mv: MDT index must be specified\n",
5673                         progname);
5674                 return CMD_HELP;
5675         }
5676
5677         if (optind >= argc) {
5678                 fprintf(stderr, "%s mv: DIR must be specified\n", progname);
5679                 return CMD_HELP;
5680         }
5681
5682
5683         /* initialize migrate mdt parameters */
5684         param.fp_lmv_md = &lmu;
5685         param.fp_migrate = 1;
5686         rc = llapi_migrate_mdt(argv[optind], &param);
5687         if (rc != 0)
5688                 fprintf(stderr, "%s mv: cannot migrate '%s' to MDT%04x: %s\n",
5689                         progname, argv[optind], param.fp_mdt_index,
5690                         strerror(-rc));
5691         return rc;
5692 }
5693
5694 static int lfs_osts(int argc, char **argv)
5695 {
5696         return lfs_tgts(argc, argv);
5697 }
5698
5699 static int lfs_mdts(int argc, char **argv)
5700 {
5701         return lfs_tgts(argc, argv);
5702 }
5703
5704 static int lfs_df(int argc, char **argv)
5705 {
5706         char mntdir[PATH_MAX] = {'\0'}, path[PATH_MAX] = {'\0'};
5707         enum mntdf_flags flags = MNTDF_SHOW;
5708         int ops = LL_STATFS_LMV | LL_STATFS_LOV;
5709         int c, rc = 0, index = 0;
5710         char fsname[PATH_MAX] = "", *pool_name = NULL;
5711         struct option long_opts[] = {
5712         { .val = 'h',   .name = "human-readable",
5713                                                 .has_arg = no_argument },
5714         { .val = 'i',   .name = "inodes",       .has_arg = no_argument },
5715         { .val = 'l',   .name = "lazy",         .has_arg = no_argument },
5716         { .val = 'p',   .name = "pool",         .has_arg = required_argument },
5717         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
5718         { .name = NULL} };
5719
5720         while ((c = getopt_long(argc, argv, "hilp:v", long_opts, NULL)) != -1) {
5721                 switch (c) {
5722                 case 'h':
5723                         flags |= MNTDF_COOKED;
5724                         break;
5725                 case 'i':
5726                         flags |= MNTDF_INODES;
5727                         break;
5728                 case 'l':
5729                         flags |= MNTDF_LAZY;
5730                         break;
5731                 case 'p':
5732                         pool_name = optarg;
5733                         break;
5734                 case 'v':
5735                         flags |= MNTDF_VERBOSE;
5736                         break;
5737                 default:
5738                         return CMD_HELP;
5739                 }
5740         }
5741         if (optind < argc && !realpath(argv[optind], path)) {
5742                 rc = -errno;
5743                 fprintf(stderr, "error: invalid path '%s': %s\n",
5744                         argv[optind], strerror(-rc));
5745                 return rc;
5746         }
5747
5748         while (!llapi_search_mounts(path, index++, mntdir, fsname)) {
5749                 /* Check if we have a mount point */
5750                 if (mntdir[0] == '\0')
5751                         continue;
5752
5753                 rc = mntdf(mntdir, fsname, pool_name, flags, ops, NULL);
5754                 if (rc || path[0] != '\0')
5755                         break;
5756                 fsname[0] = '\0'; /* avoid matching in next loop */
5757                 mntdir[0] = '\0'; /* avoid matching in next loop */
5758         }
5759
5760         return rc;
5761 }
5762
5763 static int print_instance(const char *mntdir, char *fsname, size_t fsnamelen,
5764                           bool opt_instance, bool opt_fsname, bool opt_mntdir)
5765 {
5766         char *buf = fsname;
5767
5768         /* llapi_search_mounts() fills "fsname", but that is not called if
5769          * explicit paths are specified on the command-line
5770          */
5771         if (opt_instance || (opt_fsname && fsname[0] == '\0')) {
5772                 int rc = llapi_getname(mntdir, fsname, fsnamelen);
5773
5774                 if (rc < 0) {
5775                         fprintf(stderr, "cannot get instance for '%s': %s\n",
5776                                 mntdir, strerror(-rc));
5777                         return rc;
5778                 }
5779                 buf = fsname;
5780                 if (!opt_instance) {
5781                         /* print only the fsname name */
5782                         buf = strchr(fsname, '-');
5783                         if (buf)
5784                                 *buf = '\0';
5785                         buf = fsname;
5786                 } else if (!opt_fsname) {
5787                         /* print only the instance name */
5788                         buf = strchr(fsname, '-');
5789                         if (buf)
5790                                 buf++;
5791                         else
5792                                 buf = fsname;
5793                 }
5794         } else if (opt_fsname) {
5795                 /* print only the fsname */
5796                 buf = fsname;
5797         }
5798
5799         printf("%s %s\n", buf, opt_mntdir ? mntdir : "");
5800
5801         return 0;
5802 }
5803
5804 static int lfs_getname(int argc, char **argv)
5805 {
5806         struct option long_opts[] = {
5807         { .val = 'h',   .name = "help",         .has_arg = no_argument },
5808         { .val = 'i',   .name = "instance",     .has_arg = no_argument },
5809         { .val = 'n',   .name = "fsname",       .has_arg = no_argument },
5810         { .name = NULL} };
5811         bool opt_instance = false, opt_fsname = false;
5812         char fsname[PATH_MAX] = "";
5813         int rc = 0, rc2, c;
5814
5815         while ((c = getopt_long(argc, argv, "hin", long_opts, NULL)) != -1) {
5816                 switch (c) {
5817                 case 'i':
5818                         opt_instance = true;
5819                         break;
5820                 case 'n':
5821                         opt_fsname = true;
5822                         break;
5823                 case 'h':
5824                 default:
5825                         return CMD_HELP;
5826                 }
5827         }
5828
5829         /* If neither option is given, print both instance and fsname */
5830         if (!opt_instance && !opt_fsname)
5831                 opt_instance = opt_fsname = true;
5832
5833         if (optind == argc) { /* no paths specified, get all paths. */
5834                 char mntdir[PATH_MAX] = "", path[PATH_MAX] = "";
5835                 int index = 0;
5836
5837                 while (!llapi_search_mounts(path, index++, mntdir, fsname)) {
5838                         rc2 = print_instance(mntdir, fsname, sizeof(fsname),
5839                                              opt_instance, opt_fsname, true);
5840                         if (!rc)
5841                                 rc = rc2;
5842                         path[0] = fsname[0] = mntdir[0] = '\0';
5843                 }
5844         } else { /* paths specified, only attempt to search these. */
5845                 bool opt_mntdir;
5846
5847                 /* if only one path is given, print only requested info */
5848                 opt_mntdir = argc - optind > 1 || (opt_instance == opt_fsname);
5849
5850                 for (; optind < argc; optind++) {
5851                         rc2 = print_instance(argv[optind], fsname,
5852                                              sizeof(fsname), opt_instance,
5853                                              opt_fsname, opt_mntdir);
5854                         if (!rc)
5855                                 rc = rc2;
5856                         fsname[0] = '\0';
5857                 }
5858         }
5859
5860         return rc;
5861 }
5862
5863 static int lfs_check(int argc, char **argv)
5864 {
5865         char mntdir[PATH_MAX] = {'\0'};
5866         int num_types = 1;
5867         char *obd_types[3];
5868         char obd_type1[4];
5869         char obd_type2[4];
5870         char obd_type3[4];
5871         int rc;
5872
5873         if (argc != 2) {
5874                 fprintf(stderr, "%s check: server type must be specified\n",
5875                         progname);
5876                 return CMD_HELP;
5877         }
5878
5879         obd_types[0] = obd_type1;
5880         obd_types[1] = obd_type2;
5881         obd_types[2] = obd_type3;
5882
5883         if (strcmp(argv[1], "osts") == 0) {
5884                 strcpy(obd_types[0], "osc");
5885         } else if (strcmp(argv[1], "mdts") == 0 ||
5886                    strcmp(argv[1], "mds") == 0) {
5887                 strcpy(obd_types[0], "mdc");
5888         } else if (strcmp(argv[1], "mgts") == 0) {
5889                 strcpy(obd_types[0], "mgc");
5890         } else if (strcmp(argv[1], "all") == 0 ||
5891                    strcmp(argv[1], "servers") == 0) {
5892                 num_types = 3;
5893                 strcpy(obd_types[0], "osc");
5894                 strcpy(obd_types[1], "mdc");
5895                 strcpy(obd_types[2], "mgc");
5896         } else {
5897                 fprintf(stderr, "%s check: unrecognized option '%s'\n",
5898                         progname, argv[1]);
5899                 return CMD_HELP;
5900         }
5901
5902         rc = llapi_search_mounts(NULL, 0, mntdir, NULL);
5903         if (rc < 0 || mntdir[0] == '\0') {
5904                 fprintf(stderr,
5905                         "%s check: cannot find mounted Lustre filesystem: %s\n",
5906                         progname, (rc < 0) ? strerror(-rc) : strerror(ENODEV));
5907                 return rc;
5908         }
5909
5910         rc = llapi_target_check(num_types, obd_types, mntdir);
5911         if (rc)
5912                 fprintf(stderr, "%s check: cannot check target '%s': %s\n",
5913                         progname, argv[1], strerror(-rc));
5914
5915         return rc;
5916
5917 }
5918
5919 #ifdef HAVE_SYS_QUOTA_H
5920 #define ARG2INT(nr, str, msg)                                           \
5921 do {                                                                    \
5922         char *endp;                                                     \
5923         nr = strtol(str, &endp, 0);                                     \
5924         if (*endp != '\0') {                                            \
5925                 fprintf(stderr, "%s: bad %s '%s'\n",                    \
5926                         progname, msg, str);                            \
5927                 return CMD_HELP;                                        \
5928         }                                                               \
5929 } while (0)
5930
5931 #define ADD_OVERFLOW(a,b) ((a + b) < a) ? (a = ULONG_MAX) : (a = a + b)
5932
5933 /* Convert format time string "XXwXXdXXhXXmXXs" into seconds value
5934  * returns the value or ULONG_MAX on integer overflow or incorrect format
5935  * Notes:
5936  *        1. the order of specifiers is arbitrary (may be: 5w3s or 3s5w)
5937  *        2. specifiers may be encountered multiple times (2s3s is 5 seconds)
5938  *        3. empty integer value is interpreted as 0
5939  */
5940 static unsigned long str2sec(const char* timestr)
5941 {
5942         const char spec[] = "smhdw";
5943         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
5944         unsigned long val = 0;
5945         char *tail;
5946
5947         if (strpbrk(timestr, spec) == NULL) {
5948                 /* no specifiers inside the time string,
5949                    should treat it as an integer value */
5950                 val = strtoul(timestr, &tail, 10);
5951                 return *tail ? ULONG_MAX : val;
5952         }
5953
5954         /* format string is XXwXXdXXhXXmXXs */
5955         while (*timestr) {
5956                 unsigned long v;
5957                 int ind;
5958                 char* ptr;
5959
5960                 v = strtoul(timestr, &tail, 10);
5961                 if (v == ULONG_MAX || *tail == '\0')
5962                         /* value too large (ULONG_MAX or more)
5963                            or missing specifier */
5964                         goto error;
5965
5966                 ptr = strchr(spec, *tail);
5967                 if (ptr == NULL)
5968                         /* unknown specifier */
5969                         goto error;
5970
5971                 ind = ptr - spec;
5972
5973                 /* check if product will overflow the type */
5974                 if (!(v < ULONG_MAX / mult[ind]))
5975                         goto error;
5976
5977                 ADD_OVERFLOW(val, mult[ind] * v);
5978                 if (val == ULONG_MAX)
5979                         goto error;
5980
5981                 timestr = tail + 1;
5982         }
5983
5984         return val;
5985
5986 error:
5987         return ULONG_MAX;
5988 }
5989
5990 #define ARG2ULL(nr, str, def_units)                                     \
5991 do {                                                                    \
5992         unsigned long long limit, units = def_units;                    \
5993         int rc;                                                         \
5994                                                                         \
5995         rc = llapi_parse_size(str, &limit, &units, 1);                  \
5996         if (rc < 0) {                                                   \
5997                 fprintf(stderr, "%s: invalid limit '%s'\n",             \
5998                         progname, str);                                 \
5999                 return CMD_HELP;                                        \
6000         }                                                               \
6001         nr = limit;                                                     \
6002 } while (0)
6003
6004 static inline int has_times_option(int argc, char **argv)
6005 {
6006         int i;
6007
6008         for (i = 1; i < argc; i++)
6009                 if (!strcmp(argv[i], "-t"))
6010                         return 1;
6011
6012         return 0;
6013 }
6014
6015 int lfs_setquota_times(int argc, char **argv)
6016 {
6017         int c, rc;
6018         struct if_quotactl qctl;
6019         char *mnt, *obd_type = (char *)qctl.obd_type;
6020         struct obd_dqblk *dqb = &qctl.qc_dqblk;
6021         struct obd_dqinfo *dqi = &qctl.qc_dqinfo;
6022         struct option long_opts[] = {
6023         { .val = 'b',   .name = "block-grace",  .has_arg = required_argument },
6024         { .val = 'g',   .name = "group",        .has_arg = no_argument },
6025         { .val = 'i',   .name = "inode-grace",  .has_arg = required_argument },
6026         { .val = 'p',   .name = "projid",       .has_arg = no_argument },
6027         { .val = 't',   .name = "times",        .has_arg = no_argument },
6028         { .val = 'u',   .name = "user",         .has_arg = no_argument },
6029         { .name = NULL } };
6030         int qtype;
6031
6032         memset(&qctl, 0, sizeof(qctl));
6033         qctl.qc_cmd  = LUSTRE_Q_SETINFO;
6034         qctl.qc_type = ALLQUOTA;
6035
6036         while ((c = getopt_long(argc, argv, "b:gi:ptu",
6037                                 long_opts, NULL)) != -1) {
6038                 switch (c) {
6039                 case 'u':
6040                         qtype = USRQUOTA;
6041                         goto quota_type;
6042                 case 'g':
6043                         qtype = GRPQUOTA;
6044                         goto quota_type;
6045                 case 'p':
6046                         qtype = PRJQUOTA;
6047 quota_type:
6048                         if (qctl.qc_type != ALLQUOTA) {
6049                                 fprintf(stderr, "error: -u/g/p can't be used "
6050                                                 "more than once\n");
6051                                 return CMD_HELP;
6052                         }
6053                         qctl.qc_type = qtype;
6054                         break;
6055                 case 'b':
6056                         if ((dqi->dqi_bgrace = str2sec(optarg)) == ULONG_MAX) {
6057                                 fprintf(stderr, "error: bad block-grace: %s\n",
6058                                         optarg);
6059                                 return CMD_HELP;
6060                         }
6061                         dqb->dqb_valid |= QIF_BTIME;
6062                         break;
6063                 case 'i':
6064                         if ((dqi->dqi_igrace = str2sec(optarg)) == ULONG_MAX) {
6065                                 fprintf(stderr, "error: bad inode-grace: %s\n",
6066                                         optarg);
6067                                 return CMD_HELP;
6068                         }
6069                         dqb->dqb_valid |= QIF_ITIME;
6070                         break;
6071                 case 't': /* Yes, of course! */
6072                         break;
6073                 default: /* getopt prints error message for us when opterr != 0 */
6074                         return CMD_HELP;
6075                 }
6076         }
6077
6078         if (qctl.qc_type == ALLQUOTA) {
6079                 fprintf(stderr, "error: neither -u, -g nor -p specified\n");
6080                 return CMD_HELP;
6081         }
6082
6083         if (optind != argc - 1) {
6084                 fprintf(stderr, "error: unexpected parameters encountered\n");
6085                 return CMD_HELP;
6086         }
6087
6088         if ((dqb->dqb_valid | QIF_BTIME && dqi->dqi_bgrace >= UINT_MAX) ||
6089             (dqb->dqb_valid | QIF_ITIME && dqi->dqi_igrace >= UINT_MAX)) {
6090                 fprintf(stderr, "error: grace time is too large\n");
6091                 return CMD_HELP;
6092         }
6093
6094         mnt = argv[optind];
6095         rc = llapi_quotactl(mnt, &qctl);
6096         if (rc) {
6097                 if (*obd_type)
6098                         fprintf(stderr, "%s %s ", obd_type,
6099                                 obd_uuid2str(&qctl.obd_uuid));
6100                 fprintf(stderr, "setquota failed: %s\n", strerror(-rc));
6101                 return rc;
6102         }
6103
6104         return 0;
6105 }
6106
6107 #define BSLIMIT (1 << 0)
6108 #define BHLIMIT (1 << 1)
6109 #define ISLIMIT (1 << 2)
6110 #define IHLIMIT (1 << 3)
6111
6112 int lfs_setquota(int argc, char **argv)
6113 {
6114         int c, rc = 0;
6115         struct if_quotactl qctl;
6116         char *mnt, *obd_type = (char *)qctl.obd_type;
6117         struct obd_dqblk *dqb = &qctl.qc_dqblk;
6118         struct option long_opts[] = {
6119         { .val = 'b',   .name = "block-softlimit",
6120                                                 .has_arg = required_argument },
6121         { .val = 'B',   .name = "block-hardlimit",
6122                                                 .has_arg = required_argument },
6123         { .val = 'd',   .name = "default",      .has_arg = no_argument },
6124         { .val = 'g',   .name = "group",        .has_arg = required_argument },
6125         { .val = 'G',   .name = "default-grp",  .has_arg = no_argument },
6126         { .val = 'i',   .name = "inode-softlimit",
6127                                                 .has_arg = required_argument },
6128         { .val = 'I',   .name = "inode-hardlimit",
6129                                                 .has_arg = required_argument },
6130         { .val = 'p',   .name = "projid",       .has_arg = required_argument },
6131         { .val = 'P',   .name = "default-prj",  .has_arg = no_argument },
6132         { .val = 'u',   .name = "user",         .has_arg = required_argument },
6133         { .val = 'U',   .name = "default-usr",  .has_arg = no_argument },
6134         { .name = NULL } };
6135         unsigned limit_mask = 0;
6136         char *endptr;
6137         bool use_default = false;
6138         int qtype;
6139
6140         if (has_times_option(argc, argv))
6141                 return lfs_setquota_times(argc, argv);
6142
6143         memset(&qctl, 0, sizeof(qctl));
6144         qctl.qc_cmd  = LUSTRE_Q_SETQUOTA;
6145         qctl.qc_type = ALLQUOTA; /* ALLQUOTA makes no sense for setquota,
6146                                   * so it can be used as a marker that qc_type
6147                                   * isn't reinitialized from command line */
6148
6149         while ((c = getopt_long(argc, argv, "b:B:dg:Gi:I:p:Pu:U",
6150                 long_opts, NULL)) != -1) {
6151                 switch (c) {
6152                 case 'U':
6153                         qctl.qc_cmd = LUSTRE_Q_SETDEFAULT;
6154                         qtype = USRQUOTA;
6155                         qctl.qc_id = 0;
6156                         goto quota_type_def;
6157                 case 'u':
6158                         qtype = USRQUOTA;
6159                         rc = name2uid(&qctl.qc_id, optarg);
6160                         goto quota_type;
6161                 case 'G':
6162                         qctl.qc_cmd = LUSTRE_Q_SETDEFAULT;
6163                         qtype = GRPQUOTA;
6164                         qctl.qc_id = 0;
6165                         goto quota_type_def;
6166                 case 'g':
6167                         qtype = GRPQUOTA;
6168                         rc = name2gid(&qctl.qc_id, optarg);
6169                         goto quota_type;
6170                 case 'P':
6171                         qctl.qc_cmd = LUSTRE_Q_SETDEFAULT;
6172                         qtype = PRJQUOTA;
6173                         qctl.qc_id = 0;
6174                         goto quota_type_def;
6175                 case 'p':
6176                         qtype = PRJQUOTA;
6177                         rc = name2projid(&qctl.qc_id, optarg);
6178 quota_type:
6179                         if (rc) {
6180                                 qctl.qc_id = strtoul(optarg, &endptr, 10);
6181                                 if (*endptr != '\0') {
6182                                         fprintf(stderr, "%s setquota: invalid"
6183                                                 " id '%s'\n", progname, optarg);
6184                                         return -1;
6185                                 }
6186                         }
6187
6188                         if (qctl.qc_id == 0) {
6189                                 fprintf(stderr, "%s setquota: can't set quota"
6190                                         " for root usr/group/project.\n",
6191                                         progname);
6192                                 return -1;
6193                         }
6194
6195 quota_type_def:
6196                         if (qctl.qc_type != ALLQUOTA) {
6197                                 fprintf(stderr,
6198                                         "%s setquota: only one of -u, -U, -g,"
6199                                         " -G, -p or -P may be specified\n",
6200                                         progname);
6201                                 return CMD_HELP;
6202                         }
6203                         qctl.qc_type = qtype;
6204                         break;
6205                 case 'd':
6206                         qctl.qc_cmd = LUSTRE_Q_SETDEFAULT;
6207                         use_default = true;
6208                         break;
6209                 case 'b':
6210                         ARG2ULL(dqb->dqb_bsoftlimit, optarg, 1024);
6211                         dqb->dqb_bsoftlimit >>= 10;
6212                         limit_mask |= BSLIMIT;
6213                         if (dqb->dqb_bsoftlimit &&
6214                             dqb->dqb_bsoftlimit <= 1024) /* <= 1M? */
6215                                 fprintf(stderr,
6216                                         "%s setquota: warning: block softlimit '%llu' smaller than minimum qunit size\n"
6217                                         "See '%s help setquota' or Lustre manual for details\n",
6218                                         progname, dqb->dqb_bsoftlimit,
6219                                         progname);
6220                         break;
6221                 case 'B':
6222                         ARG2ULL(dqb->dqb_bhardlimit, optarg, 1024);
6223                         dqb->dqb_bhardlimit >>= 10;
6224                         limit_mask |= BHLIMIT;
6225                         if (dqb->dqb_bhardlimit &&
6226                             dqb->dqb_bhardlimit <= 1024) /* <= 1M? */
6227                                 fprintf(stderr,
6228                                         "%s setquota: warning: block hardlimit '%llu' smaller than minimum qunit size\n"
6229                                         "See '%s help setquota' or Lustre manual for details\n",
6230                                         progname, dqb->dqb_bhardlimit,
6231                                         progname);
6232                         break;
6233                 case 'i':
6234                         ARG2ULL(dqb->dqb_isoftlimit, optarg, 1);
6235                         limit_mask |= ISLIMIT;
6236                         if (dqb->dqb_isoftlimit &&
6237                             dqb->dqb_isoftlimit <= 1024) /* <= 1K inodes? */
6238                                 fprintf(stderr,
6239                                         "%s setquota: warning: inode softlimit '%llu' smaller than minimum qunit size\n"
6240                                         "See '%s help setquota' or Lustre manual for details\n",
6241                                         progname, dqb->dqb_isoftlimit,
6242                                         progname);
6243                         break;
6244                 case 'I':
6245                         ARG2ULL(dqb->dqb_ihardlimit, optarg, 1);
6246                         limit_mask |= IHLIMIT;
6247                         if (dqb->dqb_ihardlimit &&
6248                             dqb->dqb_ihardlimit <= 1024) /* <= 1K inodes? */
6249                                 fprintf(stderr,
6250                                         "%s setquota: warning: inode hardlimit '%llu' smaller than minimum qunit size\n"
6251                                         "See '%s help setquota' or Lustre manual for details\n",
6252                                         progname, dqb->dqb_ihardlimit,
6253                                         progname);
6254                         break;
6255                 default:
6256                         fprintf(stderr,
6257                                 "%s setquota: unrecognized option '%s'\n",
6258                                 progname, argv[optind - 1]);
6259                         return CMD_HELP;
6260                 }
6261         }
6262
6263         if (qctl.qc_type == ALLQUOTA) {
6264                 fprintf(stderr,
6265                         "%s setquota: either -u or -g must be specified\n",
6266                         progname);
6267                 return CMD_HELP;
6268         }
6269
6270         if (!use_default && limit_mask == 0) {
6271                 fprintf(stderr,
6272                         "%s setquota: at least one limit must be specified\n",
6273                         progname);
6274                 return CMD_HELP;
6275         }
6276
6277         if (use_default && limit_mask != 0) {
6278                 fprintf(stderr,
6279                         "%s setquota: limits should not be specified when"
6280                         " using default quota\n",
6281                         progname);
6282                 return CMD_HELP;
6283         }
6284
6285         if (use_default && qctl.qc_id == 0) {
6286                 fprintf(stderr,
6287                         "%s setquota: can not set default quota for root"
6288                         " user/group/project\n",
6289                         progname);
6290                 return CMD_HELP;
6291         }
6292
6293         if (optind != argc - 1) {
6294                 fprintf(stderr,
6295                         "%s setquota: filesystem not specified or unexpected argument '%s'\n",
6296                         progname, argv[optind]);
6297                 return CMD_HELP;
6298         }
6299
6300         mnt = argv[optind];
6301
6302         if (use_default) {
6303                 dqb->dqb_bhardlimit = 0;
6304                 dqb->dqb_bsoftlimit = 0;
6305                 dqb->dqb_ihardlimit = 0;
6306                 dqb->dqb_isoftlimit = 0;
6307                 dqb->dqb_itime = 0;
6308                 dqb->dqb_btime = 0;
6309                 dqb->dqb_valid |= QIF_LIMITS | QIF_TIMES;
6310         } else if ((!(limit_mask & BHLIMIT) ^ !(limit_mask & BSLIMIT)) ||
6311                    (!(limit_mask & IHLIMIT) ^ !(limit_mask & ISLIMIT))) {
6312                 /* sigh, we can't just set blimits/ilimits */
6313                 struct if_quotactl tmp_qctl = {.qc_cmd  = LUSTRE_Q_GETQUOTA,
6314                                                .qc_type = qctl.qc_type,
6315                                                .qc_id   = qctl.qc_id};
6316
6317                 rc = llapi_quotactl(mnt, &tmp_qctl);
6318                 if (rc < 0)
6319                         return rc;
6320
6321                 if (!(limit_mask & BHLIMIT))
6322                         dqb->dqb_bhardlimit = tmp_qctl.qc_dqblk.dqb_bhardlimit;
6323                 if (!(limit_mask & BSLIMIT))
6324                         dqb->dqb_bsoftlimit = tmp_qctl.qc_dqblk.dqb_bsoftlimit;
6325                 if (!(limit_mask & IHLIMIT))
6326                         dqb->dqb_ihardlimit = tmp_qctl.qc_dqblk.dqb_ihardlimit;
6327                 if (!(limit_mask & ISLIMIT))
6328                         dqb->dqb_isoftlimit = tmp_qctl.qc_dqblk.dqb_isoftlimit;
6329
6330                 /* Keep grace times if we have got no softlimit arguments */
6331                 if ((limit_mask & BHLIMIT) && !(limit_mask & BSLIMIT)) {
6332                         dqb->dqb_valid |= QIF_BTIME;
6333                         dqb->dqb_btime = tmp_qctl.qc_dqblk.dqb_btime;
6334                 }
6335
6336                 if ((limit_mask & IHLIMIT) && !(limit_mask & ISLIMIT)) {
6337                         dqb->dqb_valid |= QIF_ITIME;
6338                         dqb->dqb_itime = tmp_qctl.qc_dqblk.dqb_itime;
6339                 }
6340         }
6341
6342         dqb->dqb_valid |= (limit_mask & (BHLIMIT | BSLIMIT)) ? QIF_BLIMITS : 0;
6343         dqb->dqb_valid |= (limit_mask & (IHLIMIT | ISLIMIT)) ? QIF_ILIMITS : 0;
6344
6345         rc = llapi_quotactl(mnt, &qctl);
6346         if (rc) {
6347                 if (*obd_type)
6348                         fprintf(stderr,
6349                                 "%s setquota: cannot quotactl '%s' '%s': %s",
6350                                 progname, obd_type,
6351                                 obd_uuid2str(&qctl.obd_uuid), strerror(-rc));
6352                 return rc;
6353         }
6354
6355         return 0;
6356 }
6357
6358 /* Converts seconds value into format string
6359  * result is returned in buf
6360  * Notes:
6361  *        1. result is in descenting order: 1w2d3h4m5s
6362  *        2. zero fields are not filled (except for p. 3): 5d1s
6363  *        3. zero seconds value is presented as "0s"
6364  */
6365 static char * __sec2str(time_t seconds, char *buf)
6366 {
6367         const char spec[] = "smhdw";
6368         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
6369         unsigned long c;
6370         char *tail = buf;
6371         int i;
6372
6373         for (i = sizeof(mult) / sizeof(mult[0]) - 1 ; i >= 0; i--) {
6374                 c = seconds / mult[i];
6375
6376                 if (c > 0 || (i == 0 && buf == tail))
6377                         tail += snprintf(tail, 40-(tail-buf), "%lu%c", c, spec[i]);
6378
6379                 seconds %= mult[i];
6380         }
6381
6382         return tail;
6383 }
6384
6385 static void sec2str(time_t seconds, char *buf, int rc)
6386 {
6387         char *tail = buf;
6388
6389         if (rc)
6390                 *tail++ = '[';
6391
6392         tail = __sec2str(seconds, tail);
6393
6394         if (rc && tail - buf < 39) {
6395                 *tail++ = ']';
6396                 *tail++ = 0;
6397         }
6398 }
6399
6400 static void diff2str(time_t seconds, char *buf, time_t now)
6401 {
6402
6403         buf[0] = 0;
6404         if (!seconds)
6405                 return;
6406         if (seconds <= now) {
6407                 strcpy(buf, "none");
6408                 return;
6409         }
6410         __sec2str(seconds - now, buf);
6411 }
6412
6413 static void print_quota_title(char *name, struct if_quotactl *qctl,
6414                               bool human_readable, bool show_default)
6415 {
6416         if (show_default) {
6417                 printf("Disk default %s quota:\n", qtype_name(qctl->qc_type));
6418                 printf("%15s %8s%8s%8s %8s%8s%8s\n",
6419                        "Filesystem", "bquota", "blimit", "bgrace",
6420                        "iquota", "ilimit", "igrace");
6421         } else {
6422                 printf("Disk quotas for %s %s (%cid %u):\n",
6423                        qtype_name(qctl->qc_type), name,
6424                        *qtype_name(qctl->qc_type), qctl->qc_id);
6425                 printf("%15s%8s %7s%8s%8s%8s %7s%8s%8s\n",
6426                        "Filesystem", human_readable ? "used" : "kbytes",
6427                        "quota", "limit", "grace",
6428                        "files", "quota", "limit", "grace");
6429         }
6430 }
6431
6432 static void kbytes2str(__u64 num, char *buf, int buflen, bool h)
6433 {
6434         if (!h) {
6435                 snprintf(buf, buflen, "%ju", (uintmax_t)num);
6436         } else {
6437                 if (num >> 40)
6438                         snprintf(buf, buflen, "%5.4gP",
6439                                  (double)num / ((__u64)1 << 40));
6440                 else if (num >> 30)
6441                         snprintf(buf, buflen, "%5.4gT",
6442                                  (double)num / (1 << 30));
6443                 else if (num >> 20)
6444                         snprintf(buf, buflen, "%5.4gG",
6445                                  (double)num / (1 << 20));
6446                 else if (num >> 10)
6447                         snprintf(buf, buflen, "%5.4gM",
6448                                  (double)num / (1 << 10));
6449                 else
6450                         snprintf(buf, buflen, "%ju%s", (uintmax_t)num, "k");
6451         }
6452 }
6453
6454 #define STRBUF_LEN      32
6455 static void print_quota(char *mnt, struct if_quotactl *qctl, int type,
6456                         int rc, bool h, bool show_default)
6457 {
6458         time_t now;
6459
6460         time(&now);
6461
6462         if (qctl->qc_cmd == LUSTRE_Q_GETQUOTA || qctl->qc_cmd == Q_GETOQUOTA ||
6463             qctl->qc_cmd == LUSTRE_Q_GETDEFAULT) {
6464                 int bover = 0, iover = 0;
6465                 struct obd_dqblk *dqb = &qctl->qc_dqblk;
6466                 char numbuf[3][STRBUF_LEN];
6467                 char timebuf[40];
6468                 char strbuf[STRBUF_LEN];
6469
6470                 if (dqb->dqb_bhardlimit &&
6471                     lustre_stoqb(dqb->dqb_curspace) >= dqb->dqb_bhardlimit) {
6472                         bover = 1;
6473                 } else if (dqb->dqb_bsoftlimit && dqb->dqb_btime) {
6474                         if (dqb->dqb_btime > now) {
6475                                 bover = 2;
6476                         } else {
6477                                 bover = 3;
6478                         }
6479                 }
6480
6481                 if (dqb->dqb_ihardlimit &&
6482                     dqb->dqb_curinodes >= dqb->dqb_ihardlimit) {
6483                         iover = 1;
6484                 } else if (dqb->dqb_isoftlimit && dqb->dqb_itime) {
6485                         if (dqb->dqb_itime > now) {
6486                                 iover = 2;
6487                         } else {
6488                                 iover = 3;
6489                         }
6490                 }
6491
6492
6493                 if (strlen(mnt) > 15)
6494                         printf("%s\n%15s", mnt, "");
6495                 else
6496                         printf("%15s", mnt);
6497
6498                 if (bover)
6499                         diff2str(dqb->dqb_btime, timebuf, now);
6500                 else if (show_default)
6501                         snprintf(timebuf, sizeof(timebuf), "%llu",
6502                                  dqb->dqb_btime);
6503
6504                 kbytes2str(lustre_stoqb(dqb->dqb_curspace),
6505                            strbuf, sizeof(strbuf), h);
6506                 if (rc == -EREMOTEIO)
6507                         sprintf(numbuf[0], "%s*", strbuf);
6508                 else
6509                         sprintf(numbuf[0], (dqb->dqb_valid & QIF_SPACE) ?
6510                                 "%s" : "[%s]", strbuf);
6511
6512                 kbytes2str(dqb->dqb_bsoftlimit, strbuf, sizeof(strbuf), h);
6513                 if (type == QC_GENERAL)
6514                         sprintf(numbuf[1], (dqb->dqb_valid & QIF_BLIMITS) ?
6515                                 "%s" : "[%s]", strbuf);
6516                 else
6517                         sprintf(numbuf[1], "%s", "-");
6518
6519                 kbytes2str(dqb->dqb_bhardlimit, strbuf, sizeof(strbuf), h);
6520                 sprintf(numbuf[2], (dqb->dqb_valid & QIF_BLIMITS) ?
6521                         "%s" : "[%s]", strbuf);
6522
6523                 if (show_default)
6524                         printf(" %6s %7s %7s", numbuf[1], numbuf[2], timebuf);
6525                 else
6526                         printf(" %7s%c %6s %7s %7s",
6527                                numbuf[0], bover ? '*' : ' ', numbuf[1],
6528                                numbuf[2], bover > 1 ? timebuf : "-");
6529
6530
6531                 if (iover)
6532                         diff2str(dqb->dqb_itime, timebuf, now);
6533                 else if (show_default)
6534                         snprintf(timebuf, sizeof(timebuf), "%llu",
6535                                  dqb->dqb_itime);
6536
6537                 snprintf(numbuf[0], sizeof(numbuf),
6538                          (dqb->dqb_valid & QIF_INODES) ? "%ju" : "[%ju]",
6539                          (uintmax_t)dqb->dqb_curinodes);
6540
6541                 if (type == QC_GENERAL)
6542                         sprintf(numbuf[1], (dqb->dqb_valid & QIF_ILIMITS) ?
6543                                 "%ju" : "[%ju]",
6544                                 (uintmax_t)dqb->dqb_isoftlimit);
6545                 else
6546                         sprintf(numbuf[1], "%s", "-");
6547
6548                 sprintf(numbuf[2], (dqb->dqb_valid & QIF_ILIMITS) ?
6549                         "%ju" : "[%ju]", (uintmax_t)dqb->dqb_ihardlimit);
6550
6551                 if (show_default)
6552                         printf(" %6s %7s %7s", numbuf[1], numbuf[2], timebuf);
6553                 else if (type != QC_OSTIDX)
6554                         printf(" %7s%c %6s %7s %7s",
6555                                numbuf[0], iover ? '*' : ' ', numbuf[1],
6556                                numbuf[2], iover > 1 ? timebuf : "-");
6557                 else
6558                         printf(" %7s %7s %7s %7s", "-", "-", "-", "-");
6559                 printf("\n");
6560
6561         } else if (qctl->qc_cmd == LUSTRE_Q_GETINFO ||
6562                    qctl->qc_cmd == Q_GETOINFO) {
6563                 char bgtimebuf[40];
6564                 char igtimebuf[40];
6565
6566                 sec2str(qctl->qc_dqinfo.dqi_bgrace, bgtimebuf, rc);
6567                 sec2str(qctl->qc_dqinfo.dqi_igrace, igtimebuf, rc);
6568                 printf("Block grace time: %s; Inode grace time: %s\n",
6569                        bgtimebuf, igtimebuf);
6570         }
6571 }
6572
6573 static int print_obd_quota(char *mnt, struct if_quotactl *qctl, int is_mdt,
6574                            bool h, __u64 *total)
6575 {
6576         int rc = 0, rc1 = 0, count = 0;
6577         __u32 valid = qctl->qc_valid;
6578
6579         rc = llapi_get_obd_count(mnt, &count, is_mdt);
6580         if (rc) {
6581                 fprintf(stderr, "can not get %s count: %s\n",
6582                         is_mdt ? "mdt": "ost", strerror(-rc));
6583                 return rc;
6584         }
6585
6586         for (qctl->qc_idx = 0; qctl->qc_idx < count; qctl->qc_idx++) {
6587                 qctl->qc_valid = is_mdt ? QC_MDTIDX : QC_OSTIDX;
6588                 rc = llapi_quotactl(mnt, qctl);
6589                 if (rc) {
6590                         /* It is remote client case. */
6591                         if (rc == -EOPNOTSUPP) {
6592                                 rc = 0;
6593                                 goto out;
6594                         }
6595
6596                         if (!rc1)
6597                                 rc1 = rc;
6598                         fprintf(stderr, "quotactl %s%d failed.\n",
6599                                 is_mdt ? "mdt": "ost", qctl->qc_idx);
6600                         continue;
6601                 }
6602
6603                 print_quota(obd_uuid2str(&qctl->obd_uuid), qctl,
6604                             qctl->qc_valid, 0, h, false);
6605                 *total += is_mdt ? qctl->qc_dqblk.dqb_ihardlimit :
6606                                    qctl->qc_dqblk.dqb_bhardlimit;
6607         }
6608 out:
6609         qctl->qc_valid = valid;
6610         return rc ? : rc1;
6611 }
6612
6613 static int get_print_quota(char *mnt, char *name, struct if_quotactl *qctl,
6614                            int verbose, int quiet, bool human_readable,
6615                            bool show_default)
6616 {
6617         int rc1 = 0, rc2 = 0, rc3 = 0;
6618         char *obd_type = (char *)qctl->obd_type;
6619         char *obd_uuid = (char *)qctl->obd_uuid.uuid;
6620         __u64 total_ialloc = 0, total_balloc = 0;
6621         bool use_default_for_blk = false;
6622         bool use_default_for_file = false;
6623         int inacc;
6624
6625         rc1 = llapi_quotactl(mnt, qctl);
6626         if (rc1 < 0) {
6627                 switch (rc1) {
6628                 case -ESRCH:
6629                         fprintf(stderr, "%s quotas are not enabled.\n",
6630                                 qtype_name(qctl->qc_type));
6631                         goto out;
6632                 case -EPERM:
6633                         fprintf(stderr, "Permission denied.\n");
6634                 case -ENODEV:
6635                 case -ENOENT:
6636                         /* We already got error message. */
6637                         goto out;
6638                 default:
6639                         fprintf(stderr, "Unexpected quotactl error: %s\n",
6640                                 strerror(-rc1));
6641                 }
6642         }
6643
6644         if (!show_default && qctl->qc_id == 0) {
6645                 qctl->qc_dqblk.dqb_bhardlimit = 0;
6646                 qctl->qc_dqblk.dqb_bsoftlimit = 0;
6647                 qctl->qc_dqblk.dqb_ihardlimit = 0;
6648                 qctl->qc_dqblk.dqb_isoftlimit = 0;
6649                 qctl->qc_dqblk.dqb_btime = 0;
6650                 qctl->qc_dqblk.dqb_itime = 0;
6651                 qctl->qc_dqblk.dqb_valid |= QIF_LIMITS | QIF_TIMES;
6652         }
6653
6654         if (qctl->qc_dqblk.dqb_valid & QIF_BTIME &&
6655             LQUOTA_FLAG(qctl->qc_dqblk.dqb_btime) & LQUOTA_FLAG_DEFAULT) {
6656                 use_default_for_blk = true;
6657                 qctl->qc_dqblk.dqb_btime &= LQUOTA_GRACE_MASK;
6658         }
6659
6660         if (qctl->qc_dqblk.dqb_valid & QIF_ITIME &&
6661             LQUOTA_FLAG(qctl->qc_dqblk.dqb_itime) & LQUOTA_FLAG_DEFAULT) {
6662                 use_default_for_file = true;
6663                 qctl->qc_dqblk.dqb_itime &= LQUOTA_GRACE_MASK;
6664         }
6665
6666         if ((qctl->qc_cmd == LUSTRE_Q_GETQUOTA ||
6667              qctl->qc_cmd == LUSTRE_Q_GETDEFAULT) && !quiet)
6668                 print_quota_title(name, qctl, human_readable, show_default);
6669
6670         if (rc1 && *obd_type)
6671                 fprintf(stderr, "%s %s ", obd_type, obd_uuid);
6672
6673         if (qctl->qc_valid != QC_GENERAL)
6674                 mnt = "";
6675
6676         inacc = (qctl->qc_cmd == LUSTRE_Q_GETQUOTA) &&
6677                 ((qctl->qc_dqblk.dqb_valid & (QIF_LIMITS|QIF_USAGE)) !=
6678                  (QIF_LIMITS|QIF_USAGE));
6679
6680         print_quota(mnt, qctl, QC_GENERAL, rc1, human_readable, show_default);
6681
6682         if (!show_default && verbose &&
6683             qctl->qc_valid == QC_GENERAL && qctl->qc_cmd != LUSTRE_Q_GETINFO) {
6684                 char strbuf[STRBUF_LEN];
6685
6686                 rc2 = print_obd_quota(mnt, qctl, 1, human_readable,
6687                                       &total_ialloc);
6688                 rc3 = print_obd_quota(mnt, qctl, 0, human_readable,
6689                                       &total_balloc);
6690                 kbytes2str(total_balloc, strbuf, sizeof(strbuf),
6691                            human_readable);
6692                 printf("Total allocated inode limit: %ju, total "
6693                        "allocated block limit: %s\n", (uintmax_t)total_ialloc,
6694                        strbuf);
6695         }
6696
6697         if (use_default_for_blk)
6698                 printf("%cid %u is using default block quota setting\n",
6699                        *qtype_name(qctl->qc_type), qctl->qc_id);
6700
6701         if (use_default_for_file)
6702                 printf("%cid %u is using default file quota setting\n",
6703                        *qtype_name(qctl->qc_type), qctl->qc_id);
6704
6705         if (rc1 || rc2 || rc3 || inacc)
6706                 printf("Some errors happened when getting quota info. "
6707                        "Some devices may be not working or deactivated. "
6708                        "The data in \"[]\" is inaccurate.\n");
6709 out:
6710         return rc1;
6711
6712 }
6713
6714 static int lfs_project(int argc, char **argv)
6715 {
6716         int ret = 0, err = 0, c, i;
6717         struct project_handle_control phc = { 0 };
6718         enum lfs_project_ops_t op;
6719
6720         phc.newline = true;
6721         phc.assign_projid = false;
6722         /* default action */
6723         op = LFS_PROJECT_LIST;
6724
6725         while ((c = getopt(argc, argv, "p:cCsdkr0")) != -1) {
6726                 switch (c) {
6727                 case 'c':
6728                         if (op != LFS_PROJECT_LIST) {
6729                                 fprintf(stderr,
6730                                         "%s: cannot specify '-c' '-C' '-s' together\n",
6731                                         progname);
6732                                 return CMD_HELP;
6733                         }
6734
6735                         op = LFS_PROJECT_CHECK;
6736                         break;
6737                 case 'C':
6738                         if (op != LFS_PROJECT_LIST) {
6739                                 fprintf(stderr,
6740                                         "%s: cannot specify '-c' '-C' '-s' together\n",
6741                                         progname);
6742                                 return CMD_HELP;
6743                         }
6744
6745                         op = LFS_PROJECT_CLEAR;
6746                         break;
6747                 case 's':
6748                         if (op != LFS_PROJECT_LIST) {
6749                                 fprintf(stderr,
6750                                         "%s: cannot specify '-c' '-C' '-s' together\n",
6751                                         progname);
6752                                 return CMD_HELP;
6753                         }
6754
6755                         phc.set_inherit = true;
6756                         op = LFS_PROJECT_SET;
6757                         break;
6758                 case 'd':
6759                         phc.dironly = true;
6760                         break;
6761                 case 'k':
6762                         phc.keep_projid = true;
6763                         break;
6764                 case 'r':
6765                         phc.recursive = true;
6766                         break;
6767                 case 'p':
6768                         phc.projid = strtoul(optarg, NULL, 0);
6769                         phc.assign_projid = true;
6770
6771                         break;
6772                 case '0':
6773                         phc.newline = false;
6774                         break;
6775                 default:
6776                         fprintf(stderr, "%s: invalid option '%c'\n",
6777                                 progname, optopt);
6778                         return CMD_HELP;
6779                 }
6780         }
6781
6782         if (phc.assign_projid && op == LFS_PROJECT_LIST) {
6783                 op = LFS_PROJECT_SET;
6784                 phc.set_projid = true;
6785         } else if (phc.assign_projid && op == LFS_PROJECT_SET) {
6786                 phc.set_projid = true;
6787         }
6788
6789         switch (op) {
6790         case LFS_PROJECT_CHECK:
6791                 if (phc.keep_projid) {
6792                         fprintf(stderr,
6793                                 "%s: '-k' is useless together with '-c'\n",
6794                                 progname);
6795                         return CMD_HELP;
6796                 }
6797                 break;
6798         case LFS_PROJECT_CLEAR:
6799                 if (!phc.newline) {
6800                         fprintf(stderr,
6801                                 "%s: '-0' is useless together with '-C'\n",
6802                                 progname);
6803                         return CMD_HELP;
6804                 }
6805                 if (phc.assign_projid) {
6806                         fprintf(stderr,
6807                                 "%s: '-p' is useless together with '-C'\n",
6808                                 progname);
6809                         return CMD_HELP;
6810                 }
6811                 break;
6812         case LFS_PROJECT_SET:
6813                 if (!phc.newline) {
6814                         fprintf(stderr,
6815                                 "%s: '-0' is useless together with '-s'\n",
6816                                 progname);
6817                         return CMD_HELP;
6818                 }
6819                 if (phc.keep_projid) {
6820                         fprintf(stderr,
6821                                 "%s: '-k' is useless together with '-s'\n",
6822                                 progname);
6823                         return CMD_HELP;
6824                 }
6825                 break;
6826         default:
6827                 if (!phc.newline) {
6828                         fprintf(stderr,
6829                                 "%s: '-0' is useless for list operations\n",
6830                                 progname);
6831                         return CMD_HELP;
6832                 }
6833                 break;
6834         }
6835
6836         argv += optind;
6837         argc -= optind;
6838         if (argc == 0) {
6839                 fprintf(stderr, "%s: missing file or directory target(s)\n",
6840                         progname);
6841                 return CMD_HELP;
6842         }
6843
6844         for (i = 0; i < argc; i++) {
6845                 switch (op) {
6846                 case LFS_PROJECT_CHECK:
6847                         err = lfs_project_check(argv[i], &phc);
6848                         break;
6849                 case LFS_PROJECT_LIST:
6850                         err = lfs_project_list(argv[i], &phc);
6851                         break;
6852                 case LFS_PROJECT_CLEAR:
6853                         err = lfs_project_clear(argv[i], &phc);
6854                         break;
6855                 case LFS_PROJECT_SET:
6856                         err = lfs_project_set(argv[i], &phc);
6857                         break;
6858                 default:
6859                         break;
6860                 }
6861                 if (err && !ret)
6862                         ret = err;
6863         }
6864
6865         return ret;
6866 }
6867
6868 static int lfs_quota(int argc, char **argv)
6869 {
6870         int c;
6871         char *mnt, *name = NULL;
6872         struct if_quotactl qctl = { .qc_cmd = LUSTRE_Q_GETQUOTA,
6873                                     .qc_type = ALLQUOTA };
6874         char *obd_uuid = (char *)qctl.obd_uuid.uuid;
6875         int rc = 0, rc1 = 0, verbose = 0, quiet = 0;
6876         char *endptr;
6877         __u32 valid = QC_GENERAL, idx = 0;
6878         bool human_readable = false;
6879         bool show_default = false;
6880         int qtype;
6881
6882         while ((c = getopt(argc, argv, "gGi:I:o:pPqtuUvh")) != -1) {
6883                 switch (c) {
6884                 case 'U':
6885                         show_default = true;
6886                 case 'u':
6887                         qtype = USRQUOTA;
6888                         goto quota_type;
6889                 case 'G':
6890                         show_default = true;
6891                 case 'g':
6892                         qtype = GRPQUOTA;
6893                         goto quota_type;
6894                 case 'P':
6895                         show_default = true;
6896                 case 'p':
6897                         qtype = PRJQUOTA;
6898 quota_type:
6899                         if (qctl.qc_type != ALLQUOTA) {
6900                                 fprintf(stderr,
6901                                         "%s quota: only one of -u, -g, or -p may be specified\n",
6902                                         progname);
6903                                 return CMD_HELP;
6904                         }
6905                         qctl.qc_type = qtype;
6906                         break;
6907                 case 't':
6908                         qctl.qc_cmd = LUSTRE_Q_GETINFO;
6909                         break;
6910                 case 'o':
6911                         valid = qctl.qc_valid = QC_UUID;
6912                         snprintf(obd_uuid, sizeof(qctl.obd_uuid), "%s", optarg);
6913                         break;
6914                 case 'i':
6915                         valid = qctl.qc_valid = QC_MDTIDX;
6916                         idx = qctl.qc_idx = atoi(optarg);
6917                         if (idx == 0 && *optarg != '0') {
6918                                 fprintf(stderr,
6919                                         "%s quota: invalid MDT index '%s'\n",
6920                                         progname, optarg);
6921                                 return CMD_HELP;
6922                         }
6923                         break;
6924                 case 'I':
6925                         valid = qctl.qc_valid = QC_OSTIDX;
6926                         idx = qctl.qc_idx = atoi(optarg);
6927                         if (idx == 0 && *optarg != '0') {
6928                                 fprintf(stderr,
6929                                         "%s quota: invalid OST index '%s'\n",
6930                                         progname, optarg);
6931                                 return CMD_HELP;
6932                         }
6933                         break;
6934                 case 'v':
6935                         verbose = 1;
6936                         break;
6937                 case 'q':
6938                         quiet = 1;
6939                         break;
6940                 case 'h':
6941                         human_readable = true;
6942                         break;
6943                 default:
6944                         fprintf(stderr, "%s quota: unrecognized option '%s'\n",
6945                                 progname, argv[optind - 1]);
6946                         return CMD_HELP;
6947                 }
6948         }
6949
6950         /* current uid/gid info for "lfs quota /path/to/lustre/mount" */
6951         if (qctl.qc_cmd == LUSTRE_Q_GETQUOTA && qctl.qc_type == ALLQUOTA &&
6952             optind == argc - 1 && !show_default) {
6953
6954                 qctl.qc_cmd = LUSTRE_Q_GETQUOTA;
6955                 qctl.qc_valid = valid;
6956                 qctl.qc_idx = idx;
6957
6958                 for (qtype = USRQUOTA; qtype <= GRPQUOTA; qtype++) {
6959                         qctl.qc_type = qtype;
6960                         if (qtype == USRQUOTA) {
6961                                 qctl.qc_id = geteuid();
6962                                 rc = uid2name(&name, qctl.qc_id);
6963                         } else {
6964                                 qctl.qc_id = getegid();
6965                                 rc = gid2name(&name, qctl.qc_id);
6966                         }
6967                         if (rc)
6968                                 name = "<unknown>";
6969                         mnt = argv[optind];
6970                         rc1 = get_print_quota(mnt, name, &qctl, verbose, quiet,
6971                                               human_readable, show_default);
6972                         if (rc1 && !rc)
6973                                 rc = rc1;
6974                 }
6975                 return rc;
6976         /* lfs quota -u username /path/to/lustre/mount */
6977         } else if (qctl.qc_cmd == LUSTRE_Q_GETQUOTA) {
6978                 /* options should be followed by u/g-name and mntpoint */
6979                 if ((!show_default && optind + 2 != argc) ||
6980                     (show_default && optind + 1 != argc) ||
6981                     qctl.qc_type == ALLQUOTA) {
6982                         fprintf(stderr,
6983                                 "%s quota: name and mount point must be specified\n",
6984                                 progname);
6985                         return CMD_HELP;
6986                 }
6987
6988                 if (!show_default) {
6989                         name = argv[optind++];
6990                         switch (qctl.qc_type) {
6991                         case USRQUOTA:
6992                                 rc = name2uid(&qctl.qc_id, name);
6993                                 break;
6994                         case GRPQUOTA:
6995                                 rc = name2gid(&qctl.qc_id, name);
6996                                 break;
6997                         case PRJQUOTA:
6998                                 rc = name2projid(&qctl.qc_id, name);
6999                                 break;
7000                         default:
7001                                 rc = -ENOTSUP;
7002                                 break;
7003                         }
7004                 } else {
7005                         qctl.qc_valid = QC_GENERAL;
7006                         qctl.qc_cmd = LUSTRE_Q_GETDEFAULT;
7007                         qctl.qc_id = 0;
7008                 }
7009
7010                 if (rc) {
7011                         qctl.qc_id = strtoul(name, &endptr, 10);
7012                         if (*endptr != '\0') {
7013                                 fprintf(stderr, "%s quota: invalid id '%s'\n",
7014                                         progname, name);
7015                                 return CMD_HELP;
7016                         }
7017                 }
7018         } else if (optind + 1 != argc || qctl.qc_type == ALLQUOTA) {
7019                 fprintf(stderr, "%s quota: missing quota info argument(s)\n",
7020                         progname);
7021                 return CMD_HELP;
7022         }
7023
7024         mnt = argv[optind];
7025         rc = get_print_quota(mnt, name, &qctl, verbose, quiet,
7026                              human_readable, show_default);
7027         return rc;
7028 }
7029 #endif /* HAVE_SYS_QUOTA_H! */
7030
7031 static int flushctx_ioctl(char *mp)
7032 {
7033         int fd, rc;
7034
7035         fd = open(mp, O_RDONLY);
7036         if (fd == -1) {
7037                 fprintf(stderr, "flushctx: error open %s: %s\n",
7038                         mp, strerror(errno));
7039                 return -1;
7040         }
7041
7042         rc = ioctl(fd, LL_IOC_FLUSHCTX);
7043         if (rc == -1)
7044                 fprintf(stderr, "flushctx: error ioctl %s: %s\n",
7045                         mp, strerror(errno));
7046
7047         close(fd);
7048         return rc;
7049 }
7050
7051 static int lfs_flushctx(int argc, char **argv)
7052 {
7053         int     kdestroy = 0, c;
7054         char    mntdir[PATH_MAX] = {'\0'};
7055         int     index = 0;
7056         int     rc = 0;
7057
7058         while ((c = getopt(argc, argv, "k")) != -1) {
7059                 switch (c) {
7060                 case 'k':
7061                         kdestroy = 1;
7062                         break;
7063                 default:
7064                         fprintf(stderr, "error: %s: option '-%c' "
7065                                         "unrecognized\n", argv[0], c);
7066                         return CMD_HELP;
7067                 }
7068         }
7069
7070         if (kdestroy) {
7071             if ((rc = system("kdestroy > /dev/null")) != 0) {
7072                 rc = WEXITSTATUS(rc);
7073                 fprintf(stderr, "error destroying tickets: %d, continuing\n", rc);
7074             }
7075         }
7076
7077         if (optind >= argc) {
7078                 /* flush for all mounted lustre fs. */
7079                 while (!llapi_search_mounts(NULL, index++, mntdir, NULL)) {
7080                         /* Check if we have a mount point */
7081                         if (mntdir[0] == '\0')
7082                                 continue;
7083
7084                         if (flushctx_ioctl(mntdir))
7085                                 rc = -1;
7086
7087                         mntdir[0] = '\0'; /* avoid matching in next loop */
7088                 }
7089         } else {
7090                 /* flush fs as specified */
7091                 while (optind < argc) {
7092                         if (flushctx_ioctl(argv[optind++]))
7093                                 rc = -1;
7094                 }
7095         }
7096         return rc;
7097 }
7098
7099 static int lfs_changelog(int argc, char **argv)
7100 {
7101         void *changelog_priv;
7102         struct changelog_rec *rec;
7103         long long startrec = 0, endrec = 0;
7104         char *mdd;
7105         struct option long_opts[] = {
7106                 { .val = 'f', .name = "follow", .has_arg = no_argument },
7107                 { .name = NULL } };
7108         char short_opts[] = "f";
7109         int rc, follow = 0;
7110
7111         while ((rc = getopt_long(argc, argv, short_opts,
7112                 long_opts, NULL)) != -1) {
7113                 switch (rc) {
7114                 case 'f':
7115                         follow++;
7116                         break;
7117                 default:
7118                         fprintf(stderr,
7119                                 "%s changelog: unrecognized option '%s'\n",
7120                                 progname, argv[optind - 1]);
7121                         return CMD_HELP;
7122                 }
7123         }
7124         if (optind >= argc) {
7125                 fprintf(stderr, "%s changelog: mdtname must be specified\n",
7126                         progname);
7127                 return CMD_HELP;
7128         }
7129
7130         mdd = argv[optind++];
7131         if (argc > optind)
7132                 startrec = strtoll(argv[optind++], NULL, 10);
7133         if (argc > optind)
7134                 endrec = strtoll(argv[optind++], NULL, 10);
7135
7136         rc = llapi_changelog_start(&changelog_priv,
7137                                    CHANGELOG_FLAG_BLOCK |
7138                                    CHANGELOG_FLAG_JOBID |
7139                                    CHANGELOG_FLAG_EXTRA_FLAGS |
7140                                    (follow ? CHANGELOG_FLAG_FOLLOW : 0),
7141                                    mdd, startrec);
7142         if (rc < 0) {
7143                 fprintf(stderr, "%s changelog: cannot start changelog: %s\n",
7144                         progname, strerror(errno = -rc));
7145                 return rc;
7146         }
7147
7148         rc = llapi_changelog_set_xflags(changelog_priv,
7149                                         CHANGELOG_EXTRA_FLAG_UIDGID |
7150                                         CHANGELOG_EXTRA_FLAG_NID |
7151                                         CHANGELOG_EXTRA_FLAG_OMODE |
7152                                         CHANGELOG_EXTRA_FLAG_XATTR);
7153         if (rc < 0) {
7154                 fprintf(stderr,
7155                         "%s changelog: cannot set xflags for changelog: %s\n",
7156                         progname, strerror(errno = -rc));
7157                 return rc;
7158         }
7159
7160         while ((rc = llapi_changelog_recv(changelog_priv, &rec)) == 0) {
7161                 time_t secs;
7162                 struct tm ts;
7163
7164                 if (endrec && rec->cr_index > endrec) {
7165                         llapi_changelog_free(&rec);
7166                         break;
7167                 }
7168                 if (rec->cr_index < startrec) {
7169                         llapi_changelog_free(&rec);
7170                         continue;
7171                 }
7172
7173                 secs = rec->cr_time >> 30;
7174                 gmtime_r(&secs, &ts);
7175                 printf("%ju %02d%-5s %02d:%02d:%02d.%09d %04d.%02d.%02d "
7176                        "0x%x t="DFID, (uintmax_t)rec->cr_index, rec->cr_type,
7177                        changelog_type2str(rec->cr_type),
7178                        ts.tm_hour, ts.tm_min, ts.tm_sec,
7179                        (int)(rec->cr_time & ((1 << 30) - 1)),
7180                        ts.tm_year + 1900, ts.tm_mon + 1, ts.tm_mday,
7181                        rec->cr_flags & CLF_FLAGMASK, PFID(&rec->cr_tfid));
7182
7183                 if (rec->cr_flags & CLF_JOBID) {
7184                         struct changelog_ext_jobid *jid =
7185                                 changelog_rec_jobid(rec);
7186
7187                         if (jid->cr_jobid[0] != '\0')
7188                                 printf(" j=%s", jid->cr_jobid);
7189                 }
7190
7191                 if (rec->cr_flags & CLF_EXTRA_FLAGS) {
7192                         struct changelog_ext_extra_flags *ef =
7193                                 changelog_rec_extra_flags(rec);
7194
7195                         printf(" ef=0x%llx", ef->cr_extra_flags);
7196
7197                         if (ef->cr_extra_flags & CLFE_UIDGID) {
7198                                 struct changelog_ext_uidgid *uidgid =
7199                                         changelog_rec_uidgid(rec);
7200
7201                                 printf(" u=%llu:%llu",
7202                                        uidgid->cr_uid, uidgid->cr_gid);
7203                         }
7204                         if (ef->cr_extra_flags & CLFE_NID) {
7205                                 struct changelog_ext_nid *nid =
7206                                         changelog_rec_nid(rec);
7207
7208                                 printf(" nid=%s",
7209                                        libcfs_nid2str(nid->cr_nid));
7210                         }
7211
7212                         if (ef->cr_extra_flags & CLFE_OPEN) {
7213                                 struct changelog_ext_openmode *omd =
7214                                         changelog_rec_openmode(rec);
7215                                 char mode[] = "---";
7216
7217                                 /* exec mode must be exclusive */
7218                                 if (omd->cr_openflags & MDS_FMODE_EXEC) {
7219                                         mode[2] = 'x';
7220                                 } else {
7221                                         if (omd->cr_openflags & MDS_FMODE_READ)
7222                                                 mode[0] = 'r';
7223                                         if (omd->cr_openflags &
7224                                             (MDS_FMODE_WRITE |
7225                                              MDS_OPEN_TRUNC |
7226                                              MDS_OPEN_APPEND))
7227                                                 mode[1] = 'w';
7228                                 }
7229
7230                                 if (strcmp(mode, "---") != 0)
7231                                         printf(" m=%s", mode);
7232
7233                         }
7234
7235                         if (ef->cr_extra_flags & CLFE_XATTR) {
7236                                 struct changelog_ext_xattr *xattr =
7237                                         changelog_rec_xattr(rec);
7238
7239                                 if (xattr->cr_xattr[0] != '\0')
7240                                         printf(" x=%s", xattr->cr_xattr);
7241                         }
7242                 }
7243
7244                 if (rec->cr_namelen)
7245                         printf(" p="DFID" %.*s", PFID(&rec->cr_pfid),
7246                                rec->cr_namelen, changelog_rec_name(rec));
7247
7248                 if (rec->cr_flags & CLF_RENAME) {
7249                         struct changelog_ext_rename *rnm =
7250                                 changelog_rec_rename(rec);
7251
7252                         if (!fid_is_zero(&rnm->cr_sfid))
7253                                 printf(" s="DFID" sp="DFID" %.*s",
7254                                        PFID(&rnm->cr_sfid),
7255                                        PFID(&rnm->cr_spfid),
7256                                        (int)changelog_rec_snamelen(rec),
7257                                        changelog_rec_sname(rec));
7258                 }
7259                 printf("\n");
7260
7261                 llapi_changelog_free(&rec);
7262         }
7263
7264         llapi_changelog_fini(&changelog_priv);
7265
7266         if (rc < 0)
7267                 fprintf(stderr, "%s changelog: cannot access changelog: %s\n",
7268                         progname, strerror(errno = -rc));
7269
7270         return (rc == 1 ? 0 : rc);
7271 }
7272
7273 static int lfs_changelog_clear(int argc, char **argv)
7274 {
7275         long long endrec;
7276         int rc;
7277
7278         if (argc != 4)
7279                 return CMD_HELP;
7280
7281         endrec = strtoll(argv[3], NULL, 10);
7282
7283         rc = llapi_changelog_clear(argv[1], argv[2], endrec);
7284
7285         if (rc == -EINVAL)
7286                 fprintf(stderr, "%s: record out of range: %llu\n",
7287                         argv[0], endrec);
7288         else if (rc == -ENOENT)
7289                 fprintf(stderr, "%s: no changelog user: %s\n",
7290                         argv[0], argv[2]);
7291         else if (rc)
7292                 fprintf(stderr, "%s error: %s\n", argv[0],
7293                         strerror(-rc));
7294
7295         if (rc)
7296                 errno = -rc;
7297
7298         return rc;
7299 }
7300
7301 static int lfs_fid2path(int argc, char **argv)
7302 {
7303         struct option long_opts[] = {
7304                 { .val = 'c',   .name = "cur",  .has_arg = no_argument },
7305                 { .val = 'l',   .name = "link", .has_arg = required_argument },
7306                 { .val = 'r',   .name = "rec",  .has_arg = required_argument },
7307                 { .name = NULL } };
7308         char  short_opts[] = "cl:r:";
7309         char *device, *fid, *path;
7310         long long recno = -1;
7311         int linkno = -1;
7312         int lnktmp;
7313         int printcur = 0;
7314         int rc = 0;
7315         char *endptr = NULL;
7316
7317         while ((rc = getopt_long(argc, argv, short_opts,
7318                 long_opts, NULL)) != -1) {
7319                 switch (rc) {
7320                 case 'c':
7321                         printcur++;
7322                         break;
7323                 case 'l':
7324                         linkno = strtol(optarg, &endptr, 10);
7325                         if (*endptr != '\0') {
7326                                 fprintf(stderr,
7327                                         "%s fid2path: invalid linkno '%s'\n",
7328                                         progname, optarg);
7329                                 return CMD_HELP;
7330                         }
7331                         break;
7332                 case 'r':
7333                         recno = strtoll(optarg, &endptr, 10);
7334                         if (*endptr != '\0') {
7335                                 fprintf(stderr,
7336                                         "%s fid2path: invalid recno '%s'\n",
7337                                         progname, optarg);
7338                                 return CMD_HELP;
7339                         }
7340                         break;
7341                 default:
7342                         fprintf(stderr,
7343                                 "%s fid2path: unrecognized option '%s'\n",
7344                                 progname, argv[optind - 1]);
7345                         return CMD_HELP;
7346                 }
7347         }
7348
7349         if (argc < 3) {
7350                 fprintf(stderr,
7351                         "%s fid2path: <fsname|rootpath> and <fid>... must be specified\n",
7352                         progname);
7353                 return CMD_HELP;
7354         }
7355
7356         device = argv[optind++];
7357         path = calloc(1, PATH_MAX);
7358         if (path == NULL) {
7359                 rc = -errno;
7360                 fprintf(stderr,
7361                         "%s fid2path: cannot allocate memory for path: %s\n",
7362                         progname, strerror(-rc));
7363                 return rc;
7364         }
7365
7366         rc = 0;
7367         while (optind < argc) {
7368                 fid = argv[optind++];
7369
7370                 lnktmp = (linkno >= 0) ? linkno : 0;
7371                 while (1) {
7372                         int oldtmp = lnktmp;
7373                         long long rectmp = recno;
7374                         int rc2;
7375                         rc2 = llapi_fid2path(device, fid, path, PATH_MAX,
7376                                              &rectmp, &lnktmp);
7377                         if (rc2 < 0) {
7378                                 fprintf(stderr,
7379                                         "%s fid2path: cannot find '%s': %s\n",
7380                                         progname, fid, strerror(errno = -rc2));
7381                                 if (rc == 0)
7382                                         rc = rc2;
7383                                 break;
7384                         }
7385
7386                         if (printcur)
7387                                 fprintf(stdout, "%lld ", rectmp);
7388                         if (device[0] == '/') {
7389                                 fprintf(stdout, "%s", device);
7390                                 if (device[strlen(device) - 1] != '/')
7391                                         fprintf(stdout, "/");
7392                         } else if (path[0] == '\0') {
7393                                 fprintf(stdout, "/");
7394                         }
7395                         fprintf(stdout, "%s\n", path);
7396
7397                         if (linkno >= 0)
7398                                 /* specified linkno */
7399                                 break;
7400                         if (oldtmp == lnktmp)
7401                                 /* no more links */
7402                                 break;
7403                 }
7404         }
7405
7406         free(path);
7407         return rc;
7408 }
7409
7410 static int lfs_path2fid(int argc, char **argv)
7411 {
7412         struct option long_opts[] = {
7413                 { .val = 'p', .name = "parents", .has_arg = no_argument },
7414                 { .name = NULL } };
7415         char            **path;
7416         const char        short_opts[] = "p";
7417         const char       *sep = "";
7418         struct lu_fid     fid;
7419         int               rc = 0;
7420         bool              show_parents = false;
7421
7422         while ((rc = getopt_long(argc, argv, short_opts,
7423                                  long_opts, NULL)) != -1) {
7424                 switch (rc) {
7425                 case 'p':
7426                         show_parents = true;
7427                         break;
7428                 default:
7429                         fprintf(stderr,
7430                                 "%s path2fid: unrecognized option '%s'\n",
7431                                 progname, argv[optind - 1]);
7432                         return CMD_HELP;
7433                 }
7434         }
7435
7436         if (optind > argc - 1) {
7437                 fprintf(stderr, "%s path2fid: FILE... must be specified\n",
7438                         progname);
7439                 return CMD_HELP;
7440         }
7441         else if (optind < argc - 1)
7442                 sep = ": ";
7443
7444         rc = 0;
7445         for (path = argv + optind; *path != NULL; path++) {
7446                 int err = 0;
7447                 if (!show_parents) {
7448                         err = llapi_path2fid(*path, &fid);
7449                         if (!err)
7450                                 printf("%s%s"DFID"\n",
7451                                        *sep != '\0' ? *path : "", sep,
7452                                        PFID(&fid));
7453                 } else {
7454                         char            name[NAME_MAX + 1];
7455                         unsigned int    linkno = 0;
7456
7457                         while ((err = llapi_path2parent(*path, linkno, &fid,
7458                                                 name, sizeof(name))) == 0) {
7459                                 if (*sep != '\0' && linkno == 0)
7460                                         printf("%s%s", *path, sep);
7461
7462                                 printf("%s"DFID"/%s", linkno != 0 ? "\t" : "",
7463                                        PFID(&fid), name);
7464                                 linkno++;
7465                         }
7466
7467                         /* err == -ENODATA is end-of-loop */
7468                         if (linkno > 0 && err == -ENODATA) {
7469                                 printf("\n");
7470                                 err = 0;
7471                         }
7472                 }
7473
7474                 if (err) {
7475                         fprintf(stderr,
7476                                 "%s path2fid: cannot get %sfid for '%s': %s\n",
7477                                 progname, show_parents ? "parent " : "", *path,
7478                                 strerror(-err));
7479                         if (rc == 0) {
7480                                 rc = err;
7481                                 errno = -err;
7482                         }
7483                 }
7484         }
7485
7486         return rc;
7487 }
7488
7489 static int lfs_data_version(int argc, char **argv)
7490 {
7491         char *path;
7492         __u64 data_version;
7493         int fd;
7494         int rc;
7495         int c;
7496         int data_version_flags = LL_DV_RD_FLUSH; /* Read by default */
7497
7498         if (argc < 2) {
7499                 fprintf(stderr, "%s data_version: FILE must be specified\n",
7500                         progname);
7501                 return CMD_HELP;
7502         }
7503
7504         while ((c = getopt(argc, argv, "nrw")) != -1) {
7505                 switch (c) {
7506                 case 'n':
7507                         data_version_flags = 0;
7508                         break;
7509                 case 'r':
7510                         data_version_flags |= LL_DV_RD_FLUSH;
7511                         break;
7512                 case 'w':
7513                         data_version_flags |= LL_DV_WR_FLUSH;
7514                         break;
7515                 default:
7516                         fprintf(stderr,
7517                                 "%s data_version: unrecognized option '%s'\n",
7518                                 progname, argv[optind - 1]);
7519                         return CMD_HELP;
7520                 }
7521         }
7522         if (optind == argc) {
7523                 fprintf(stderr, "%s data_version: FILE must be specified\n",
7524                         progname);
7525                 return CMD_HELP;
7526         }
7527
7528         path = argv[optind];
7529         fd = open(path, O_RDONLY);
7530         if (fd < 0) {
7531                 rc = -errno;
7532                 fprintf(stderr, "%s data_version: cannot open file '%s': %s\n",
7533                         progname, path, strerror(-rc));
7534                 return rc;
7535         }
7536
7537         rc = llapi_get_data_version(fd, &data_version, data_version_flags);
7538         if (rc < 0)
7539                 fprintf(stderr,
7540                         "%s data_version: cannot get version for '%s': %s\n",
7541                         progname, path, strerror(-rc));
7542         else
7543                 printf("%ju" "\n", (uintmax_t)data_version);
7544
7545         close(fd);
7546         return rc;
7547 }
7548
7549 static int lfs_hsm_state(int argc, char **argv)
7550 {
7551         int rc;
7552         int i = 1;
7553         char *path;
7554         struct hsm_user_state hus;
7555
7556         if (argc < 2)
7557                 return CMD_HELP;
7558
7559         do {
7560                 path = argv[i];
7561
7562                 rc = llapi_hsm_state_get(path, &hus);
7563                 if (rc) {
7564                         fprintf(stderr, "can't get hsm state for %s: %s\n",
7565                                 path, strerror(errno = -rc));
7566                         return rc;
7567                 }
7568
7569                 /* Display path name and status flags */
7570                 printf("%s: (0x%08x)", path, hus.hus_states);
7571
7572                 if (hus.hus_states & HS_RELEASED)
7573                         printf(" released");
7574                 if (hus.hus_states & HS_EXISTS)
7575                         printf(" exists");
7576                 if (hus.hus_states & HS_DIRTY)
7577                         printf(" dirty");
7578                 if (hus.hus_states & HS_ARCHIVED)
7579                         printf(" archived");
7580                 /* Display user-settable flags */
7581                 if (hus.hus_states & HS_NORELEASE)
7582                         printf(" never_release");
7583                 if (hus.hus_states & HS_NOARCHIVE)
7584                         printf(" never_archive");
7585                 if (hus.hus_states & HS_LOST)
7586                         printf(" lost_from_hsm");
7587
7588                 if (hus.hus_archive_id != 0)
7589                         printf(", archive_id:%d", hus.hus_archive_id);
7590                 printf("\n");
7591
7592         } while (++i < argc);
7593
7594         return 0;
7595 }
7596
7597 #define LFS_HSM_SET   0
7598 #define LFS_HSM_CLEAR 1
7599
7600 /**
7601  * Generic function to set or clear HSM flags.
7602  * Used by hsm_set and hsm_clear.
7603  *
7604  * @mode  if LFS_HSM_SET, set the flags, if LFS_HSM_CLEAR, clear the flags.
7605  */
7606 static int lfs_hsm_change_flags(int argc, char **argv, int mode)
7607 {
7608         struct option long_opts[] = {
7609         { .val = 'A',   .name = "archived",     .has_arg = no_argument },
7610         { .val = 'a',   .name = "noarchive",    .has_arg = no_argument },
7611         { .val = 'd',   .name = "dirty",        .has_arg = no_argument },
7612         { .val = 'e',   .name = "exists",       .has_arg = no_argument },
7613         { .val = 'l',   .name = "lost",         .has_arg = no_argument },
7614         { .val = 'r',   .name = "norelease",    .has_arg = no_argument },
7615         { .val = 'i',   .name = "archive-id",   .has_arg = required_argument },
7616         { .name = NULL } };
7617         char short_opts[] = "lraAdei:";
7618         __u64 mask = 0;
7619         int c, rc;
7620         char *path;
7621         __u32 archive_id = 0;
7622         char *end = NULL;
7623
7624         if (argc < 3)
7625                 return CMD_HELP;
7626
7627         while ((c = getopt_long(argc, argv, short_opts,
7628                                 long_opts, NULL)) != -1) {
7629                 switch (c) {
7630                 case 'l':
7631                         mask |= HS_LOST;
7632                         break;
7633                 case 'a':
7634                         mask |= HS_NOARCHIVE;
7635                         break;
7636                 case 'A':
7637                         mask |= HS_ARCHIVED;
7638                         break;
7639                 case 'r':
7640                         mask |= HS_NORELEASE;
7641                         break;
7642                 case 'd':
7643                         mask |= HS_DIRTY;
7644                         break;
7645                 case 'e':
7646                         mask |= HS_EXISTS;
7647                         break;
7648                 case 'i':
7649                         archive_id = strtol(optarg, &end, 10);
7650                         if (*end != '\0') {
7651                                 fprintf(stderr, "invalid archive_id: '%s'\n",
7652                                         end);
7653                                 return CMD_HELP;
7654                         }
7655                         break;
7656                 case '?':
7657                         return CMD_HELP;
7658                 default:
7659                         fprintf(stderr, "error: %s: option '%s' unrecognized\n",
7660                                 argv[0], argv[optind - 1]);
7661                         return CMD_HELP;
7662                 }
7663         }
7664
7665         /* User should have specified a flag */
7666         if (mask == 0)
7667                 return CMD_HELP;
7668
7669         while (optind < argc) {
7670
7671                 path = argv[optind];
7672
7673                 /* If mode == 0, this means we apply the mask. */
7674                 if (mode == LFS_HSM_SET)
7675                         rc = llapi_hsm_state_set(path, mask, 0, archive_id);
7676                 else
7677                         rc = llapi_hsm_state_set(path, 0, mask, 0);
7678
7679                 if (rc != 0) {
7680                         fprintf(stderr, "Can't change hsm flags for %s: %s\n",
7681                                 path, strerror(errno = -rc));
7682                         return rc;
7683                 }
7684                 optind++;
7685         }
7686
7687         return 0;
7688 }
7689
7690 static int lfs_hsm_action(int argc, char **argv)
7691 {
7692         int                              rc;
7693         int                              i = 1;
7694         char                            *path;
7695         struct hsm_current_action        hca;
7696         struct hsm_extent                he;
7697         enum hsm_user_action             hua;
7698         enum hsm_progress_states         hps;
7699
7700         if (argc < 2)
7701                 return CMD_HELP;
7702
7703         do {
7704                 path = argv[i];
7705
7706                 rc = llapi_hsm_current_action(path, &hca);
7707                 if (rc) {
7708                         fprintf(stderr, "can't get hsm action for %s: %s\n",
7709                                 path, strerror(errno = -rc));
7710                         return rc;
7711                 }
7712                 he = hca.hca_location;
7713                 hua = hca.hca_action;
7714                 hps = hca.hca_state;
7715
7716                 printf("%s: %s", path, hsm_user_action2name(hua));
7717
7718                 /* Skip file without action */
7719                 if (hca.hca_action == HUA_NONE) {
7720                         printf("\n");
7721                         continue;
7722                 }
7723
7724                 printf(" %s ", hsm_progress_state2name(hps));
7725
7726                 if ((hps == HPS_RUNNING) &&
7727                     (hua == HUA_ARCHIVE || hua == HUA_RESTORE))
7728                         printf("(%llu bytes moved)\n",
7729                                (unsigned long long)he.length);
7730                 else if ((he.offset + he.length) == LUSTRE_EOF)
7731                         printf("(from %llu to EOF)\n",
7732                                (unsigned long long)he.offset);
7733                 else
7734                         printf("(from %llu to %llu)\n",
7735                                (unsigned long long)he.offset,
7736                                (unsigned long long)(he.offset + he.length));
7737
7738         } while (++i < argc);
7739
7740         return 0;
7741 }
7742
7743 static int lfs_hsm_set(int argc, char **argv)
7744 {
7745         return lfs_hsm_change_flags(argc, argv, LFS_HSM_SET);
7746 }
7747
7748 static int lfs_hsm_clear(int argc, char **argv)
7749 {
7750         return lfs_hsm_change_flags(argc, argv, LFS_HSM_CLEAR);
7751 }
7752
7753 /**
7754  * Check file state and return its fid, to be used by lfs_hsm_request().
7755  *
7756  * \param[in]     file      Path to file to check
7757  * \param[in,out] fid       Pointer to allocated lu_fid struct.
7758  * \param[in,out] last_dev  Pointer to last device id used.
7759  *
7760  * \return 0 on success.
7761  */
7762 static int lfs_hsm_prepare_file(const char *file, struct lu_fid *fid,
7763                                 dev_t *last_dev)
7764 {
7765         struct stat     st;
7766         int             rc;
7767
7768         rc = lstat(file, &st);
7769         if (rc) {
7770                 fprintf(stderr, "Cannot stat %s: %s\n", file, strerror(errno));
7771                 return -errno;
7772         }
7773         /* Checking for regular file as archiving as posix copytool
7774          * rejects archiving files other than regular files
7775          */
7776         if (!S_ISREG(st.st_mode)) {
7777                 fprintf(stderr, "error: \"%s\" is not a regular file\n", file);
7778                 return CMD_HELP;
7779         }
7780         /* A request should be ... */
7781         if (*last_dev != st.st_dev && *last_dev != 0) {
7782                 fprintf(stderr, "All files should be "
7783                         "on the same filesystem: %s\n", file);
7784                 return -EINVAL;
7785         }
7786         *last_dev = st.st_dev;
7787
7788         rc = llapi_path2fid(file, fid);
7789         if (rc) {
7790                 fprintf(stderr, "Cannot read FID of %s: %s\n",
7791                         file, strerror(-rc));
7792                 return rc;
7793         }
7794         return 0;
7795 }
7796
7797 /* Fill an HSM HUR item with a given file name.
7798  *
7799  * If mntpath is set, then the filename is actually a FID, and no
7800  * lookup on the filesystem will be performed.
7801  *
7802  * \param[in]  hur         the user request to fill
7803  * \param[in]  idx         index of the item inside the HUR to fill
7804  * \param[in]  mntpath     mountpoint of Lustre
7805  * \param[in]  fname       filename (if mtnpath is NULL)
7806  *                         or FID (if mntpath is set)
7807  * \param[in]  last_dev    pointer to last device id used
7808  *
7809  * \retval 0 on success
7810  * \retval CMD_HELP or a negative errno on error
7811  */
7812 static int fill_hur_item(struct hsm_user_request *hur, unsigned int idx,
7813                          const char *mntpath, const char *fname,
7814                          dev_t *last_dev)
7815 {
7816         struct hsm_user_item *hui = &hur->hur_user_item[idx];
7817         int rc;
7818
7819         hui->hui_extent.length = -1;
7820
7821         if (mntpath != NULL) {
7822                 if (*fname == '[')
7823                         fname++;
7824                 rc = sscanf(fname, SFID, RFID(&hui->hui_fid));
7825                 if (rc == 3) {
7826                         rc = 0;
7827                 } else {
7828                         fprintf(stderr, "hsm: '%s' is not a valid FID\n",
7829                                 fname);
7830                         rc = -EINVAL;
7831                 }
7832         } else {
7833                 rc = lfs_hsm_prepare_file(fname, &hui->hui_fid, last_dev);
7834         }
7835
7836         if (rc == 0)
7837                 hur->hur_request.hr_itemcount++;
7838
7839         return rc;
7840 }
7841
7842 static int lfs_hsm_request(int argc, char **argv, int action)
7843 {
7844         struct option long_opts[] = {
7845         { .val = 'a',   .name = "archive",      .has_arg = required_argument },
7846         { .val = 'D',   .name = "data",         .has_arg = required_argument },
7847         { .val = 'l',   .name = "filelist",     .has_arg = required_argument },
7848         { .val = 'm',   .name = "mntpath",      .has_arg = required_argument },
7849         { .name = NULL } };
7850         dev_t                    last_dev = 0;
7851         char                     short_opts[] = "l:D:a:m:";
7852         struct hsm_user_request *hur, *oldhur;
7853         int                      c, i;
7854         size_t                   len;
7855         int                      nbfile;
7856         char                    *line = NULL;
7857         char                    *filelist = NULL;
7858         char                     fullpath[PATH_MAX];
7859         char                    *opaque = NULL;
7860         int                      opaque_len = 0;
7861         int                      archive_id = 0;
7862         FILE                    *fp;
7863         int                      nbfile_alloc = 0;
7864         char                    *some_file = NULL;
7865         char                    *mntpath = NULL;
7866         int                      rc;
7867
7868         if (argc < 2)
7869                 return CMD_HELP;
7870
7871         while ((c = getopt_long(argc, argv, short_opts,
7872                                 long_opts, NULL)) != -1) {
7873                 switch (c) {
7874                 case 'l':
7875                         filelist = optarg;
7876                         break;
7877                 case 'D':
7878                         opaque = optarg;
7879                         break;
7880                 case 'a':
7881                         if (action != HUA_ARCHIVE &&
7882                             action != HUA_REMOVE) {
7883                                 fprintf(stderr,
7884                                         "error: -a is supported only "
7885                                         "when archiving or removing\n");
7886                                 return CMD_HELP;
7887                         }
7888                         archive_id = atoi(optarg);
7889                         break;
7890                 case 'm':
7891                         if (some_file == NULL) {
7892                                 mntpath = optarg;
7893                                 some_file = strdup(optarg);
7894                         }
7895                         break;
7896                 case '?':
7897                         return CMD_HELP;
7898                 default:
7899                         fprintf(stderr, "error: %s: option '%s' unrecognized\n",
7900                                 argv[0], argv[optind - 1]);
7901                         return CMD_HELP;
7902                 }
7903         }
7904
7905         /* All remaining args are files, so we have at least nbfile */
7906         nbfile = argc - optind;
7907
7908         if ((nbfile == 0) && (filelist == NULL))
7909                 return CMD_HELP;
7910
7911         if (opaque != NULL)
7912                 opaque_len = strlen(opaque);
7913
7914         /* Alloc the request structure with enough place to store all files
7915          * from command line. */
7916         hur = llapi_hsm_user_request_alloc(nbfile, opaque_len);
7917         if (hur == NULL) {
7918                 fprintf(stderr, "Cannot create the request: %s\n",
7919                         strerror(errno));
7920                 return errno;
7921         }
7922         nbfile_alloc = nbfile;
7923
7924         hur->hur_request.hr_action = action;
7925         hur->hur_request.hr_archive_id = archive_id;
7926         hur->hur_request.hr_flags = 0;
7927
7928         /* All remaining args are files, add them */
7929         if (nbfile != 0 && some_file == NULL)
7930                 some_file = strdup(argv[optind]);
7931
7932         for (i = 0; i < nbfile; i++) {
7933                 rc = fill_hur_item(hur, i, mntpath, argv[optind + i],
7934                                    &last_dev);
7935                 if (rc)
7936                         goto out_free;
7937         }
7938
7939         /* from here stop using nb_file, use hur->hur_request.hr_itemcount */
7940
7941         /* If a filelist was specified, read the filelist from it. */
7942         if (filelist != NULL) {
7943                 fp = fopen(filelist, "r");
7944                 if (fp == NULL) {
7945                         fprintf(stderr, "Cannot read the file list %s: %s\n",
7946                                 filelist, strerror(errno));
7947                         rc = -errno;
7948                         goto out_free;
7949                 }
7950
7951                 while ((rc = getline(&line, &len, fp)) != -1) {
7952                         /* If allocated buffer was too small, get something
7953                          * larger */
7954                         if (nbfile_alloc <= hur->hur_request.hr_itemcount) {
7955                                 ssize_t size;
7956
7957                                 nbfile_alloc = nbfile_alloc * 2 + 1;
7958                                 oldhur = hur;
7959                                 hur = llapi_hsm_user_request_alloc(nbfile_alloc,
7960                                                                    opaque_len);
7961                                 if (hur == NULL) {
7962                                         fprintf(stderr, "hsm: cannot allocate "
7963                                                 "the request: %s\n",
7964                                                 strerror(errno));
7965                                         hur = oldhur;
7966                                         rc = -errno;
7967                                         fclose(fp);
7968                                         goto out_free;
7969                                 }
7970                                 size = hur_len(oldhur);
7971                                 if (size < 0) {
7972                                         fprintf(stderr, "hsm: cannot allocate "
7973                                                 "%u files + %u bytes data\n",
7974                                             oldhur->hur_request.hr_itemcount,
7975                                             oldhur->hur_request.hr_data_len);
7976                                         free(hur);
7977                                         hur = oldhur;
7978                                         rc = -E2BIG;
7979                                         fclose(fp);
7980                                         goto out_free;
7981                                 }
7982                                 memcpy(hur, oldhur, size);
7983                                 free(oldhur);
7984                         }
7985
7986                         /* Chop CR */
7987                         if (line[strlen(line) - 1] == '\n')
7988                                 line[strlen(line) - 1] = '\0';
7989
7990                         rc = fill_hur_item(hur, hur->hur_request.hr_itemcount,
7991                                            mntpath, line, &last_dev);
7992                         if (rc) {
7993                                 fclose(fp);
7994                                 goto out_free;
7995                         }
7996
7997                         if (some_file == NULL) {
7998                                 some_file = line;
7999                                 line = NULL;
8000                         }
8001                 }
8002
8003                 rc = fclose(fp);
8004                 free(line);
8005         }
8006
8007         /* If a --data was used, add it to the request */
8008         hur->hur_request.hr_data_len = opaque_len;
8009         if (opaque != NULL)
8010                 memcpy(hur_data(hur), opaque, opaque_len);
8011
8012         /* Send the HSM request */
8013         if (realpath(some_file, fullpath) == NULL) {
8014                 fprintf(stderr, "Could not find path '%s': %s\n",
8015                         some_file, strerror(errno));
8016         }
8017         rc = llapi_hsm_request(fullpath, hur);
8018         if (rc) {
8019                 fprintf(stderr, "Cannot send HSM request (use of %s): %s\n",
8020                         some_file, strerror(-rc));
8021                 goto out_free;
8022         }
8023
8024 out_free:
8025         free(some_file);
8026         free(hur);
8027         return rc;
8028 }
8029
8030 static int lfs_hsm_archive(int argc, char **argv)
8031 {
8032         return lfs_hsm_request(argc, argv, HUA_ARCHIVE);
8033 }
8034
8035 static int lfs_hsm_restore(int argc, char **argv)
8036 {
8037         return lfs_hsm_request(argc, argv, HUA_RESTORE);
8038 }
8039
8040 static int lfs_hsm_release(int argc, char **argv)
8041 {
8042         return lfs_hsm_request(argc, argv, HUA_RELEASE);
8043 }
8044
8045 static int lfs_hsm_remove(int argc, char **argv)
8046 {
8047         return lfs_hsm_request(argc, argv, HUA_REMOVE);
8048 }
8049
8050 static int lfs_hsm_cancel(int argc, char **argv)
8051 {
8052         return lfs_hsm_request(argc, argv, HUA_CANCEL);
8053 }
8054
8055 static int lfs_swap_layouts(int argc, char **argv)
8056 {
8057         if (argc != 3)
8058                 return CMD_HELP;
8059
8060         return llapi_swap_layouts(argv[1], argv[2], 0, 0,
8061                                   SWAP_LAYOUTS_KEEP_MTIME |
8062                                   SWAP_LAYOUTS_KEEP_ATIME);
8063 }
8064
8065 static const char *const ladvise_names[] = LU_LADVISE_NAMES;
8066
8067 static const char *const lock_mode_names[] = LOCK_MODE_NAMES;
8068
8069 int lfs_get_mode(const char *string)
8070 {
8071         enum lock_mode_user mode;
8072
8073         for (mode = 0; mode < ARRAY_SIZE(lock_mode_names); mode++) {
8074                 if (lock_mode_names[mode] == NULL)
8075                         continue;
8076                 if (strcmp(string, lock_mode_names[mode]) == 0)
8077                         return mode;
8078         }
8079
8080         return -EINVAL;
8081 }
8082
8083 static enum lu_ladvise_type lfs_get_ladvice(const char *string)
8084 {
8085         enum lu_ladvise_type advice;
8086
8087         for (advice = 0;
8088              advice < ARRAY_SIZE(ladvise_names); advice++) {
8089                 if (ladvise_names[advice] == NULL)
8090                         continue;
8091                 if (strcmp(string, ladvise_names[advice]) == 0)
8092                         return advice;
8093         }
8094
8095         return LU_LADVISE_INVALID;
8096 }
8097
8098 static int lfs_ladvise(int argc, char **argv)
8099 {
8100         struct option long_opts[] = {
8101         { .val = 'a',   .name = "advice",       .has_arg = required_argument },
8102         { .val = 'b',   .name = "background",   .has_arg = no_argument },
8103         { .val = 'e',   .name = "end",          .has_arg = required_argument },
8104         { .val = 'l',   .name = "length",       .has_arg = required_argument },
8105         { .val = 'm',   .name = "mode",         .has_arg = required_argument },
8106         { .val = 's',   .name = "start",        .has_arg = required_argument },
8107         { .val = 'u',   .name = "unset",        .has_arg = no_argument },
8108         { .name = NULL } };
8109         char                     short_opts[] = "a:be:l:m:s:u";
8110         int                      c;
8111         int                      rc = 0;
8112         const char              *path;
8113         int                      fd;
8114         struct llapi_lu_ladvise  advice;
8115         enum lu_ladvise_type     advice_type = LU_LADVISE_INVALID;
8116         unsigned long long       start = 0;
8117         unsigned long long       end = LUSTRE_EOF;
8118         unsigned long long       length = 0;
8119         unsigned long long       size_units;
8120         unsigned long long       flags = 0;
8121         int                      mode = 0;
8122
8123         optind = 0;
8124         while ((c = getopt_long(argc, argv, short_opts,
8125                                 long_opts, NULL)) != -1) {
8126                 switch (c) {
8127                 case 'a':
8128                         advice_type = lfs_get_ladvice(optarg);
8129                         if (advice_type == LU_LADVISE_INVALID) {
8130                                 fprintf(stderr, "%s: invalid advice type "
8131                                         "'%s'\n", argv[0], optarg);
8132                                 fprintf(stderr, "Valid types:");
8133
8134                                 for (advice_type = 0;
8135                                      advice_type < ARRAY_SIZE(ladvise_names);
8136                                      advice_type++) {
8137                                         if (ladvise_names[advice_type] == NULL)
8138                                                 continue;
8139                                         fprintf(stderr, " %s",
8140                                                 ladvise_names[advice_type]);
8141                                 }
8142                                 fprintf(stderr, "\n");
8143
8144                                 return CMD_HELP;
8145                         }
8146                         break;
8147                 case 'b':
8148                         flags |= LF_ASYNC;
8149                         break;
8150                 case 'u':
8151                         flags |= LF_UNSET;
8152                         break;
8153                 case 'e':
8154                         size_units = 1;
8155                         rc = llapi_parse_size(optarg, &end,
8156                                               &size_units, 0);
8157                         if (rc) {
8158                                 fprintf(stderr, "%s: bad end offset '%s'\n",
8159                                         argv[0], optarg);
8160                                 return CMD_HELP;
8161                         }
8162                         break;
8163                 case 's':
8164                         size_units = 1;
8165                         rc = llapi_parse_size(optarg, &start,
8166                                               &size_units, 0);
8167                         if (rc) {
8168                                 fprintf(stderr, "%s: bad start offset "
8169                                         "'%s'\n", argv[0], optarg);
8170                                 return CMD_HELP;
8171                         }
8172                         break;
8173                 case 'l':
8174                         size_units = 1;
8175                         rc = llapi_parse_size(optarg, &length,
8176                                               &size_units, 0);
8177                         if (rc) {
8178                                 fprintf(stderr, "%s: bad length '%s'\n",
8179                                         argv[0], optarg);
8180                                 return CMD_HELP;
8181                         }
8182                         break;
8183                 case 'm':
8184                         mode = lfs_get_mode(optarg);
8185                         if (mode < 0) {
8186                                 fprintf(stderr, "%s: bad mode '%s', valid "
8187                                                  "modes are READ or WRITE\n",
8188                                         argv[0], optarg);
8189                                 return CMD_HELP;
8190                         }
8191                         break;
8192                 case '?':
8193                         return CMD_HELP;
8194                 default:
8195                         fprintf(stderr, "%s: option '%s' unrecognized\n",
8196                                 argv[0], argv[optind - 1]);
8197                         return CMD_HELP;
8198                 }
8199         }
8200
8201         if (advice_type == LU_LADVISE_INVALID) {
8202                 fprintf(stderr, "%s: please give an advice type\n", argv[0]);
8203                 fprintf(stderr, "Valid types:");
8204                 for (advice_type = 0; advice_type < ARRAY_SIZE(ladvise_names);
8205                      advice_type++) {
8206                         if (ladvise_names[advice_type] == NULL)
8207                                 continue;
8208                         fprintf(stderr, " %s", ladvise_names[advice_type]);
8209                 }
8210                 fprintf(stderr, "\n");
8211                 return CMD_HELP;
8212         }
8213
8214         if (advice_type == LU_LADVISE_LOCKNOEXPAND) {
8215                 fprintf(stderr, "%s: Lock no expand advice is a per file "
8216                                  "descriptor advice, so when called from lfs, "
8217                                  "it does nothing.\n", argv[0]);
8218                 return CMD_HELP;
8219         }
8220
8221         if (argc <= optind) {
8222                 fprintf(stderr, "%s: please give one or more file names\n",
8223                         argv[0]);
8224                 return CMD_HELP;
8225         }
8226
8227         if (end != LUSTRE_EOF && length != 0 && end != start + length) {
8228                 fprintf(stderr, "%s: conflicting arguments of -l and -e\n",
8229                         argv[0]);
8230                 return CMD_HELP;
8231         }
8232
8233         if (end == LUSTRE_EOF && length != 0)
8234                 end = start + length;
8235
8236         if (end <= start) {
8237                 fprintf(stderr, "%s: range [%llu, %llu] is invalid\n",
8238                         argv[0], start, end);
8239                 return CMD_HELP;
8240         }
8241
8242         if (advice_type != LU_LADVISE_LOCKAHEAD && mode != 0) {
8243                 fprintf(stderr, "%s: mode is only valid with lockahead\n",
8244                         argv[0]);
8245                 return CMD_HELP;
8246         }
8247
8248         if (advice_type == LU_LADVISE_LOCKAHEAD && mode == 0) {
8249                 fprintf(stderr, "%s: mode is required with lockahead\n",
8250                         argv[0]);
8251                 return CMD_HELP;
8252         }
8253
8254         while (optind < argc) {
8255                 int rc2;
8256
8257                 path = argv[optind++];
8258
8259                 fd = open(path, O_RDONLY);
8260                 if (fd < 0) {
8261                         fprintf(stderr, "%s: cannot open file '%s': %s\n",
8262                                 argv[0], path, strerror(errno));
8263                         rc2 = -errno;
8264                         goto next;
8265                 }
8266
8267                 advice.lla_start = start;
8268                 advice.lla_end = end;
8269                 advice.lla_advice = advice_type;
8270                 advice.lla_value1 = 0;
8271                 advice.lla_value2 = 0;
8272                 advice.lla_value3 = 0;
8273                 advice.lla_value4 = 0;
8274                 if (advice_type == LU_LADVISE_LOCKAHEAD) {
8275                         advice.lla_lockahead_mode = mode;
8276                         advice.lla_peradvice_flags = flags;
8277                 }
8278
8279                 rc2 = llapi_ladvise(fd, flags, 1, &advice);
8280                 close(fd);
8281                 if (rc2 < 0) {
8282                         fprintf(stderr, "%s: cannot give advice '%s' to file "
8283                                 "'%s': %s\n", argv[0],
8284                                 ladvise_names[advice_type],
8285                                 path, strerror(errno));
8286
8287                         goto next;
8288                 }
8289
8290 next:
8291                 if (rc == 0 && rc2 < 0)
8292                         rc = rc2;
8293         }
8294         return rc;
8295 }
8296
8297 static const char *const heat_names[] = LU_HEAT_NAMES;
8298
8299 static int lfs_heat_get(int argc, char **argv)
8300 {
8301         struct lu_heat *heat;
8302         int rc = 0, rc2;
8303         char *path;
8304         int fd;
8305         int i;
8306
8307         if (argc <= 1)
8308                 return CMD_HELP;
8309
8310         heat = calloc(sizeof(*heat) + sizeof(__u64) * OBD_HEAT_COUNT, 1);
8311         if (!heat) {
8312                 fprintf(stderr, "%s: memory allocation failed\n", argv[0]);
8313                 return -ENOMEM;
8314         }
8315
8316         optind = 1;
8317         while (optind < argc) {
8318                 path = argv[optind++];
8319
8320                 fd = open(path, O_RDONLY);
8321                 if (fd < 0) {
8322                         fprintf(stderr, "%s: cannot open file '%s': %s\n",
8323                                 argv[0], path, strerror(errno));
8324                         rc2 = -errno;
8325                         goto next;
8326                 }
8327
8328                 heat->lh_count = OBD_HEAT_COUNT;
8329                 rc2 = llapi_heat_get(fd, heat);
8330                 close(fd);
8331                 if (rc2 < 0) {
8332                         fprintf(stderr, "%s: cannot get heat of file '%s'"
8333                                 ": %s\n", argv[0], path, strerror(errno));
8334                         goto next;
8335                 }
8336
8337                 printf("flags: %x\n", heat->lh_flags);
8338                 for (i = 0; i < heat->lh_count; i++)
8339                         printf("%s: %llu\n", heat_names[i], heat->lh_heat[i]);
8340 next:
8341                 if (rc == 0 && rc2 < 0)
8342                         rc = rc2;
8343         }
8344
8345         free(heat);
8346         return rc;
8347 }
8348
8349 static int lfs_heat_set(int argc, char **argv)
8350 {
8351         struct option long_opts[] = {
8352         { .val = 'c',   .name = "clear",        .has_arg = no_argument },
8353         { .val = 'o',   .name = "off",          .has_arg = no_argument },
8354         { .val = 'O',   .name = "on",           .has_arg = no_argument },
8355         { .name = NULL } };
8356         enum lu_heat_flag flags = 0;
8357         int rc = 0, rc2;
8358         char *path;
8359         int fd;
8360         int c;
8361
8362         if (argc <= 1)
8363                 return CMD_HELP;
8364
8365         optind = 0;
8366         while ((c = getopt_long(argc, argv, "coO", long_opts, NULL)) != -1) {
8367                 switch (c) {
8368                 case 'c':
8369                         flags |= LU_HEAT_FLAG_CLEAR;
8370                         break;
8371                 case 'o':
8372                         flags |= LU_HEAT_FLAG_CLEAR;
8373                         flags |= LU_HEAT_FLAG_OFF;
8374                         break;
8375                 case 'O':
8376                         flags &= ~LU_HEAT_FLAG_OFF;
8377                         break;
8378                 case '?':
8379                         return CMD_HELP;
8380                 default:
8381                         fprintf(stderr, "%s: option '%s' unrecognized\n",
8382                                 argv[0], argv[optind - 1]);
8383                         return CMD_HELP;
8384                 }
8385         }
8386
8387         if (argc <= optind) {
8388                 fprintf(stderr, "%s: please give one or more file names\n",
8389                         argv[0]);
8390                 return CMD_HELP;
8391         }
8392
8393         while (optind < argc) {
8394                 path = argv[optind++];
8395
8396                 fd = open(path, O_RDONLY);
8397                 if (fd < 0) {
8398                         fprintf(stderr, "%s: cannot open file '%s': %s\n",
8399                                 argv[0], path, strerror(errno));
8400                         rc2 = -errno;
8401                         goto next;
8402                 }
8403
8404                 rc2 = llapi_heat_set(fd, flags);
8405                 close(fd);
8406                 if (rc2 < 0) {
8407                         fprintf(stderr, "%s: cannot setflags heat of file '%s'"
8408                                 ": %s\n", argv[0], path, strerror(errno));
8409                         goto next;
8410                 }
8411 next:
8412                 if (rc == 0 && rc2 < 0)
8413                         rc = rc2;
8414         }
8415         return rc;
8416 }
8417
8418 /** The input string contains a comma delimited list of component ids and
8419  * ranges, for example "1,2-4,7".
8420  */
8421 static int parse_mirror_ids(__u16 *ids, int size, char *arg)
8422 {
8423         bool end_of_loop = false;
8424         char *ptr = NULL;
8425         int nr = 0;
8426         int rc;
8427
8428         if (arg == NULL)
8429                 return -EINVAL;
8430
8431         while (!end_of_loop) {
8432                 int start_index;
8433                 int end_index;
8434                 int i;
8435                 char *endptr = NULL;
8436
8437                 rc = -EINVAL;
8438                 ptr = strchrnul(arg, ',');
8439                 end_of_loop = *ptr == '\0';
8440                 *ptr = '\0';
8441
8442                 start_index = strtol(arg, &endptr, 0);
8443                 if (endptr == arg) /* no data at all */
8444                         break;
8445                 if (*endptr != '-' && *endptr != '\0') /* has invalid data */
8446                         break;
8447                 if (start_index < 0)
8448                         break;
8449
8450                 end_index = start_index;
8451                 if (*endptr == '-') {
8452                         end_index = strtol(endptr + 1, &endptr, 0);
8453                         if (*endptr != '\0')
8454                                 break;
8455                         if (end_index < start_index)
8456                                 break;
8457                 }
8458
8459                 for (i = start_index; i <= end_index && size > 0; i++) {
8460                         int j;
8461
8462                         /* remove duplicate */
8463                         for (j = 0; j < nr; j++) {
8464                                 if (ids[j] == i)
8465                                         break;
8466                         }
8467                         if (j == nr) { /* no duplicate */
8468                                 ids[nr++] = i;
8469                                 --size;
8470                         }
8471                 }
8472
8473                 if (size == 0 && i < end_index)
8474                         break;
8475
8476                 *ptr = ',';
8477                 arg = ++ptr;
8478                 rc = 0;
8479         }
8480         if (!end_of_loop && ptr != NULL)
8481                 *ptr = ',';
8482
8483         return rc < 0 ? rc : nr;
8484 }
8485
8486 /**
8487  * struct verify_mirror_id - Mirror id to be verified.
8488  * @mirror_id:   A specified mirror id.
8489  * @is_valid_id: @mirror_id is valid or not in the mirrored file.
8490  */
8491 struct verify_mirror_id {
8492         __u16 mirror_id;
8493         bool is_valid_id;
8494 };
8495
8496 /**
8497  * compare_mirror_ids() - Compare mirror ids.
8498  * @layout: Mirror component list.
8499  * @cbdata: Callback data in verify_mirror_id structure.
8500  *
8501  * This is a callback function called by llapi_layout_comp_iterate()
8502  * to compare the specified mirror id with the one in the current
8503  * component of @layout. If they are the same, then the specified
8504  * mirror id is valid.
8505  *
8506  * Return: a negative error code on failure or
8507  *         LLAPI_LAYOUT_ITER_CONT: Proceed iteration
8508  *         LLAPI_LAYOUT_ITER_STOP: Stop iteration
8509  */
8510 static inline
8511 int compare_mirror_ids(struct llapi_layout *layout, void *cbdata)
8512 {
8513         struct verify_mirror_id *mirror_id_cbdata =
8514                                  (struct verify_mirror_id *)cbdata;
8515         uint32_t mirror_id;
8516         int rc = 0;
8517
8518         rc = llapi_layout_mirror_id_get(layout, &mirror_id);
8519         if (rc < 0) {
8520                 rc = -errno;
8521                 fprintf(stderr,
8522                         "%s: llapi_layout_mirror_id_get failed: %s.\n",
8523                         progname, strerror(errno));
8524                 return rc;
8525         }
8526
8527         if (mirror_id_cbdata->mirror_id == mirror_id) {
8528                 mirror_id_cbdata->is_valid_id = true;
8529                 return LLAPI_LAYOUT_ITER_STOP;
8530         }
8531
8532         return LLAPI_LAYOUT_ITER_CONT;
8533 }
8534
8535 /**
8536  * verify_mirror_ids() - Verify specified mirror ids.
8537  * @fname:      Mirrored file name.
8538  * @mirror_ids: Specified mirror ids to be verified.
8539  * @ids_nr:     Number of specified mirror ids.
8540  *
8541  * This function verifies that specified @mirror_ids are valid
8542  * in the mirrored file @fname.
8543  *
8544  * Return: 0 on success or a negative error code on failure.
8545  */
8546 static inline
8547 int verify_mirror_ids(const char *fname, __u16 *mirror_ids, int ids_nr)
8548 {
8549         struct llapi_layout *layout = NULL;
8550         struct verify_mirror_id mirror_id_cbdata = { 0 };
8551         struct stat stbuf;
8552         uint32_t flr_state;
8553         int i;
8554         int fd;
8555         int rc = 0;
8556         int rc2 = 0;
8557
8558         if (ids_nr <= 0)
8559                 return -EINVAL;
8560
8561         if (stat(fname, &stbuf) < 0) {
8562                 fprintf(stderr, "%s: cannot stat file '%s': %s.\n",
8563                         progname, fname, strerror(errno));
8564                 rc = -errno;
8565                 goto error;
8566         }
8567
8568         if (!S_ISREG(stbuf.st_mode)) {
8569                 fprintf(stderr, "%s: '%s' is not a regular file.\n",
8570                         progname, fname);
8571                 rc = -EINVAL;
8572                 goto error;
8573         }
8574
8575         fd = open(fname, O_DIRECT | O_RDONLY);
8576         if (fd < 0) {
8577                 fprintf(stderr, "%s: cannot open '%s': %s.\n",
8578                         progname, fname, strerror(errno));
8579                 rc = -errno;
8580                 goto error;
8581         }
8582
8583         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
8584         if (rc < 0) {
8585                 fprintf(stderr, "%s: '%s' llapi_lease_acquire failed: %s.\n",
8586                         progname, fname, strerror(errno));
8587                 goto close_fd;
8588         }
8589
8590         layout = llapi_layout_get_by_fd(fd, 0);
8591         if (layout == NULL) {
8592                 fprintf(stderr, "%s: '%s' llapi_layout_get_by_fd failed: %s.\n",
8593                         progname, fname, strerror(errno));
8594                 rc = -errno;
8595                 llapi_lease_release(fd);
8596                 goto close_fd;
8597         }
8598
8599         rc = llapi_layout_flags_get(layout, &flr_state);
8600         if (rc < 0) {
8601                 fprintf(stderr, "%s: '%s' llapi_layout_flags_get failed: %s.\n",
8602                         progname, fname, strerror(errno));
8603                 rc = -errno;
8604                 goto free_layout;
8605         }
8606
8607         flr_state &= LCM_FL_FLR_MASK;
8608         switch (flr_state) {
8609         case LCM_FL_NONE:
8610                 rc = -EINVAL;
8611                 fprintf(stderr, "%s: '%s' file state error: %s.\n",
8612                         progname, fname, llapi_layout_flags_string(flr_state));
8613                 goto free_layout;
8614         default:
8615                 break;
8616         }
8617
8618         rc2 = 0;
8619         for (i = 0; i < ids_nr; i++) {
8620                 mirror_id_cbdata.mirror_id = mirror_ids[i];
8621                 mirror_id_cbdata.is_valid_id = false;
8622
8623                 rc = llapi_layout_comp_iterate(layout, compare_mirror_ids,
8624                                                &mirror_id_cbdata);
8625                 if (rc < 0) {
8626                         rc = -errno;
8627                         fprintf(stderr,
8628                                 "%s: '%s' failed to verify mirror id: %u.\n",
8629                                 progname, fname, mirror_ids[i]);
8630                         goto free_layout;
8631                 }
8632
8633                 if (!mirror_id_cbdata.is_valid_id) {
8634                         rc2 = -EINVAL;
8635                         fprintf(stderr,
8636                                 "%s: '%s' invalid specified mirror id: %u.\n",
8637                                 progname, fname, mirror_ids[i]);
8638                 }
8639         }
8640         rc = rc2;
8641
8642 free_layout:
8643         llapi_layout_free(layout);
8644         llapi_lease_release(fd);
8645 close_fd:
8646         close(fd);
8647 error:
8648         return rc;
8649 }
8650
8651 static inline
8652 int lfs_mirror_resync_file(const char *fname, struct ll_ioc_lease *ioc,
8653                            __u16 *mirror_ids, int ids_nr)
8654 {
8655         struct llapi_resync_comp comp_array[1024] = { { 0 } };
8656         struct llapi_layout *layout;
8657         struct stat stbuf;
8658         uint32_t flr_state;
8659         uint64_t start;
8660         uint64_t end;
8661         int comp_size = 0;
8662         int idx;
8663         int fd;
8664         int rc;
8665
8666         if (stat(fname, &stbuf) < 0) {
8667                 fprintf(stderr, "%s: cannot stat file '%s': %s.\n",
8668                         progname, fname, strerror(errno));
8669                 rc = -errno;
8670                 goto error;
8671         }
8672         if (!S_ISREG(stbuf.st_mode)) {
8673                 fprintf(stderr, "%s: '%s' is not a regular file.\n",
8674                         progname, fname);
8675                 rc = -EINVAL;
8676                 goto error;
8677         }
8678
8679         fd = open(fname, O_DIRECT | O_RDWR);
8680         if (fd < 0) {
8681                 fprintf(stderr, "%s: cannot open '%s': %s.\n",
8682                         progname, fname, strerror(errno));
8683                 rc = -errno;
8684                 goto error;
8685         }
8686
8687         layout = llapi_layout_get_by_fd(fd, 0);
8688         if (layout == NULL) {
8689                 fprintf(stderr, "%s: '%s' llapi_layout_get_by_fd failed: %s.\n",
8690                         progname, fname, strerror(errno));
8691                 rc = -errno;
8692                 goto close_fd;
8693         }
8694
8695         rc = llapi_layout_flags_get(layout, &flr_state);
8696         if (rc) {
8697                 fprintf(stderr, "%s: '%s' llapi_layout_flags_get failed: %s.\n",
8698                         progname, fname, strerror(errno));
8699                 rc = -errno;
8700                 goto free_layout;
8701         }
8702
8703         flr_state &= LCM_FL_FLR_MASK;
8704         if (flr_state == LCM_FL_NONE) {
8705                 rc = -EINVAL;
8706                 fprintf(stderr, "%s: '%s' is not a FLR file.\n",
8707                         progname, fname);
8708                 goto free_layout;
8709         }
8710
8711         /* get stale component info */
8712         comp_size = llapi_mirror_find_stale(layout, comp_array,
8713                                             ARRAY_SIZE(comp_array),
8714                                             mirror_ids, ids_nr);
8715         if (comp_size <= 0) {
8716                 rc = comp_size;
8717                 goto free_layout;
8718         }
8719
8720         ioc->lil_mode = LL_LEASE_WRLCK;
8721         ioc->lil_flags = LL_LEASE_RESYNC;
8722         rc = llapi_lease_set(fd, ioc);
8723         if (rc < 0) {
8724                 if (rc == -EALREADY)
8725                         rc = 0;
8726                 else
8727                         fprintf(stderr,
8728                             "%s: '%s' llapi_lease_get_ext resync failed: %s.\n",
8729                                 progname, fname, strerror(errno));
8730                 goto free_layout;
8731         }
8732
8733         /* get the read range [start, end) */
8734         start = comp_array[0].lrc_start;
8735         end = comp_array[0].lrc_end;
8736         for (idx = 1; idx < comp_size; idx++) {
8737                 if (comp_array[idx].lrc_start < start)
8738                         start = comp_array[idx].lrc_start;
8739                 if (end < comp_array[idx].lrc_end)
8740                         end = comp_array[idx].lrc_end;
8741         }
8742
8743         rc = llapi_lease_check(fd);
8744         if (rc != LL_LEASE_WRLCK) {
8745                 fprintf(stderr, "%s: '%s' lost lease lock.\n",
8746                         progname, fname);
8747                 goto free_layout;
8748         }
8749
8750         rc = llapi_mirror_resync_many(fd, layout, comp_array, comp_size,
8751                                       start, end);
8752         if (rc < 0)
8753                 fprintf(stderr, "%s: '%s' llapi_mirror_resync_many: %d.\n",
8754                         progname, fname, rc);
8755
8756         /* prepare ioc for lease put */
8757         ioc->lil_mode = LL_LEASE_UNLCK;
8758         ioc->lil_flags = LL_LEASE_RESYNC_DONE;
8759         ioc->lil_count = 0;
8760         for (idx = 0; idx < comp_size; idx++) {
8761                 if (comp_array[idx].lrc_synced) {
8762                         ioc->lil_ids[ioc->lil_count] = comp_array[idx].lrc_id;
8763                         ioc->lil_count++;
8764                 }
8765         }
8766
8767         rc = llapi_lease_set(fd, ioc);
8768         if (rc <= 0) {
8769                 if (rc == 0) /* lost lease lock */
8770                         rc = -EBUSY;
8771                 fprintf(stderr, "%s: resync file '%s' failed: %s.\n",
8772                         progname, fname, strerror(errno));
8773                 goto free_layout;
8774         }
8775         /**
8776          * llapi_lease_set returns lease mode when it request to unlock
8777          * the lease lock
8778          */
8779         rc = 0;
8780
8781 free_layout:
8782         llapi_layout_free(layout);
8783 close_fd:
8784         close(fd);
8785 error:
8786         return rc;
8787 }
8788
8789 static inline int lfs_mirror_resync(int argc, char **argv)
8790 {
8791         struct ll_ioc_lease *ioc = NULL;
8792         __u16 mirror_ids[128] = { 0 };
8793         int ids_nr = 0;
8794         int c;
8795         int rc = 0;
8796
8797         struct option long_opts[] = {
8798         { .val = 'o',   .name = "only",         .has_arg = required_argument },
8799         { .name = NULL } };
8800
8801         while ((c = getopt_long(argc, argv, "o:", long_opts, NULL)) >= 0) {
8802                 switch (c) {
8803                 case 'o':
8804                         rc = parse_mirror_ids(mirror_ids,
8805                                         sizeof(mirror_ids) / sizeof(__u16),
8806                                         optarg);
8807                         if (rc < 0) {
8808                                 fprintf(stderr,
8809                                         "%s: bad mirror ids '%s'.\n",
8810                                         argv[0], optarg);
8811                                 goto error;
8812                         }
8813                         ids_nr = rc;
8814                         break;
8815                 default:
8816                         fprintf(stderr, "%s: options '%s' unrecognized.\n",
8817                                 argv[0], argv[optind - 1]);
8818                         rc = -EINVAL;
8819                         goto error;
8820                 }
8821         }
8822
8823         if (argc == optind) {
8824                 fprintf(stderr, "%s: no file name given.\n", argv[0]);
8825                 rc = CMD_HELP;
8826                 goto error;
8827         }
8828
8829         if (ids_nr > 0 && argc > optind + 1) {
8830                 fprintf(stderr,
8831                     "%s: option '--only' cannot be used upon multiple files.\n",
8832                         argv[0]);
8833                 rc = CMD_HELP;
8834                 goto error;
8835
8836         }
8837
8838         if (ids_nr > 0) {
8839                 rc = verify_mirror_ids(argv[optind], mirror_ids, ids_nr);
8840                 if (rc < 0)
8841                         goto error;
8842         }
8843
8844         /* set the lease on the file */
8845         ioc = calloc(sizeof(*ioc) + sizeof(__u32) * 4096, 1);
8846         if (ioc == NULL) {
8847                 fprintf(stderr, "%s: cannot alloc id array for ioc: %s.\n",
8848                         argv[0], strerror(errno));
8849                 rc = -errno;
8850                 goto error;
8851         }
8852
8853         for (; optind < argc; optind++) {
8854                 rc = lfs_mirror_resync_file(argv[optind], ioc,
8855                                             mirror_ids, ids_nr);
8856                 /* ignore previous file's error, continue with next file */
8857
8858                 /* reset ioc */
8859                 memset(ioc, 0, sizeof(*ioc) + sizeof(__u32) * 4096);
8860         }
8861
8862         free(ioc);
8863 error:
8864         return rc;
8865 }
8866
8867 static inline int verify_mirror_id_by_fd(int fd, __u16 mirror_id)
8868 {
8869         struct llapi_layout *layout;
8870         int rc;
8871
8872         layout = llapi_layout_get_by_fd(fd, 0);
8873         if (layout == NULL) {
8874                 fprintf(stderr, "could not get layout.\n");
8875                 return  -EINVAL;
8876         }
8877
8878         rc = llapi_layout_comp_iterate(layout, find_mirror_id, &mirror_id);
8879         if (rc < 0) {
8880                 fprintf(stderr, "failed to iterate layout\n");
8881                 llapi_layout_free(layout);
8882
8883                 return rc;
8884         } else if (rc == LLAPI_LAYOUT_ITER_CONT) {
8885                 fprintf(stderr, "does not find mirror with ID %u\n", mirror_id);
8886                 llapi_layout_free(layout);
8887
8888                 return -EINVAL;
8889         }
8890         llapi_layout_free(layout);
8891
8892         return 0;
8893 }
8894
8895 /**
8896  * Check whether two files are the same file
8897  * \retval      0  same file
8898  * \retval      1  not the same file
8899  * \retval      <0 error code
8900  */
8901 static inline int check_same_file(const char *f1, const char *f2)
8902 {
8903         struct stat stbuf1;
8904         struct stat stbuf2;
8905
8906         if (stat(f1, &stbuf1) < 0) {
8907                 fprintf(stderr, "%s: cannot stat file '%s': %s\n",
8908                         progname, f1, strerror(errno));
8909                 return -errno;
8910         }
8911
8912         if (stat(f2, &stbuf2) < 0) {
8913                 fprintf(stderr, "%s: cannot stat file '%s': %s\n",
8914                         progname, f2, strerror(errno));
8915                 return -errno;
8916         }
8917
8918         if (stbuf1.st_rdev == stbuf2.st_rdev &&
8919             stbuf1.st_ino == stbuf2.st_ino)
8920                 return 0;
8921
8922         return 1;
8923 }
8924
8925 static inline int lfs_mirror_read(int argc, char **argv)
8926 {
8927         int rc = CMD_HELP;
8928         __u16 mirror_id = 0;
8929         const char *outfile = NULL;
8930         char *fname;
8931         int fd = 0;
8932         int outfd;
8933         int c;
8934         void *buf;
8935         const size_t buflen = 4 << 20;
8936         off_t pos;
8937         struct option long_opts[] = {
8938         { .val = 'N',   .name = "mirror-id",    .has_arg = required_argument },
8939         { .val = 'o',   .name = "outfile",      .has_arg = required_argument },
8940         { .name = NULL } };
8941
8942         while ((c = getopt_long(argc, argv, "N:o:", long_opts, NULL)) >= 0) {
8943                 char *end;
8944
8945                 switch (c) {
8946                 case 'N':
8947                         mirror_id = strtoul(optarg, &end, 0);
8948                         if (*end != '\0' || mirror_id == 0) {
8949                                 fprintf(stderr,
8950                                         "%s %s: invalid mirror ID '%s'\n",
8951                                         progname, argv[0], optarg);
8952                                 return rc;
8953                         }
8954                         break;
8955                 case 'o':
8956                         outfile = optarg;
8957                         break;
8958                 default:
8959                         fprintf(stderr, "%s: option '%s' unrecognized.\n",
8960                                 progname, argv[optind - 1]);
8961                         return -EINVAL;
8962                 }
8963         }
8964
8965         if (argc == optind) {
8966                 fprintf(stderr, "%s %s: no mirrored file provided\n",
8967                         progname, argv[0]);
8968                 return rc;
8969         } else if (argc > optind + 1) {
8970                 fprintf(stderr, "%s %s: too many files\n", progname, argv[0]);
8971                 return rc;
8972         }
8973
8974         if (mirror_id == 0) {
8975                 fprintf(stderr, "%s %s: no valid mirror ID is provided\n",
8976                         progname, argv[0]);
8977                 return rc;
8978         }
8979
8980         /* open mirror file */
8981         fname = argv[optind];
8982
8983         if (outfile) {
8984                 rc = check_same_file(fname, outfile);
8985                 if (rc == 0) {
8986                         fprintf(stderr,
8987                         "%s %s: output file cannot be the mirrored file\n",
8988                                 progname, argv[0]);
8989                         return -EINVAL;
8990                 }
8991                 if (rc < 0)
8992                         return rc;
8993         }
8994
8995         fd = open(fname, O_DIRECT | O_RDONLY);
8996         if (fd < 0) {
8997                 fprintf(stderr, "%s %s: cannot open '%s': %s\n",
8998                         progname, argv[0], fname, strerror(errno));
8999                 return rc;
9000         }
9001
9002         /* verify mirror id */
9003         rc = verify_mirror_id_by_fd(fd, mirror_id);
9004         if (rc) {
9005                 fprintf(stderr,
9006                         "%s %s: cannot find mirror with ID %u in '%s'\n",
9007                         progname, argv[0], mirror_id, fname);
9008                 goto close_fd;
9009         }
9010
9011         /* open output file */
9012         if (outfile) {
9013                 outfd = open(outfile, O_EXCL | O_WRONLY | O_CREAT, 0644);
9014                 if (outfd < 0) {
9015                         fprintf(stderr, "%s %s: cannot create file '%s': %s\n",
9016                                 progname, argv[0], outfile, strerror(errno));
9017                         rc = -errno;
9018                         goto close_fd;
9019                 }
9020         } else {
9021                 outfd = STDOUT_FILENO;
9022         }
9023
9024         /* allocate buffer */
9025         rc = posix_memalign(&buf, sysconf(_SC_PAGESIZE), buflen);
9026         if (rc) {
9027                 fprintf(stderr, "%s %s: posix_memalign returns %d\n",
9028                                 progname, argv[0], rc);
9029                 goto close_outfd;
9030         }
9031
9032         pos = 0;
9033         while (1) {
9034                 ssize_t bytes_read;
9035                 ssize_t written = 0;
9036
9037                 bytes_read = llapi_mirror_read(fd, mirror_id, buf, buflen, pos);
9038                 if (bytes_read < 0) {
9039                         rc = bytes_read;
9040                         fprintf(stderr,
9041                                 "%s %s: fail to read data from mirror %u: %s\n",
9042                                 progname, argv[0], mirror_id, strerror(-rc));
9043                         goto free_buf;
9044                 }
9045
9046                 /* EOF reached */
9047                 if (bytes_read == 0)
9048                         break;
9049
9050                 while (written < bytes_read) {
9051                         ssize_t written2;
9052
9053                         written2 = write(outfd, buf + written,
9054                                          bytes_read - written);
9055                         if (written2 < 0) {
9056                                 fprintf(stderr,
9057                                         "%s %s: fail to write %s: %s\n",
9058                                         progname, argv[0], outfile ? : "STDOUT",
9059                                         strerror(errno));
9060                                 rc = -errno;
9061                                 goto free_buf;
9062                         }
9063                         written += written2;
9064                 }
9065
9066                 if (written != bytes_read) {
9067                         fprintf(stderr,
9068                 "%s %s: written %ld bytes does not match with %ld read.\n",
9069                                 progname, argv[0], written, bytes_read);
9070                         rc = -EIO;
9071                         goto free_buf;
9072                 }
9073
9074                 pos += bytes_read;
9075         }
9076
9077         fsync(outfd);
9078         rc = 0;
9079
9080 free_buf:
9081         free(buf);
9082 close_outfd:
9083         if (outfile)
9084                 close(outfd);
9085 close_fd:
9086         close(fd);
9087
9088         return rc;
9089 }
9090
9091 static inline int lfs_mirror_write(int argc, char **argv)
9092 {
9093         int rc = CMD_HELP;
9094         __u16 mirror_id = 0;
9095         const char *inputfile = NULL;
9096         char *fname;
9097         int fd = 0;
9098         int inputfd;
9099         int c;
9100         void *buf;
9101         const size_t buflen = 4 << 20;
9102         off_t pos;
9103         size_t page_size = sysconf(_SC_PAGESIZE);
9104         struct ll_ioc_lease_id ioc;
9105
9106         struct option long_opts[] = {
9107         { .val = 'N',   .name = "mirror-id",    .has_arg = required_argument },
9108         { .val = 'i',   .name = "inputfile",    .has_arg = required_argument },
9109         { .name = NULL } };
9110
9111         while ((c = getopt_long(argc, argv, "N:i:", long_opts, NULL)) >= 0) {
9112                 char *end;
9113
9114                 switch (c) {
9115                 case 'N':
9116                         mirror_id = strtoul(optarg, &end, 0);
9117                         if (*end != '\0' || mirror_id == 0) {
9118                                 fprintf(stderr,
9119                                         "%s %s: invalid mirror ID '%s'\n",
9120                                         progname, argv[0], optarg);
9121                                 return rc;
9122                         }
9123                         break;
9124                 case 'i':
9125                         inputfile = optarg;
9126                         break;
9127                 default:
9128                         fprintf(stderr, "%s: option '%s' unrecognized\n",
9129                                 progname, argv[optind - 1]);
9130                         return -EINVAL;
9131                 }
9132         }
9133
9134         if (argc == optind) {
9135                 fprintf(stderr, "%s %s: no mirrored file provided\n",
9136                         progname, argv[0]);
9137                 return rc;
9138         } else if (argc > optind + 1) {
9139                 fprintf(stderr, "%s %s: too many files\n", progname, argv[0]);
9140                 return rc;
9141         }
9142
9143         if (mirror_id == 0) {
9144                 fprintf(stderr, "%s %s: no valid mirror ID is provided\n",
9145                         progname, argv[0]);
9146                 return rc;
9147         }
9148
9149         /* open mirror file */
9150         fname = argv[optind];
9151
9152         if (inputfile) {
9153                 rc = check_same_file(fname, inputfile);
9154                 if (rc == 0) {
9155                         fprintf(stderr,
9156                         "%s %s: input file cannot be the mirrored file\n",
9157                                 progname, argv[0]);
9158                         return -EINVAL;
9159                 }
9160                 if (rc < 0)
9161                         return rc;
9162         }
9163
9164         fd = open(fname, O_DIRECT | O_WRONLY);
9165         if (fd < 0) {
9166                 fprintf(stderr, "%s %s: cannot open '%s': %s\n",
9167                         progname, argv[0], fname, strerror(errno));
9168                 return rc;
9169         }
9170
9171         /* verify mirror id */
9172         rc = verify_mirror_id_by_fd(fd, mirror_id);
9173         if (rc) {
9174                 fprintf(stderr,
9175                         "%s %s: cannot find mirror with ID %u in '%s'\n",
9176                         progname, argv[0], mirror_id, fname);
9177                 goto close_fd;
9178         }
9179
9180         /* open input file */
9181         if (inputfile) {
9182                 inputfd = open(inputfile, O_RDONLY, 0644);
9183                 if (inputfd < 0) {
9184                         fprintf(stderr, "%s %s: cannot open file '%s': %s\n",
9185                                 progname, argv[0], inputfile, strerror(errno));
9186                         rc = -errno;
9187                         goto close_fd;
9188                 }
9189         } else {
9190                 inputfd = STDIN_FILENO;
9191         }
9192
9193         /* allocate buffer */
9194         rc = posix_memalign(&buf, page_size, buflen);
9195         if (rc) {
9196                 fprintf(stderr, "%s %s: posix_memalign returns %d\n",
9197                         progname, argv[0], rc);
9198                 goto close_inputfd;
9199         }
9200
9201         /* prepare target mirror components instantiation */
9202         ioc.lil_mode = LL_LEASE_WRLCK;
9203         ioc.lil_flags = LL_LEASE_RESYNC;
9204         ioc.lil_mirror_id = mirror_id;
9205         rc = llapi_lease_set(fd, (struct ll_ioc_lease *)&ioc);
9206         if (rc < 0) {
9207                 fprintf(stderr,
9208                         "%s %s: '%s' llapi_lease_get_ext failed: %s\n",
9209                         progname, argv[0], fname, strerror(errno));
9210                 goto free_buf;
9211         }
9212
9213         pos = 0;
9214         while (1) {
9215                 ssize_t bytes_read;
9216                 ssize_t written;
9217                 size_t to_write;
9218
9219                 rc = llapi_lease_check(fd);
9220                 if (rc != LL_LEASE_WRLCK) {
9221                         fprintf(stderr, "%s %s: '%s' lost lease lock\n",
9222                                 progname, argv[0], fname);
9223                         goto free_buf;
9224                 }
9225
9226                 bytes_read = read(inputfd, buf, buflen);
9227                 if (bytes_read < 0) {
9228                         rc = bytes_read;
9229                         fprintf(stderr,
9230                                 "%s %s: fail to read data from '%s': %s\n",
9231                                 progname, argv[0], inputfile ? : "STDIN",
9232                                 strerror(errno));
9233                         rc = -errno;
9234                         goto free_buf;
9235                 }
9236
9237                 /* EOF reached */
9238                 if (bytes_read == 0)
9239                         break;
9240
9241                 /* round up to page align to make direct IO happy. */
9242                 to_write = (bytes_read + page_size - 1) & ~(page_size - 1);
9243
9244                 written = llapi_mirror_write(fd, mirror_id, buf, to_write,
9245                                              pos);
9246                 if (written < 0) {
9247                         rc = written;
9248                         fprintf(stderr,
9249                               "%s %s: fail to write to mirror %u: %s\n",
9250                                 progname, argv[0], mirror_id,
9251                                 strerror(-rc));
9252                         goto free_buf;
9253                 }
9254
9255                 pos += bytes_read;
9256         }
9257
9258         if (pos & (page_size - 1)) {
9259                 rc = llapi_mirror_truncate(fd, mirror_id, pos);
9260                 if (rc < 0)
9261                         goto free_buf;
9262         }
9263
9264         ioc.lil_mode = LL_LEASE_UNLCK;
9265         ioc.lil_flags = LL_LEASE_RESYNC_DONE;
9266         ioc.lil_count = 0;
9267         rc = llapi_lease_set(fd, (struct ll_ioc_lease *)&ioc);
9268         if (rc <= 0) {
9269                 if (rc == 0)
9270                         rc = -EBUSY;
9271                 fprintf(stderr,
9272                         "%s %s: release lease lock of '%s' failed: %s\n",
9273                         progname, argv[0], fname, strerror(errno));
9274                 goto free_buf;
9275         }
9276
9277         rc = 0;
9278
9279 free_buf:
9280         free(buf);
9281 close_inputfd:
9282         if (inputfile)
9283                 close(inputfd);
9284 close_fd:
9285         close(fd);
9286
9287         return rc;
9288 }
9289
9290 struct collect_ids_data {
9291         __u16   *cid_ids;
9292         int     cid_count;
9293         __u16   cid_exclude;
9294 };
9295
9296 static int collect_mirror_id(struct llapi_layout *layout, void *cbdata)
9297 {
9298         struct collect_ids_data *cid = cbdata;
9299         uint32_t id;
9300         int rc;
9301
9302         rc = llapi_layout_mirror_id_get(layout, &id);
9303         if (rc < 0)
9304                 return rc;
9305
9306         if ((__u16)id != cid->cid_exclude) {
9307                 int i;
9308
9309                 for (i = 0; i < cid->cid_count; i++) {
9310                         /* already collected the mirror id */
9311                         if (id == cid->cid_ids[i])
9312                                 return LLAPI_LAYOUT_ITER_CONT;
9313                 }
9314                 cid->cid_ids[cid->cid_count] = id;
9315                 cid->cid_count++;
9316         }
9317
9318         return LLAPI_LAYOUT_ITER_CONT;
9319 }
9320
9321 static inline int get_other_mirror_ids(int fd, __u16 *ids, __u16 exclude_id)
9322 {
9323         struct llapi_layout *layout;
9324         struct collect_ids_data cid = { .cid_ids = ids,
9325                                         .cid_count = 0,
9326                                         .cid_exclude = exclude_id, };
9327         int rc;
9328
9329         layout = llapi_layout_get_by_fd(fd, 0);
9330         if (layout == NULL) {
9331                 fprintf(stderr, "could not get layout\n");
9332                 return -EINVAL;
9333         }
9334
9335         rc = llapi_layout_comp_iterate(layout, collect_mirror_id, &cid);
9336         if (rc < 0) {
9337                 fprintf(stderr, "failed to iterate layout\n");
9338                 llapi_layout_free(layout);
9339
9340                 return rc;
9341         }
9342         llapi_layout_free(layout);
9343
9344         return cid.cid_count;
9345 }
9346
9347 static inline int lfs_mirror_copy(int argc, char **argv)
9348 {
9349         int rc = CMD_HELP;
9350         __u16 read_mirror_id = 0;
9351         __u16 ids[128] = { 0 };
9352         int count = 0;
9353         struct llapi_layout *layout = NULL;
9354         struct llapi_resync_comp comp_array[1024] = { { 0 } };
9355         int comp_size = 0;
9356         char *fname;
9357         int fd = 0;
9358         int c;
9359         int i;
9360         ssize_t copied;
9361         struct ll_ioc_lease *ioc = NULL;
9362         struct ll_ioc_lease_id *resync_ioc;
9363
9364         struct option long_opts[] = {
9365         { .val = 'i',   .name = "read-mirror",  .has_arg = required_argument },
9366         { .val = 'o',   .name = "write-mirror", .has_arg = required_argument },
9367         { .name = NULL } };
9368
9369         while ((c = getopt_long(argc, argv, "i:o:", long_opts, NULL)) >= 0) {
9370                 char *end;
9371
9372                 switch (c) {
9373                 case 'i':
9374                         read_mirror_id = strtoul(optarg, &end, 0);
9375                         if (*end != '\0' || read_mirror_id == 0) {
9376                                 fprintf(stderr,
9377                                         "%s %s: invalid read mirror ID '%s'\n",
9378                                         progname, argv[0], optarg);
9379                                 return rc;
9380                         }
9381                         break;
9382                 case 'o':
9383                         if (!strcmp(optarg, "-1")) {
9384                                 /* specify all other mirrors */
9385                                 ids[0] = (__u16)-1;
9386                                 count = 1;
9387                         } else {
9388                                 count = parse_mirror_ids((__u16 *)ids,
9389                                                          ARRAY_SIZE(ids),
9390                                                          optarg);
9391                                 if (count < 0)
9392                                         return rc;
9393                         }
9394                         break;
9395                 default:
9396                         fprintf(stderr, "%s: option '%s' unrecognized\n",
9397                                 progname, argv[optind - 1]);
9398                         return -EINVAL;
9399                 }
9400         }
9401
9402         if (argc == optind) {
9403                 fprintf(stderr, "%s %s: no mirrored file provided\n",
9404                         progname, argv[0]);
9405                 return rc;
9406         } else if (argc > optind + 1) {
9407                 fprintf(stderr, "%s %s: too many files\n", progname, argv[0]);
9408                 return rc;
9409         }
9410
9411         if (read_mirror_id == 0) {
9412                 fprintf(stderr,
9413                         "%s %s: no valid read mirror ID %d is provided\n",
9414                         progname, argv[0], read_mirror_id);
9415                 return rc;
9416         }
9417
9418         if (count == 0) {
9419                 fprintf(stderr,
9420                         "%s %s: no write mirror ID is provided\n",
9421                         progname, argv[0]);
9422                 return rc;
9423         }
9424
9425         for (i = 0; i < count; i++) {
9426                 if (read_mirror_id == ids[i]) {
9427                         fprintf(stderr,
9428                         "%s %s: read and write mirror ID cannot be the same\n",
9429                                 progname, argv[0]);
9430                         return rc;
9431                 }
9432         }
9433
9434         /* open mirror file */
9435         fname = argv[optind];
9436
9437         fd = open(fname, O_DIRECT | O_RDWR);
9438         if (fd < 0) {
9439                 fprintf(stderr, "%s %s: cannot open '%s': %s\n",
9440                         progname, argv[0], fname, strerror(errno));
9441                 return rc;
9442         }
9443
9444         /* write to all other mirrors */
9445         if (ids[0] == (__u16)-1) {
9446                 count = get_other_mirror_ids(fd, ids, read_mirror_id);
9447                 if (count <= 0) {
9448                         rc = count;
9449                         fprintf(stderr,
9450                         "%s %s: failed to get other mirror ids in '%s': %d\n",
9451                                 progname, argv[0], fname, rc);
9452                         goto close_fd;
9453                 }
9454         }
9455
9456         /* verify mirror id */
9457         rc = verify_mirror_id_by_fd(fd, read_mirror_id);
9458         if (rc) {
9459                 fprintf(stderr,
9460                         "%s %s: cannot find mirror with ID %u in '%s'\n",
9461                         progname, argv[0], read_mirror_id, fname);
9462                 goto close_fd;
9463         }
9464
9465         for (i = 0; i < count; i++) {
9466                 rc = verify_mirror_id_by_fd(fd, ids[i]);
9467                 if (rc) {
9468                         fprintf(stderr,
9469                         "%s %s: cannot find mirror with ID %u in '%s'\n",
9470                                 progname, argv[0], ids[i], fname);
9471                         goto close_fd;
9472                 }
9473         }
9474
9475         ioc = calloc(sizeof(*ioc) + sizeof(__u32) * 4096, 1);
9476         if (ioc == NULL) {
9477                 fprintf(stderr,
9478                         "%s %s: cannot alloc comp id array for ioc: %s\n",
9479                         progname, argv[0], strerror(errno));
9480                 rc = -errno;
9481                 goto close_fd;
9482         }
9483
9484         /* get stale component info */
9485         layout = llapi_layout_get_by_fd(fd, 0);
9486         if (layout == NULL) {
9487                 fprintf(stderr, "%s %s: failed to get layout of '%s': %s\n",
9488                         progname, argv[0], fname, strerror(errno));
9489                 rc = -errno;
9490                 goto free_ioc;
9491         }
9492         comp_size = llapi_mirror_find_stale(layout, comp_array,
9493                                             ARRAY_SIZE(comp_array),
9494                                             ids, count);
9495         llapi_layout_free(layout);
9496         if (comp_size < 0) {
9497                 rc = comp_size;
9498                 goto free_ioc;
9499         }
9500
9501         /* prepare target mirror components instantiation */
9502         resync_ioc = (struct ll_ioc_lease_id *)ioc;
9503         resync_ioc->lil_mode = LL_LEASE_WRLCK;
9504         resync_ioc->lil_flags = LL_LEASE_RESYNC;
9505         if (count == 1)
9506                 resync_ioc->lil_mirror_id = ids[0];
9507         else
9508                 resync_ioc->lil_mirror_id = read_mirror_id | MIRROR_ID_NEG;
9509         rc = llapi_lease_set(fd, ioc);
9510         if (rc < 0) {
9511                 fprintf(stderr,
9512                         "%s %s: '%s' llapi_lease_get_ext failed: %s\n",
9513                         progname, argv[0], fname, strerror(errno));
9514                 goto free_ioc;
9515         }
9516
9517         copied = llapi_mirror_copy_many(fd, read_mirror_id, ids, count);
9518         if (copied < 0) {
9519                 rc = copied;
9520                 fprintf(stderr, "%s %s: copy error: %d\n",
9521                         progname, argv[0], rc);
9522                 goto free_ioc;
9523         }
9524
9525         fprintf(stdout, "mirror copied successfully: ");
9526         for (i = 0; i < copied; i++)
9527                 fprintf(stdout, "%d ", ids[i]);
9528         fprintf(stdout, "\n");
9529
9530         ioc->lil_mode = LL_LEASE_UNLCK;
9531         ioc->lil_flags = LL_LEASE_RESYNC_DONE;
9532         ioc->lil_count = 0;
9533         for (i = 0; i < comp_size; i++) {
9534                 int j;
9535
9536                 for (j = 0; j < copied; j++) {
9537                         if (comp_array[i].lrc_mirror_id != ids[j])
9538                                 continue;
9539
9540                         ioc->lil_ids[ioc->lil_count] = comp_array[i].lrc_id;
9541                         ioc->lil_count++;
9542                 }
9543         }
9544         rc = llapi_lease_set(fd, ioc);
9545         if (rc <= 0) {
9546                 if (rc == 0)
9547                         rc = -EBUSY;
9548                 fprintf(stderr,
9549                         "%s %s: release lease lock of '%s' failed: %s\n",
9550                         progname, argv[0], fname, strerror(errno));
9551                 goto free_ioc;
9552         }
9553
9554         rc = 0;
9555
9556 free_ioc:
9557         free(ioc);
9558 close_fd:
9559         close(fd);
9560
9561         return rc;
9562 }
9563 /**
9564  * struct verify_chunk - Mirror chunk to be verified.
9565  * @chunk:        [start, end) of the chunk.
9566  * @mirror_count: Number of mirror ids in @mirror_id array.
9567  * @mirror_id:    Array of valid mirror ids that cover the chunk.
9568  */
9569 struct verify_chunk {
9570         struct lu_extent chunk;
9571         unsigned int mirror_count;
9572         __u16 mirror_id[LUSTRE_MIRROR_COUNT_MAX];
9573 };
9574
9575 /**
9576  * print_chunks() - Print chunk information.
9577  * @fname:       Mirrored file name.
9578  * @chunks:      Array of chunks.
9579  * @chunk_count: Number of chunks in @chunks array.
9580  *
9581  * This function prints [start, end) of each chunk in @chunks
9582  * for mirrored file @fname, and also prints the valid mirror ids
9583  * that cover the chunk.
9584  *
9585  * Return: void.
9586  */
9587 static inline
9588 void print_chunks(const char *fname, struct verify_chunk *chunks,
9589                   int chunk_count)
9590 {
9591         int i;
9592         int j;
9593
9594         fprintf(stdout, "Chunks to be verified in %s:\n", fname);
9595         for (i = 0; i < chunk_count; i++) {
9596                 fprintf(stdout, DEXT, PEXT(&chunks[i].chunk));
9597
9598                 if (chunks[i].mirror_count == 0)
9599                         fprintf(stdout, "\t[");
9600                 else {
9601                         fprintf(stdout, "\t[%u", chunks[i].mirror_id[0]);
9602                         for (j = 1; j < chunks[i].mirror_count; j++)
9603                                 fprintf(stdout, ", %u", chunks[i].mirror_id[j]);
9604                 }
9605                 fprintf(stdout, "]\t%u\n", chunks[i].mirror_count);
9606         }
9607         fprintf(stdout, "\n");
9608 }
9609
9610 /**
9611  * print_checksums() - Print CRC-32 checksum values.
9612  * @chunk: A chunk and its corresponding valid mirror ids.
9613  * @crc:   CRC-32 checksum values on the chunk for each valid mirror.
9614  *
9615  * This function prints CRC-32 checksum values on @chunk for
9616  * each valid mirror that covers it.
9617  *
9618  * Return: void.
9619  */
9620 static inline
9621 void print_checksums(struct verify_chunk *chunk, unsigned long *crc)
9622 {
9623         int i;
9624
9625         fprintf(stdout,
9626                 "CRC-32 checksum value for chunk "DEXT":\n",
9627                 PEXT(&chunk->chunk));
9628         for (i = 0; i < chunk->mirror_count; i++)
9629                 fprintf(stdout, "Mirror %u:\t%#lx\n",
9630                         chunk->mirror_id[i], crc[i]);
9631         fprintf(stdout, "\n");
9632 }
9633
9634 /**
9635  * filter_mirror_id() - Filter specified mirror ids.
9636  * @chunks:      Array of chunks.
9637  * @chunk_count: Number of chunks in @chunks array.
9638  * @mirror_ids:  Specified mirror ids to be verified.
9639  * @ids_nr:      Number of specified mirror ids.
9640  *
9641  * This function scans valid mirror ids that cover each chunk in @chunks
9642  * and filters specified mirror ids.
9643  *
9644  * Return: void.
9645  */
9646 static inline
9647 void filter_mirror_id(struct verify_chunk *chunks, int chunk_count,
9648                       __u16 *mirror_ids, int ids_nr)
9649 {
9650         int i;
9651         int j;
9652         int k;
9653         __u16 valid_id[LUSTRE_MIRROR_COUNT_MAX] = { 0 };
9654         unsigned int valid_count = 0;
9655
9656         for (i = 0; i < chunk_count; i++) {
9657                 if (chunks[i].mirror_count == 0)
9658                         continue;
9659
9660                 valid_count = 0;
9661                 for (j = 0; j < ids_nr; j++) {
9662                         for (k = 0; k < chunks[i].mirror_count; k++) {
9663                                 if (chunks[i].mirror_id[k] == mirror_ids[j]) {
9664                                         valid_id[valid_count] = mirror_ids[j];
9665                                         valid_count++;
9666                                         break;
9667                                 }
9668                         }
9669                 }
9670
9671                 memcpy(chunks[i].mirror_id, valid_id,
9672                        sizeof(__u16) * valid_count);
9673                 chunks[i].mirror_count = valid_count;
9674         }
9675 }
9676
9677 /**
9678  * lfs_mirror_prepare_chunk() - Find mirror chunks to be verified.
9679  * @layout:      Mirror component list.
9680  * @chunks:      Array of chunks.
9681  * @chunks_size: Array size of @chunks.
9682  *
9683  * This function scans the components in @layout from offset 0 to LUSTRE_EOF
9684  * to find out chunk segments and store them in @chunks array.
9685  *
9686  * The @mirror_id array in each element of @chunks will store the valid
9687  * mirror ids that cover the chunk. If a mirror component covering the
9688  * chunk has LCME_FL_STALE or LCME_FL_OFFLINE flag, then the mirror id
9689  * will not be stored into the @mirror_id array, and the chunk for that
9690  * mirror will not be verified.
9691  *
9692  * The @mirror_count in each element of @chunks will store the number of
9693  * mirror ids in @mirror_id array. If @mirror_count is 0, it indicates the
9694  * chunk is invalid in all of the mirrors. And if @mirror_count is 1, it
9695  * indicates the chunk is valid in only one mirror. In both cases, the
9696  * chunk will not be verified.
9697  *
9698  * Here is an example:
9699  *
9700  *  0      1M     2M     3M     4M           EOF
9701  *  +------+-------------+--------------------+
9702  *  |      |             |      S             |       mirror1
9703  *  +------+------+------+------+-------------+
9704  *  |             |   S  |   S  |             |       mirror2
9705  *  +-------------+------+------+-------------+
9706  *
9707  * prepared @chunks array will contain 5 elements:
9708  * (([0, 1M), [1, 2], 2),
9709  *  ([1M, 2M), [1, 2], 2),
9710  *  ([2M, 3M), [1], 1),
9711  *  ([3M, 4M], [], 0),
9712  *  ([4M, EOF), [2], 1))
9713  *
9714  * Return: the actual array size of @chunks on success
9715  *         or a negative error code on failure.
9716  */
9717 static inline
9718 int lfs_mirror_prepare_chunk(struct llapi_layout *layout,
9719                              struct verify_chunk *chunks,
9720                              size_t chunks_size)
9721 {
9722         uint64_t start;
9723         uint64_t end;
9724         uint32_t mirror_id;
9725         uint32_t flags;
9726         int idx = 0;
9727         int i = 0;
9728         int rc = 0;
9729
9730         memset(chunks, 0, sizeof(*chunks) * chunks_size);
9731
9732         while (1) {
9733                 rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_FIRST);
9734                 if (rc < 0) {
9735                         fprintf(stderr,
9736                                 "%s: move to the first layout component: %s.\n",
9737                                 progname, strerror(errno));
9738                         goto error;
9739                 }
9740
9741                 i = 0;
9742                 rc = 0;
9743                 chunks[idx].chunk.e_end = LUSTRE_EOF;
9744                 while (rc == 0) {
9745                         rc = llapi_layout_comp_extent_get(layout, &start, &end);
9746                         if (rc < 0) {
9747                                 fprintf(stderr,
9748                                         "%s: llapi_layout_comp_extent_get failed: %s.\n",
9749                                         progname, strerror(errno));
9750                                 goto error;
9751                         }
9752
9753                         if (start > chunks[idx].chunk.e_start ||
9754                             end <= chunks[idx].chunk.e_start)
9755                                 goto next;
9756
9757                         if (end < chunks[idx].chunk.e_end)
9758                                 chunks[idx].chunk.e_end = end;
9759
9760                         rc = llapi_layout_comp_flags_get(layout, &flags);
9761                         if (rc < 0) {
9762                                 fprintf(stderr,
9763                                         "%s: llapi_layout_comp_flags_get failed: %s.\n",
9764                                         progname, strerror(errno));
9765                                 goto error;
9766                         }
9767
9768                         if (flags & LCME_FL_STALE || flags & LCME_FL_OFFLINE)
9769                                 goto next;
9770
9771                         rc = llapi_layout_mirror_id_get(layout, &mirror_id);
9772                         if (rc < 0) {
9773                                 fprintf(stderr,
9774                                         "%s: llapi_layout_mirror_id_get failed: %s.\n",
9775                                         progname, strerror(errno));
9776                                 goto error;
9777                         }
9778
9779                         chunks[idx].mirror_id[i] = mirror_id;
9780                         i++;
9781                         if (i >= ARRAY_SIZE(chunks[idx].mirror_id)) {
9782                                 fprintf(stderr,
9783                                         "%s: mirror_id array is too small.\n",
9784                                         progname);
9785                                 rc = -EINVAL;
9786                                 goto error;
9787                         }
9788
9789                 next:
9790                         rc = llapi_layout_comp_use(layout,
9791                                                    LLAPI_LAYOUT_COMP_USE_NEXT);
9792                         if (rc < 0) {
9793                                 fprintf(stderr,
9794                                         "%s: move to the next layout component: %s.\n",
9795                                         progname, strerror(errno));
9796                                 goto error;
9797                         }
9798                 } /* loop through all components */
9799
9800                 chunks[idx].mirror_count = i;
9801
9802                 if (chunks[idx].chunk.e_end == LUSTRE_EOF)
9803                         break;
9804
9805                 idx++;
9806                 if (idx >= chunks_size) {
9807                         fprintf(stderr, "%s: chunks array is too small.\n",
9808                                 progname);
9809                         rc = -EINVAL;
9810                         goto error;
9811                 }
9812
9813                 chunks[idx].chunk.e_start = chunks[idx - 1].chunk.e_end;
9814         }
9815
9816 error:
9817         return rc < 0 ? rc : idx + 1;
9818 }
9819
9820 /**
9821  * lfs_mirror_verify_chunk() - Verify a chunk.
9822  * @fd:        File descriptor of the mirrored file.
9823  * @file_size: Size of the mirrored file.
9824  * @chunk:     A chunk and its corresponding valid mirror ids.
9825  * @verbose:   Verbose mode.
9826  *
9827  * This function verifies a @chunk contains exactly the same data
9828  * ammong the mirrors that cover it.
9829  *
9830  * If @verbose is specified, then the function will print where the
9831  * differences are if the data do not match. Otherwise, it will
9832  * just return an error in that case.
9833  *
9834  * Return: 0 on success or a negative error code on failure.
9835  */
9836 static inline
9837 int lfs_mirror_verify_chunk(int fd, size_t file_size,
9838                             struct verify_chunk *chunk, int verbose)
9839 {
9840         const size_t buflen = 4 * 1024 * 1024; /* 4M */
9841         void *buf;
9842         size_t page_size = sysconf(_SC_PAGESIZE);
9843         ssize_t bytes_read;
9844         ssize_t bytes_done;
9845         size_t count;
9846         off_t pos;
9847         unsigned long crc;
9848         unsigned long crc_array[LUSTRE_MIRROR_COUNT_MAX] = { 0 };
9849         int i;
9850         int rc = 0;
9851
9852         if (file_size == 0)
9853                 return 0;
9854
9855         rc = posix_memalign(&buf, page_size, buflen);
9856         if (rc) /* error code is returned directly */
9857                 return -rc;
9858
9859         if (verbose > 1) {
9860                 fprintf(stdout, "Verifying chunk "DEXT" on mirror:",
9861                         PEXT(&chunk->chunk));
9862                 for (i = 0; i < chunk->mirror_count; i++)
9863                         fprintf(stdout, " %u", chunk->mirror_id[i]);
9864                 fprintf(stdout, "\n");
9865         }
9866
9867         bytes_done = 0;
9868         count = MIN(chunk->chunk.e_end, file_size) - chunk->chunk.e_start;
9869         pos = chunk->chunk.e_start;
9870         while (bytes_done < count) {
9871                 /* compute initial CRC-32 checksum */
9872                 crc = crc32(0L, Z_NULL, 0);
9873                 memset(crc_array, 0, sizeof(crc_array));
9874
9875                 bytes_read = 0;
9876                 for (i = 0; i < chunk->mirror_count; i++) {
9877                         bytes_read = llapi_mirror_read(fd, chunk->mirror_id[i],
9878                                                        buf, buflen, pos);
9879                         if (bytes_read < 0) {
9880                                 rc = bytes_read;
9881                                 fprintf(stderr,
9882                                         "%s: failed to read data from mirror %u: %s.\n",
9883                                         progname, chunk->mirror_id[i],
9884                                         strerror(-rc));
9885                                 goto error;
9886                         }
9887
9888                         /* compute new CRC-32 checksum */
9889                         crc_array[i] = crc32(crc, buf, bytes_read);
9890                 }
9891
9892                 if (verbose)
9893                         print_checksums(chunk, crc_array);
9894
9895                 /* compare CRC-32 checksum values */
9896                 for (i = 1; i < chunk->mirror_count; i++) {
9897                         if (crc_array[i] != crc_array[0]) {
9898                                 rc = -EINVAL;
9899
9900                                 fprintf(stderr,
9901                                         "%s: chunk "DEXT" has different checksum value on mirror %u and mirror %u.\n",
9902                                         progname, PEXT(&chunk->chunk),
9903                                         chunk->mirror_id[0],
9904                                         chunk->mirror_id[i]);
9905                         }
9906                 }
9907
9908                 pos += bytes_read;
9909                 bytes_done += bytes_read;
9910         }
9911
9912         if (verbose > 1 && rc == 0) {
9913                 fprintf(stdout, "Verifying chunk "DEXT" on mirror:",
9914                         PEXT(&chunk->chunk));
9915                 for (i = 0; i < chunk->mirror_count; i++)
9916                         fprintf(stdout, " %u", chunk->mirror_id[i]);
9917                 fprintf(stdout, " PASS\n\n");
9918         }
9919
9920 error:
9921         free(buf);
9922         return rc;
9923 }
9924
9925 /**
9926  * lfs_mirror_verify_file() - Verify a mirrored file.
9927  * @fname:      Mirrored file name.
9928  * @mirror_ids: Specified mirror ids to be verified.
9929  * @ids_nr:     Number of specified mirror ids.
9930  * @verbose:    Verbose mode.
9931  *
9932  * This function verifies that each SYNC mirror of a mirrored file
9933  * specified by @fname contains exactly the same data.
9934  *
9935  * If @mirror_ids is specified, then the function will verify the
9936  * mirrors specified by @mirror_ids contain exactly the same data.
9937  *
9938  * If @verbose is specified, then the function will print where the
9939  * differences are if the data do not match. Otherwise, it will
9940  * just return an error in that case.
9941  *
9942  * Return: 0 on success or a negative error code on failure.
9943  */
9944 static inline
9945 int lfs_mirror_verify_file(const char *fname, __u16 *mirror_ids, int ids_nr,
9946                            int verbose)
9947 {
9948         struct verify_chunk chunks_array[1024] = { };
9949         struct llapi_layout *layout = NULL;
9950         struct stat stbuf;
9951         uint32_t flr_state;
9952         int fd;
9953         int chunk_count = 0;
9954         int idx = 0;
9955         int rc = 0;
9956         int rc1 = 0;
9957         int rc2 = 0;
9958
9959         if (stat(fname, &stbuf) < 0) {
9960                 fprintf(stderr, "%s: cannot stat file '%s': %s.\n",
9961                         progname, fname, strerror(errno));
9962                 rc = -errno;
9963                 goto error;
9964         }
9965
9966         if (!S_ISREG(stbuf.st_mode)) {
9967                 fprintf(stderr, "%s: '%s' is not a regular file.\n",
9968                         progname, fname);
9969                 rc = -EINVAL;
9970                 goto error;
9971         }
9972
9973         if (stbuf.st_size == 0) {
9974                 if (verbose)
9975                         fprintf(stdout, "%s: '%s' file size is 0.\n",
9976                                 progname, fname);
9977                 rc = 0;
9978                 goto error;
9979         }
9980
9981         fd = open(fname, O_DIRECT | O_RDONLY);
9982         if (fd < 0) {
9983                 fprintf(stderr, "%s: cannot open '%s': %s.\n",
9984                         progname, fname, strerror(errno));
9985                 rc = -errno;
9986                 goto error;
9987         }
9988
9989         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
9990         if (rc < 0) {
9991                 fprintf(stderr, "%s: '%s' llapi_lease_acquire failed: %s.\n",
9992                         progname, fname, strerror(errno));
9993                 goto close_fd;
9994         }
9995
9996         layout = llapi_layout_get_by_fd(fd, 0);
9997         if (layout == NULL) {
9998                 fprintf(stderr, "%s: '%s' llapi_layout_get_by_fd failed: %s.\n",
9999                         progname, fname, strerror(errno));
10000                 rc = -errno;
10001                 llapi_lease_release(fd);
10002                 goto close_fd;
10003         }
10004
10005         rc = llapi_layout_flags_get(layout, &flr_state);
10006         if (rc < 0) {
10007                 fprintf(stderr, "%s: '%s' llapi_layout_flags_get failed: %s.\n",
10008                         progname, fname, strerror(errno));
10009                 rc = -errno;
10010                 goto free_layout;
10011         }
10012
10013         flr_state &= LCM_FL_FLR_MASK;
10014         switch (flr_state) {
10015         case LCM_FL_NONE:
10016                 rc = -EINVAL;
10017                 fprintf(stderr, "%s: '%s' file state error: %s.\n",
10018                         progname, fname, llapi_layout_flags_string(flr_state));
10019                 goto free_layout;
10020         default:
10021                 break;
10022         }
10023
10024         /* find out mirror chunks to be verified */
10025         chunk_count = lfs_mirror_prepare_chunk(layout, chunks_array,
10026                                                ARRAY_SIZE(chunks_array));
10027         if (chunk_count < 0) {
10028                 rc = chunk_count;
10029                 goto free_layout;
10030         }
10031
10032         if (ids_nr > 0)
10033                 /* filter specified mirror ids */
10034                 filter_mirror_id(chunks_array, chunk_count, mirror_ids, ids_nr);
10035
10036         if (verbose > 2)
10037                 print_chunks(fname, chunks_array, chunk_count);
10038
10039         for (idx = 0; idx < chunk_count; idx++) {
10040                 if (chunks_array[idx].chunk.e_start >= stbuf.st_size) {
10041                         if (verbose)
10042                                 fprintf(stdout,
10043                                         "%s: '%s' chunk "DEXT" exceeds file size %#llx: skipped\n",
10044                                         progname, fname,
10045                                         PEXT(&chunks_array[idx].chunk),
10046                                         (unsigned long long)stbuf.st_size);
10047                         break;
10048                 }
10049
10050                 if (chunks_array[idx].mirror_count == 0) {
10051                         fprintf(stderr,
10052                                 "%s: '%s' chunk "DEXT" is invalid in all of the mirrors: ",
10053                                 progname, fname,
10054                                 PEXT(&chunks_array[idx].chunk));
10055                         if (verbose) {
10056                                 fprintf(stderr, "skipped\n");
10057                                 continue;
10058                         }
10059                         rc = -EINVAL;
10060                         fprintf(stderr, "failed\n");
10061                         goto free_layout;
10062                 }
10063
10064                 if (chunks_array[idx].mirror_count == 1) {
10065                         if (verbose)
10066                                 fprintf(stdout,
10067                                         "%s: '%s' chunk "DEXT" is only valid in mirror %u: skipped\n",
10068                                         progname, fname,
10069                                         PEXT(&chunks_array[idx].chunk),
10070                                         chunks_array[idx].mirror_id[0]);
10071                         continue;
10072                 }
10073
10074                 rc = llapi_lease_check(fd);
10075                 if (rc != LL_LEASE_RDLCK) {
10076                         fprintf(stderr, "%s: '%s' lost lease lock.\n",
10077                                 progname, fname);
10078                         goto free_layout;
10079                 }
10080
10081                 /* verify one chunk */
10082                 rc1 = lfs_mirror_verify_chunk(fd, stbuf.st_size,
10083                                               &chunks_array[idx], verbose);
10084                 if (rc1 < 0) {
10085                         rc2 = rc1;
10086                         if (!verbose) {
10087                                 rc = rc1;
10088                                 goto free_layout;
10089                         }
10090                 }
10091         }
10092
10093         if (rc2 < 0)
10094                 rc = rc2;
10095
10096 free_layout:
10097         llapi_layout_free(layout);
10098         llapi_lease_release(fd);
10099 close_fd:
10100         close(fd);
10101 error:
10102         return rc;
10103 }
10104
10105 /**
10106  * lfs_mirror_verify() - Parse and execute lfs mirror verify command.
10107  * @argc: The count of lfs mirror verify command line arguments.
10108  * @argv: Array of strings for lfs mirror verify command line arguments.
10109  *
10110  * This function parses lfs mirror verify command and verifies the
10111  * specified mirrored file(s).
10112  *
10113  * Return: 0 on success or a negative error code on failure.
10114  */
10115 static inline int lfs_mirror_verify(int argc, char **argv)
10116 {
10117         __u16 mirror_ids[LUSTRE_MIRROR_COUNT_MAX] = { 0 };
10118         int ids_nr = 0;
10119         int c;
10120         int verbose = 0;
10121         int rc = 0;
10122         int rc1 = 0;
10123         char cmd[PATH_MAX];
10124
10125         struct option long_opts[] = {
10126         { .val = 'o',   .name = "only",         .has_arg = required_argument },
10127         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
10128         { .name = NULL } };
10129
10130         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
10131         progname = cmd;
10132         while ((c = getopt_long(argc, argv, "o:v", long_opts, NULL)) >= 0) {
10133                 switch (c) {
10134                 case 'o':
10135                         rc = parse_mirror_ids(mirror_ids,
10136                                               ARRAY_SIZE(mirror_ids),
10137                                               optarg);
10138                         if (rc < 0) {
10139                                 fprintf(stderr,
10140                                         "%s: bad mirror ids '%s'.\n",
10141                                         progname, optarg);
10142                                 goto error;
10143                         }
10144                         ids_nr = rc;
10145                         if (ids_nr < 2) {
10146                                 fprintf(stderr,
10147                                         "%s: at least 2 mirror ids needed with '--only' option.\n",
10148                                         progname);
10149                                 rc = CMD_HELP;
10150                                 goto error;
10151                         }
10152                         break;
10153                 case 'v':
10154                         verbose++;
10155                         break;
10156                 default:
10157                         fprintf(stderr, "%s: option '%s' unrecognized.\n",
10158                                 progname, argv[optind - 1]);
10159                         rc = -EINVAL;
10160                         goto error;
10161                 }
10162         }
10163
10164         if (argc == optind) {
10165                 fprintf(stderr, "%s: no file name given.\n", progname);
10166                 rc = CMD_HELP;
10167                 goto error;
10168         }
10169
10170         if (ids_nr > 0 && argc > optind + 1) {
10171                 fprintf(stderr,
10172                         "%s: '--only' cannot be used upon multiple files.\n",
10173                         progname);
10174                 rc = CMD_HELP;
10175                 goto error;
10176
10177         }
10178
10179         if (ids_nr > 0) {
10180                 rc = verify_mirror_ids(argv[optind], mirror_ids, ids_nr);
10181                 if (rc < 0)
10182                         goto error;
10183         }
10184
10185         rc = 0;
10186         for (; optind < argc; optind++) {
10187                 rc1 = lfs_mirror_verify_file(argv[optind], mirror_ids, ids_nr,
10188                                              verbose);
10189                 if (rc1 < 0)
10190                         rc = rc1;
10191         }
10192 error:
10193         return rc;
10194 }
10195
10196 /**
10197  * lfs_mirror() - Parse and execute lfs mirror commands.
10198  * @argc: The count of lfs mirror command line arguments.
10199  * @argv: Array of strings for lfs mirror command line arguments.
10200  *
10201  * This function parses lfs mirror commands and performs the
10202  * corresponding functions specified in mirror_cmdlist[].
10203  *
10204  * Return: 0 on success or an error code on failure.
10205  */
10206 static int lfs_mirror(int argc, char **argv)
10207 {
10208         char cmd[PATH_MAX];
10209         int rc = 0;
10210
10211         setlinebuf(stdout);
10212
10213         Parser_init("lfs-mirror > ", mirror_cmdlist);
10214
10215         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
10216         progname = cmd;
10217         program_invocation_short_name = cmd;
10218         if (argc > 1)
10219                 rc = Parser_execarg(argc - 1, argv + 1, mirror_cmdlist);
10220         else
10221                 rc = Parser_commands();
10222
10223         return rc < 0 ? -rc : rc;
10224 }
10225
10226 static void lustre_som_swab(struct lustre_som_attrs *attrs)
10227 {
10228 #if __BYTE_ORDER == __BIG_ENDIAN
10229         __swab16s(&attrs->lsa_valid);
10230         __swab64s(&attrs->lsa_size);
10231         __swab64s(&attrs->lsa_blocks);
10232 #endif
10233 }
10234
10235 enum lfs_som_type {
10236         LFS_SOM_SIZE = 0x1,
10237         LFS_SOM_BLOCKS = 0x2,
10238         LFS_SOM_FLAGS = 0x4,
10239         LFS_SOM_ATTR_ALL = LFS_SOM_SIZE | LFS_SOM_BLOCKS |
10240                            LFS_SOM_FLAGS,
10241 };
10242
10243 static int lfs_getsom(int argc, char **argv)
10244 {
10245         const char *path;
10246         struct lustre_som_attrs *attrs;
10247         char buf[sizeof(*attrs) + 64];
10248         enum lfs_som_type type = LFS_SOM_ATTR_ALL;
10249         int rc = 0, c;
10250
10251         while ((c = getopt(argc, argv, "sbf")) != -1) {
10252                 switch (c) {
10253                 case 's':
10254                         type = LFS_SOM_SIZE;
10255                         break;
10256                 case 'b':
10257                         type = LFS_SOM_BLOCKS;
10258                         break;
10259                 case 'f':
10260                         type = LFS_SOM_FLAGS;
10261                         break;
10262                 default:
10263                         fprintf(stderr, "%s: invalid option '%c'\n",
10264                                 progname, optopt);
10265                         return CMD_HELP;
10266                 }
10267         }
10268
10269         argc -= optind;
10270         argv += optind;
10271
10272         if (argc != 1) {
10273                 fprintf(stderr, "%s: %s\n",
10274                         progname, argc == 0 ? "miss file target" :
10275                         "input more than 2 files");
10276                 return CMD_HELP;
10277         }
10278
10279         path = argv[0];
10280         attrs = (void *)buf;
10281         rc = lgetxattr(path, "trusted.som", attrs, sizeof(buf));
10282         if (rc < 0) {
10283                 rc = -errno;
10284                 fprintf(stderr, "%s failed to get som xattr: %s (%d)\n",
10285                         argv[0], strerror(errno), errno);
10286                 return rc;
10287         }
10288
10289         lustre_som_swab(attrs);
10290
10291         switch (type) {
10292         case LFS_SOM_ATTR_ALL:
10293                 printf("file: %s size: %llu blocks: %llu flags: %x\n",
10294                        path, attrs->lsa_size, attrs->lsa_blocks,
10295                        attrs->lsa_valid);
10296                 break;
10297         case LFS_SOM_SIZE:
10298                 printf("%llu\n", attrs->lsa_size);
10299                 break;
10300         case LFS_SOM_BLOCKS:
10301                 printf("%llu\n", attrs->lsa_blocks);
10302                 break;
10303         case LFS_SOM_FLAGS:
10304                 printf("%x\n", attrs->lsa_valid);
10305                 break;
10306         default:
10307                 fprintf(stderr, "%s: unknown option\n", progname);
10308                 return CMD_HELP;
10309         }
10310
10311         return 0;
10312 }
10313
10314 /**
10315  * lfs_mirror_list_commands() - List lfs mirror commands.
10316  * @argc: The count of command line arguments.
10317  * @argv: Array of strings for command line arguments.
10318  *
10319  * This function lists lfs mirror commands defined in mirror_cmdlist[].
10320  *
10321  * Return: 0 on success.
10322  */
10323 static int lfs_mirror_list_commands(int argc, char **argv)
10324 {
10325         char buffer[81] = "";
10326
10327         Parser_list_commands(mirror_cmdlist, buffer, sizeof(buffer),
10328                              NULL, 0, 4);
10329
10330         return 0;
10331 }
10332
10333 static int lfs_list_commands(int argc, char **argv)
10334 {
10335         char buffer[81] = ""; /* 80 printable chars + terminating NUL */
10336
10337         Parser_list_commands(cmdlist, buffer, sizeof(buffer), NULL, 0, 4);
10338
10339         return 0;
10340 }
10341
10342 int main(int argc, char **argv)
10343 {
10344         int rc;
10345
10346         /* Ensure that liblustreapi constructor has run */
10347         if (!llapi_liblustreapi_initialized())
10348                 fprintf(stderr, "liblustreapi was not properly initialized\n");
10349
10350         setlinebuf(stdout);
10351         opterr = 0;
10352
10353         Parser_init("lfs > ", cmdlist);
10354
10355         progname = program_invocation_short_name; /* Used in error messages */
10356         if (argc > 1) {
10357                 llapi_set_command_name(argv[1]);
10358                 rc = Parser_execarg(argc - 1, argv + 1, cmdlist);
10359                 llapi_clear_command_name();
10360         } else {
10361                 rc = Parser_commands();
10362         }
10363
10364         return rc < 0 ? -rc : rc;
10365 }
10366
10367 #ifdef _LUSTRE_IDL_H_
10368 /* Everything we need here should be included by lustreapi.h. */
10369 # error "lfs should not depend on lustre_idl.h"
10370 #endif /* _LUSTRE_IDL_H_ */