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