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