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