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