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