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