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