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