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