Whamcloud - gitweb
LU-15362 util: fix silent failure of component delete
[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  *
31  * lustre/utils/lfs.c
32  *
33  * Author: Peter J. Braam <braam@clusterfs.com>
34  * Author: Phil Schwan <phil@clusterfs.com>
35  * Author: Robert Read <rread@clusterfs.com>
36  */
37
38 /* for O_DIRECTORY */
39 #ifndef _GNU_SOURCE
40 #define _GNU_SOURCE
41 #endif
42
43 #include <stdlib.h>
44 #include <stdio.h>
45 #include <inttypes.h>
46 #include <getopt.h>
47 #include <string.h>
48 #include <mntent.h>
49 #include <unistd.h>
50 #include <errno.h>
51 #include <err.h>
52 #include <pwd.h>
53 #include <grp.h>
54 #include <sys/ioctl.h>
55 #include <sys/quota.h>
56 #include <sys/time.h>
57 #include <sys/types.h>
58 #include <sys/stat.h>
59 #include <sys/param.h>
60 #include <sys/xattr.h>
61 #include <fcntl.h>
62 #include <dirent.h>
63 #include <time.h>
64 #include <ctype.h>
65 #include <zlib.h>
66 #include <libgen.h>
67 #include <asm/byteorder.h>
68 #include "lfs_project.h"
69
70 #include <libcfs/util/string.h>
71 #include <libcfs/util/ioctl.h>
72 #include <libcfs/util/parser.h>
73 #include <libcfs/util/string.h>
74 #include <lustre/lustreapi.h>
75 #include <linux/lustre/lustre_ver.h>
76 #include <linux/lustre/lustre_param.h>
77 #include <linux/lnet/nidstr.h>
78 #include <lnetconfig/cyaml.h>
79 #include "lstddef.h"
80
81 /* all functions */
82 static int lfs_find(int argc, char **argv);
83 static int lfs_getstripe(int argc, char **argv);
84 static int lfs_getdirstripe(int argc, char **argv);
85 static int lfs_setdirstripe(int argc, char **argv);
86 static int lfs_rmentry(int argc, char **argv);
87 static int lfs_unlink_foreign(int argc, char **argv);
88 static int lfs_osts(int argc, char **argv);
89 static int lfs_mdts(int argc, char **argv);
90 static int lfs_df(int argc, char **argv);
91 static int lfs_getname(int argc, char **argv);
92 static int lfs_check(int argc, char **argv);
93 #ifdef HAVE_SYS_QUOTA_H
94 static int lfs_setquota(int argc, char **argv);
95 static int lfs_quota(int argc, char **argv);
96 static int lfs_project(int argc, char **argv);
97 #endif
98 static int lfs_flushctx(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_rmfid(int argc, char **argv);
105 static int lfs_data_version(int argc, char **argv);
106 static int lfs_hsm_state(int argc, char **argv);
107 static int lfs_hsm_set(int argc, char **argv);
108 static int lfs_hsm_clear(int argc, char **argv);
109 static int lfs_hsm_action(int argc, char **argv);
110 static int lfs_hsm_archive(int argc, char **argv);
111 static int lfs_hsm_restore(int argc, char **argv);
112 static int lfs_hsm_release(int argc, char **argv);
113 static int lfs_hsm_remove(int argc, char **argv);
114 static int lfs_hsm_cancel(int argc, char **argv);
115 static int lfs_swap_layouts(int argc, char **argv);
116 static int lfs_mv(int argc, char **argv);
117 static int lfs_ladvise(int argc, char **argv);
118 static int lfs_getsom(int argc, char **argv);
119 static int lfs_heat_get(int argc, char **argv);
120 static int lfs_heat_set(int argc, char **argv);
121 static int lfs_mirror(int argc, char **argv);
122 static int lfs_mirror_list_commands(int argc, char **argv);
123 static int lfs_list_commands(int argc, char **argv);
124 static inline int lfs_mirror_resync(int argc, char **argv);
125 static inline int lfs_mirror_verify(int argc, char **argv);
126 static inline int lfs_mirror_read(int argc, char **argv);
127 static inline int lfs_mirror_write(int argc, char **argv);
128 static inline int lfs_mirror_copy(int argc, char **argv);
129 static int lfs_pcc_attach(int argc, char **argv);
130 static int lfs_pcc_attach_fid(int argc, char **argv);
131 static int lfs_pcc_detach(int argc, char **argv);
132 static int lfs_pcc_detach_fid(int argc, char **argv);
133 static int lfs_pcc_state(int argc, char **argv);
134 static int lfs_pcc(int argc, char **argv);
135 static int lfs_pcc_list_commands(int argc, char **argv);
136 static int lfs_migrate_to_dom(int fd, int fdv, char *name,
137                               __u64 migration_flags);
138
139 struct pool_to_id_cbdata {
140         const char *pool;
141         __u32 id;
142 };
143 static int find_comp_id_by_pool(struct llapi_layout *layout, void *cbdata);
144 static int find_mirror_id_by_pool(struct llapi_layout *layout, void *cbdata);
145
146 enum setstripe_origin {
147         SO_SETSTRIPE,
148         SO_MIGRATE,
149         SO_MIGRATE_MDT,
150         SO_MIRROR_CREATE,
151         SO_MIRROR_EXTEND,
152         SO_MIRROR_SPLIT,
153         SO_MIRROR_DELETE,
154 };
155
156 static int lfs_setstripe_internal(int argc, char **argv,
157                                   enum setstripe_origin opc);
158
159 static inline int lfs_setstripe(int argc, char **argv)
160 {
161         return lfs_setstripe_internal(argc, argv, SO_SETSTRIPE);
162 }
163
164 static inline int lfs_setstripe_migrate(int argc, char **argv)
165 {
166         return lfs_setstripe_internal(argc, argv, SO_MIGRATE);
167 }
168
169 static inline int lfs_mirror_create(int argc, char **argv)
170 {
171         return lfs_setstripe_internal(argc, argv, SO_MIRROR_CREATE);
172 }
173
174 static inline int lfs_mirror_extend(int argc, char **argv)
175 {
176         return lfs_setstripe_internal(argc, argv, SO_MIRROR_EXTEND);
177 }
178
179 static inline int lfs_mirror_split(int argc, char **argv)
180 {
181         return lfs_setstripe_internal(argc, argv, SO_MIRROR_SPLIT);
182 }
183
184 static inline int lfs_mirror_delete(int argc, char **argv)
185 {
186         return lfs_setstripe_internal(argc, argv, SO_MIRROR_DELETE);
187 }
188
189 /* Setstripe and migrate share mostly the same parameters */
190 #define SSM_CMD_COMMON(cmd) \
191         "usage: "cmd" [--component-end|-E COMP_END]\n"                  \
192         "                 [--copy=LUSTRE_SRC]\n"                        \
193         "                 [--extension-size|--ext-size|-z SIZE]\n"      \
194         "                 [--help|-h] [--layout|-L PATTERN]\n"          \
195         "                 [--layout|-L PATTERN]\n"                      \
196         "                 [--mirror-count|-N[MIRROR_COUNT]]\n"          \
197         "                 [--ost|-o OST_INDICES]\n"                     \
198         "                 [--overstripe-count|-C STRIPE_COUNT]\n"       \
199         "                 [--pool|-p POOL_NAME]\n"                      \
200         "                 [--stripe-count|-c STRIPE_COUNT]\n"           \
201         "                 [--stripe-index|-i START_OST_IDX]\n"          \
202         "                 [--stripe-size|-S STRIPE_SIZE]\n"             \
203         "                 [--yaml|-y YAML_TEMPLATE_FILE]\n"
204
205 #define MIRROR_EXTEND_USAGE                                             \
206         "                 {--mirror-count|-N[MIRROR_COUNT]}\n"          \
207         "                 [SETSTRIPE_OPTIONS|-f|--file VICTIM_FILE]\n"  \
208         "                 [--no-verify]\n"
209
210 #define SETSTRIPE_USAGE                                                 \
211         SSM_CMD_COMMON("setstripe")                                     \
212         MIRROR_EXTEND_USAGE                                             \
213         "                 DIRECTORY|FILENAME\n"
214
215 #define MIGRATE_USAGE                                                   \
216         SSM_CMD_COMMON("migrate  ")                                     \
217         "                 [--block|-b] [--non-block|-n]\n"              \
218         "                 [--non-direct|-D] [--verbose|-v]\n"           \
219         "                 FILENAME\n"
220
221 #define SETDIRSTRIPE_USAGE                                              \
222         "               [--mdt-count|-c stripe_count>\n"                \
223         "               [--help|-h] [--mdt-hash|-H mdt_hash]\n"         \
224         "               [--mdt-index|-i mdt_index[,mdt_index,...]\n"    \
225         "               [--default|-D] [--mode|-o mode]\n"              \
226         "               [--max-inherit|-X max_inherit]\n"               \
227         "               [--max-inherit-rr max_inherit_rr] <dir>\n"      \
228         "To create dir with a foreign (free format) layout :\n"         \
229         "setdirstripe|mkdir --foreign[=FOREIGN_TYPE] -x|-xattr STRING " \
230         "               [--mode|-o MODE] [--flags HEX] DIRECTORY\n"
231
232 /**
233  * command_t mirror_cmdlist - lfs mirror commands.
234  */
235 command_t mirror_cmdlist[] = {
236         { .pc_name = "create", .pc_func = lfs_mirror_create,
237           .pc_help = "Create a mirrored file.\n"
238                 "usage: lfs mirror create --mirror-count|-N[MIRROR_COUNT]\n"
239                 "           [SETSTRIPE_OPTIONS] ... FILENAME|DIRECTORY ...\n" },
240         { .pc_name = "delete", .pc_func = lfs_mirror_delete,
241           .pc_help = "Delete a mirror from a file.\n"
242         "usage: lfs mirror delete {--mirror-id <mirror_id> |\n"
243         "\t               --component-id|--comp-id|-I COMP_ID |\n"
244         "\t               -p <pool>} MIRRORED_FILE ...\n"
245         },
246         { .pc_name = "extend", .pc_func = lfs_mirror_extend,
247           .pc_help = "Extend a mirrored file.\n"
248                 "usage: lfs mirror extend "
249                 "{--mirror-count|-N[MIRROR_COUNT]} [--no-verify] "
250                 "[SETSTRIPE_OPTIONS|-f VICTIM_FILE] ... FILENAME ...\n" },
251         { .pc_name = "split", .pc_func = lfs_mirror_split,
252           .pc_help = "Split a mirrored file.\n"
253         "usage: lfs mirror split {--mirror-id MIRROR_ID |\n"
254         "\t             --component-id|-I COMP_ID|-p POOL} [--destroy|-d]\n"
255         "\t             [-f NEW_FILE] MIRRORED_FILE ...\n" },
256         { .pc_name = "read", .pc_func = lfs_mirror_read,
257           .pc_help = "Read the content of a specified mirror of a file.\n"
258                 "usage: lfs mirror read {--mirror-id|-N MIRROR_ID}\n"
259                 "\t\t[--outfile|-o <output_file>] <mirrored_file>\n" },
260         { .pc_name = "write", .pc_func = lfs_mirror_write,
261           .pc_help = "Write to a specified mirror of a file.\n"
262                 "usage: lfs mirror write {--mirror-id|-N MIRROR_ID}\n"
263                 "\t\t[--inputfile|-i <input_file>] <mirrored_file>\n" },
264         { .pc_name = "copy", .pc_func = lfs_mirror_copy,
265           .pc_help = "Copy a specified mirror to other mirror(s) of a file.\n"
266                 "usage: lfs mirror copy {--read-mirror|-i MIRROR_ID0}\n"
267                 "\t\t{--write-mirror|-o MIRROR_ID1[,...]} <mirrored_file>\n" },
268         { .pc_name = "resync", .pc_func = lfs_mirror_resync,
269           .pc_help = "Resynchronizes out-of-sync mirrored file(s).\n"
270                 "usage: lfs mirror resync [--only MIRROR_ID[,...]>]\n"
271                 "\t\t<mirrored_file> [<mirrored_file2>...]\n" },
272         { .pc_name = "verify", .pc_func = lfs_mirror_verify,
273           .pc_help = "Verify mirrored file(s).\n"
274                 "usage: lfs mirror verify [--only MIRROR_ID[,...]]\n"
275                 "\t\t[--verbose|-v] <mirrored_file> [<mirrored_file2> ...]\n" },
276         { .pc_name = "list-commands", .pc_func = lfs_mirror_list_commands,
277           .pc_help = "list commands supported by lfs mirror"},
278         { .pc_name = "help", .pc_func = Parser_help, .pc_help = "help" },
279         { .pc_name = "exit", .pc_func = Parser_quit, .pc_help = "quit" },
280         { .pc_name = "quit", .pc_func = Parser_quit, .pc_help = "quit" },
281         { .pc_help = NULL }
282 };
283
284 /**
285  * command_t pcc_cmdlist - lfs pcc commands.
286  */
287 command_t pcc_cmdlist[] = {
288         { .pc_name = "attach", .pc_func = lfs_pcc_attach,
289           .pc_help = "Attach given files to the Persistent Client Cache.\n"
290                 "usage: lfs pcc attach <--id|-i NUM> <file> ...\n"
291                 "\t-i: archive id for RW-PCC\n" },
292         { .pc_name = "attach_fid", .pc_func = lfs_pcc_attach_fid,
293           .pc_help = "Attach given files into PCC by FID(s).\n"
294                 "usage: lfs pcc attach_id {--id|-i NUM} {--mnt|-m MOUNTPOINT} FID ...\n"
295                 "\t-i: archive id for RW-PCC\n"
296                 "\t-m: Lustre mount point\n" },
297         { .pc_name = "state", .pc_func = lfs_pcc_state,
298           .pc_help = "Display the PCC state for given files.\n"
299                 "usage: lfs pcc state <file> ...\n" },
300         { .pc_name = "detach", .pc_func = lfs_pcc_detach,
301           .pc_help = "Detach given files from the Persistent Client Cache.\n"
302                 "usage: lfs pcc detach <file> ...\n" },
303         { .pc_name = "detach_fid", .pc_func = lfs_pcc_detach_fid,
304           .pc_help = "Detach given files from PCC by FID(s).\n"
305                 "usage: lfs pcc detach_fid <mntpath> <fid>...\n" },
306         { .pc_name = "list-commands", .pc_func = lfs_pcc_list_commands,
307           .pc_help = "list commands supported by lfs pcc"},
308         { .pc_name = "help", .pc_func = Parser_help, .pc_help = "help" },
309         { .pc_name = "exit", .pc_func = Parser_quit, .pc_help = "quit" },
310         { .pc_name = "quit", .pc_func = Parser_quit, .pc_help = "quit" },
311         { .pc_help = NULL }
312 };
313
314 /* all available commands */
315 command_t cmdlist[] = {
316         {"setstripe", lfs_setstripe, 0,
317          "To create a file with specified striping/composite layout, or\n"
318          "create/replace the default layout on an existing directory:\n"
319          SSM_CMD_COMMON("setstripe")
320          "                 [--mode MODE]\n"
321          "                 <directory|filename>\n"
322          " or\n"
323          "To add component(s) to an existing composite file:\n"
324          SSM_CMD_COMMON("setstripe --component-add")
325          "To totally delete the default striping from an existing directory:\n"
326          "usage: setstripe [--delete|-d] <directory>\n"
327          " or\n"
328          "To create a mirrored file or set s default mirror layout on a directory:\n"
329          "usage: setstripe {--mirror-count|-N}[MIRROR_COUNT] [SETSTRIPE_OPTIONS] <directory|filename>\n"
330          " or\n"
331          "To delete the last component(s) from an existing composite file\n"
332          "(note that this will also delete any data in those components):\n"
333          "usage: setstripe --component-del [--component-id|-I COMP_ID]\n"
334          "                               [--component-flags|-F COMP_FLAGS]\n"
335          "                               <filename>\n"
336          "\tCOMP_ID:     Unique component ID to delete\n"
337          "\tCOMP_FLAGS:  'init' indicating all instantiated components\n"
338          "\t             '^init' indicating all uninstantiated components\n"
339          "\t-I and -F cannot be specified at the same time\n"
340          " or\n"
341          "To set or clear flags on a specific component\n"
342          "(note that this command can only be applied to mirrored files:\n"
343          "usage: setstripe --comp-set {-I COMP_ID|--comp-flags=COMP_FLAGS}\n"
344          "                            <filename>\n"
345          " or\n"
346          "To create a file with a foreign (free format) layout:\n"
347          "usage: setstripe --foreign[=FOREIGN_TYPE]\n"
348          "                 --xattr|-x LAYOUT_STRING [--flags HEX]\n"
349          "                 [--mode MODE] <filename>\n"},
350         {"getstripe", lfs_getstripe, 0,
351          "To list the layout pattern for a given file or files in a\n"
352          "directory or recursively for all files in a directory tree.\n"
353          "usage: getstripe [--ost|-O UUID] [--quiet|-q] [--verbose|-v]\n"
354          "                 [--stripe-count|-c] [--stripe-index|-i] [--fid|-F]\n"
355          "                 [--pool|-p] [--stripe-size|-S] [--directory|-d]\n"
356          "                 [--mdt-index|-m] [--recursive|-r] [--raw|-R]\n"
357          "                 [--layout|-L] [--generation|-g] [--yaml|-y]\n"
358          "                 [--help|-h] [--component-id|-I[=COMP_ID]]\n"
359          "                 [--component-flags[=COMP_FLAGS]]\n"
360          "                 [--component-count]\n"
361          "                 [--extension-size|--ext-size|-z]\n"
362          "                 [--component-start[=[+-]COMP_START]]\n"
363          "                 [--component-end[=[+-]COMP_END]|-E[[+-]comp_end]]\n"
364          "                 [[!] --mirror-index=[+-]INDEX |\n"
365          "                 [!] --mirror-id=[+-]MIRROR_ID] [--mirror-count|-N]\n"
366          "                 <directory|filename> ..."},
367         {"setdirstripe", lfs_setdirstripe, 0,
368          "Create striped directory on specified MDT, same as mkdir.\n"
369          "May be restricted to root or group users, depending on settings.\n"
370          "usage: setdirstripe [OPTION] <directory>\n"
371          SETDIRSTRIPE_USAGE},
372         {"getdirstripe", lfs_getdirstripe, 0,
373          "To list the layout pattern info for a given directory\n"
374          "or recursively for all directories in a directory tree.\n"
375          "usage: getdirstripe [--mdt-count|-c] [--mdt-index|-m|-i]\n"
376          "                    [--help|-h] [--mdt-hash|-H] [--obd|-O UUID]\n"
377          "                    [--recursive|-r] [--yaml|-y]\n"
378          "                    [--verbose|-v] [--default|-D]\n"
379          "                    [--max-inherit|-X]\n"
380          "                    [--max-inherit-rr] <dir> ..."},
381         {"mkdir", lfs_setdirstripe, 0,
382          "Create striped directory on specified MDT, same as setdirstripe.\n"
383          "usage: mkdir [OPTION] <directory>\n"
384          SETDIRSTRIPE_USAGE},
385         {"rm_entry", lfs_rmentry, 0,
386          "To remove the name entry of the remote directory. Note: This\n"
387          "command will only delete the name entry, i.e. the remote directory\n"
388          "will become inaccessable after this command. This can only be done\n"
389          "by the administrator\n"
390          "usage: rm_entry <dir>\n"},
391         {"unlink_foreign", lfs_unlink_foreign, 0,
392          "To remove the foreign file/dir.\n"
393          "Note: This is for files/dirs prevented to be removed using\n"
394          "unlink/rmdir, but works also for regular ones\n"
395          "usage: unlink_foreign <foreign_dir/file> [<foreign_dir/file> ...]\n"},
396         {"pool_list", lfs_poollist, 0,
397          "List pools or pool OSTs\n"
398          "usage: pool_list <fsname>[.<pool>] | <pathname>\n"},
399         {"find", lfs_find, 0,
400          "find files matching given attributes recursively in directory tree.\n"
401          "usage: find <directory|filename> ...\n"
402          "     [[!] --atime|-A [+-]N[smhdwy]] [[!] --btime|-B [+-]N[smhdwy]]\n"
403          "     [[!] --ctime|-C [+-]N[smhdwy]] [[!] --mtime|-M [+-]N[smhdwy]]\n"
404          "     [[!] --blocks|-b N] [[!] --component-count [+-]<comp_cnt>]\n"
405          "     [[!] --component-start [+-]N[kMGTPE]]\n"
406          "     [[!] --component-end|-E [+-]N[kMGTPE]]\n"
407          "     [[!] --component-flags {init,stale,prefer,offline,nosync,extension}]\n"
408          "     [[!] --extension-size|--ext-size|-z [+-]N[kMGT]]\n"
409          "     [[!] --foreign[=<foreign_type>]]\n"
410          "     [[!] --gid|-g|--group|-G <gid>|<gname>] [--help|-h]\n"
411          "     [[!] --layout|-L released,raid0,mdt] [--lazy]\n"
412          "     [--maxdepth|-D N] [[!] --mdt-count|-T [+-]<stripes>]\n"
413          "     [[!] --mdt-hash|-H <[^][blm],[^]fnv_1a_64,all_char,crush,...>\n"
414          "     [[!] --mdt-index|--mdt|-m <uuid|index,...>]\n"
415          "     [[!] --mirror-count|-N [+-]<n>]\n"
416          "     [[!] --mirror-state <[^]state>]\n"
417          "     [[!] --name|-n <pattern>] [[!] --newer[XY] <reference>]\n"
418          "     [[!] --ost|-O <uuid|index,...>] [[!] --perm [/-]mode]\n"
419          "     [[!] --pool <pool>] [--print|-P] [--print0|-0]\n"
420          "     [[!] --projid <projid>] [[!] --size|-s [+-]N[bkMGTPE]]\n"
421          "     [[!] --stripe-count|-c [+-]<stripes>]\n"
422          "     [[!] --stripe-index|-i <index,...>]\n"
423          "     [[!] --stripe-size|-S [+-]N[kMGT]] [[!] --type|-t <filetype>]\n"
424          "     [[!] --uid|-u|--user|-U <uid>|<uname>]\n"
425          "\t !: used before an option indicates 'NOT' requested attribute\n"
426          "\t -: used before a value indicates less than requested value\n"
427          "\t +: used before a value indicates more than requested value\n"
428          "\t ^: used before a flag indicates to exclude it\n"},
429         {"check", lfs_check, 0,
430          "Display the status of MGTs, MDTs or OSTs (as specified in the command)\n"
431          "or all the servers (MGTs, MDTs and OSTs).\n"
432          "usage: check {mgts|osts|mdts|all}"},
433         {"osts", lfs_osts, 0, "list OSTs connected to client "
434          "[for specified path only]\n" "usage: osts [path]"},
435         {"mdts", lfs_mdts, 0, "list MDTs connected to client "
436          "[for specified path only]\n" "usage: mdts [path]"},
437         {"df", lfs_df, 0,
438          "report filesystem disk space usage or inodes usage "
439          "of each MDS and all OSDs or a batch belonging to a specific pool.\n"
440          "Usage: df [--inodes|-i] [--human-readable|-h] [--lazy|-l]\n"
441          "          [--pool|-p <fsname>[.<pool>]] [path]"},
442         {"getname", lfs_getname, 0,
443          "list instances and specified mount points [for specified path only]\n"
444          "Usage: getname [--help|-h] [--instance|-i] [--fsname|-n] [path ...]"},
445 #ifdef HAVE_SYS_QUOTA_H
446         {"setquota", lfs_setquota, 0, "Set filesystem quotas.\n"
447          "usage: setquota [-t][-d] {-u|-U|-g|-G|-p|-P} {-b|-B|-i|-I LIMIT} [--pool POOL] FILESYSTEM"},
448         {"quota", lfs_quota, 0, "Display disk usage and limits.\n"
449          "usage: quota [-q] [-v] [-h] [-o OBD_UUID|-i MDT_IDX|-I OST_IDX]\n"
450          "             [{-u|-g|-p} UNAME|UID|GNAME|GID|PROJID]\n"
451          "             [--pool <OST pool name>] <filesystem>\n"
452          "       quota -t <-u|-g|-p> [--pool <OST pool name>] <filesystem>\n"
453          "       quota [-q] [-v] [h] {-U|-G|-P} [--pool <OST pool name>] <filesystem>"},
454         {"project", lfs_project, 0,
455          "Change or list project attribute for specified file or directory.\n"
456          "usage: project [-d|-r] <file|directory...>\n"
457          "         list project ID and flags on file(s) or directories\n"
458          "       project [-p id] [-s] [-r] <file|directory...>\n"
459          "         set project ID and/or inherit flag for specified file(s) or directories\n"
460          "       project -c [-d|-r [-p id] [-0]] <file|directory...>\n"
461          "         check project ID and flags on file(s) or directories, print outliers\n"
462          "       project -C [-r] [-k] <file|directory...>\n"
463          "         clear the project inherit flag and ID on the file or directory\n"
464         },
465 #endif
466         {"flushctx", lfs_flushctx, 0,
467          "Flush security context for current user.\n"
468          "usage: flushctx [-k] [-r] [mountpoint...]"},
469         {"changelog", lfs_changelog, 0,
470          "Show the metadata changes on an MDT."
471          "\nusage: changelog <mdtname> [startrec [endrec]]"},
472         {"changelog_clear", lfs_changelog_clear, 0,
473          "Indicate that old changelog records up to <endrec> are no longer of "
474          "interest to consumer <id>, allowing the system to free up space.\n"
475          "An <endrec> of 0 means all records.\n"
476          "usage: changelog_clear <mdtname> <id> <endrec>"},
477         {"fid2path", lfs_fid2path, 0,
478          "Resolve the full path(s) for given FID(s). For a specific hardlink "
479          "specify link number <linkno>.\n"
480          "usage: fid2path [--print-fid|-f] [--print-link|-c] [--link|-l <linkno>] "
481          "<fsname|root> <fid>..."},
482         {"path2fid", lfs_path2fid, 0, "Display the fid(s) for a given path(s).\n"
483          "usage: path2fid [--parents] <path> ..."},
484         {"rmfid", lfs_rmfid, 0, "Remove file(s) by FID(s)\n"
485          "usage: rmfid <fsname|rootpath> <fid> ..."},
486         {"data_version", lfs_data_version, 0, "Display file data version for "
487          "a given path.\n" "usage: data_version [-n|-r|-w] <path>"},
488         {"hsm_state", lfs_hsm_state, 0, "Display the HSM information (states, "
489          "undergoing actions) for given files.\n usage: hsm_state <file> ..."},
490         {"hsm_set", lfs_hsm_set, 0, "Set HSM user flag on specified files.\n"
491          "usage: hsm_set [--norelease] [--noarchive] [--dirty] [--exists] "
492          "[--archived] [--lost] [--archive-id NUM] <file> ..."},
493         {"hsm_clear", lfs_hsm_clear, 0, "Clear HSM user flag on specified "
494          "files.\n"
495          "usage: hsm_clear [--norelease] [--noarchive] [--dirty] [--exists] "
496          "[--archived] [--lost] <file> ..."},
497         {"hsm_action", lfs_hsm_action, 0, "Display current HSM request for "
498          "given files.\n" "usage: hsm_action <file> ..."},
499         {"hsm_archive", lfs_hsm_archive, 0,
500          "Archive file to external storage.\n"
501          "usage: hsm_archive [--filelist FILELIST] [--data DATA] [--archive NUM] "
502          "<file> ..."},
503         {"hsm_restore", lfs_hsm_restore, 0,
504          "Restore file from external storage.\n"
505          "usage: hsm_restore [--filelist FILELIST] [--data DATA] <file> ..."},
506         {"hsm_release", lfs_hsm_release, 0,
507          "Release files from Lustre.\n"
508          "usage: hsm_release [--filelist FILELIST] [--data DATA] <file> ..."},
509         {"hsm_remove", lfs_hsm_remove, 0,
510          "Remove file copy from external storage.\n"
511          "usage: hsm_remove [--filelist FILELIST] [--data DATA] "
512          "[--archive NUM]\n"
513          "                  (FILE [FILE ...] | "
514          "--mntpath MOUNTPATH FID [FID ...])\n"
515          "\n"
516          "Note: To remove an archived copy of a file already deleted from a "
517          "Lustre FS, the\n"
518          "--mntpath option and a list of FIDs must be specified"
519         },
520         {"hsm_cancel", lfs_hsm_cancel, 0,
521          "Cancel requests related to specified files.\n"
522          "usage: hsm_cancel [--filelist FILELIST] [--data DATA] <file> ..."},
523         {"swap_layouts", lfs_swap_layouts, 0, "Swap layouts between 2 files.\n"
524          "usage: swap_layouts <path1> <path2>"},
525         {"migrate", lfs_setstripe_migrate, 0,
526          "migrate directories and their inodes between MDTs.\n"
527          "usage: migrate [--mdt-count|-c STRIPE_COUNT] [--directory|-d]\n"
528          "               [--mdt-hash|-H HASH_TYPE]\n"
529          "               [--mdt-index|-m START_MDT_INDEX] [--verbose|-v]\n"
530          "               DIRECTORY\n"
531          "\n"
532          "migrate file objects from one OST layout to another\n"
533          "(may be not safe with concurent writes).\n"
534          MIGRATE_USAGE },
535         {"mv", lfs_mv, 0,
536          "To move directories between MDTs. This command is deprecated, "
537          "use \"migrate\" instead.\n"
538          "usage: mv <directory|filename> [--mdt-index|-m MDT_INDEX] "
539          "[--verbose|-v]\n"},
540         {"ladvise", lfs_ladvise, 0,
541          "Provide servers with advice about access patterns for a file.\n"
542          "usage: ladvise [--advice|-a ADVICE] [--start|-s START[kMGT]]\n"
543          "               [--background|-b] [--unset|-u]\n\n"
544          "               {--end|-e END[kMGT]|--length|-l LENGTH[kMGT]}\n"
545          "               {[--mode|-m [READ,WRITE]}\n"
546          "               <file> ...\n"},
547         {"mirror", lfs_mirror, mirror_cmdlist,
548          "lfs commands used to manage files with mirrored components:\n"
549          "lfs mirror create - create a mirrored file or directory\n"
550          "lfs mirror extend - add mirror(s) to an existing file\n"
551          "lfs mirror split  - split a mirror from an existing mirrored file\n"
552          "lfs mirror resync - resynchronize out-of-sync mirrored file(s)\n"
553          "lfs mirror read   - read a mirror content of a mirrored file\n"
554          "lfs mirror write  - write to a mirror of a mirrored file\n"
555          "lfs mirror copy   - copy a mirror to other mirror(s) of a file\n"
556          "lfs mirror verify - verify mirrored file(s)\n"},
557         {"getsom", lfs_getsom, 0, "To list the SOM info for a given file.\n"
558          "usage: getsom [-s] [-b] [-f] <path>\n"
559          "\t-s: Only show the size value of the SOM data for a given file\n"
560          "\t-b: Only show the blocks value of the SOM data for a given file\n"
561          "\t-f: Only show the flags value of the SOM data for a given file\n"},
562         {"heat_get", lfs_heat_get, 0,
563          "To get heat of files.\n"
564          "usage: heat_get <file> ...\n"},
565         {"heat_set", lfs_heat_set, 0,
566          "To set heat flags of files.\n"
567          "usage: heat_set [--clear|-c] [--off|-o] [--on|-O] <file> ...\n"
568          "\t--clear|-c: Clear file heat for given files\n"
569          "\t--off|-o:   Turn off file heat for given files\n"
570          "\t--on|-O:    Turn on file heat for given files\n"},
571         {"pcc", lfs_pcc, pcc_cmdlist,
572          "lfs commands used to interact with PCC features:\n"
573          "lfs pcc attach - attach given files to Persistent Client Cache\n"
574          "lfs pcc attach_fid - attach given files into PCC by FID(s)\n"
575          "lfs pcc state  - display the PCC state for given files\n"
576          "lfs pcc detach - detach given files from Persistent Client Cache\n"
577          "lfs pcc detach_fid - detach given files from PCC by FID(s)\n"},
578         {"help", Parser_help, 0, "help"},
579         {"exit", Parser_quit, 0, "quit"},
580         {"quit", Parser_quit, 0, "quit"},
581         {"--version", Parser_version, 0,
582          "output build version of the utility and exit"},
583         {"--list-commands", lfs_list_commands, 0,
584          "list commands supported by the utility and exit"},
585         { 0, 0, 0, NULL }
586 };
587
588 static int check_hashtype(const char *hashtype)
589 {
590         int type_num = atoi(hashtype);
591         int i;
592
593         /* numeric hash type */
594         if (hashtype && strlen(hashtype) == 1 &&
595             (type_num > 0 && type_num < LMV_HASH_TYPE_MAX))
596                 return type_num;
597         /* string hash type */
598         for (i = LMV_HASH_TYPE_ALL_CHARS; i < LMV_HASH_TYPE_MAX; i++)
599                 if (strcmp(hashtype, mdt_hash_name[i]) == 0)
600                         return i;
601
602         return 0;
603 }
604
605 static uint32_t check_foreign_type_name(const char *foreign_type_name)
606 {
607         uint32_t i;
608
609         for (i = 0; i < LU_FOREIGN_TYPE_UNKNOWN; i++) {
610                 if (!lu_foreign_types[i].lft_name)
611                         break;
612                 if (strcmp(foreign_type_name,
613                            lu_foreign_types[i].lft_name) == 0)
614                         return lu_foreign_types[i].lft_type;
615         }
616
617         return LU_FOREIGN_TYPE_UNKNOWN;
618 }
619
620 static const char *error_loc = "syserror";
621
622 static int
623 migrate_open_files(const char *name, __u64 migration_flags,
624                    const struct llapi_stripe_param *param,
625                    struct llapi_layout *layout, int *fd_src, int *fd_tgt)
626 {
627         int                      fd = -1;
628         int                      fdv = -1;
629         int                      rflags;
630         int                      mdt_index;
631         int                      random_value;
632         char                     parent[PATH_MAX];
633         char                     volatile_file[PATH_MAX];
634         char                    *ptr;
635         int                      rc;
636         struct stat              st;
637         struct stat              stv;
638
639         if (!param && !layout) {
640                 error_loc = "layout information";
641                 return -EINVAL;
642         }
643
644         /* search for file directory pathname */
645         if (strlen(name) > sizeof(parent) - 1) {
646                 error_loc = "source file name";
647                 return -ERANGE;
648         }
649
650         strncpy(parent, name, sizeof(parent));
651         ptr = strrchr(parent, '/');
652         if (!ptr) {
653                 if (!getcwd(parent, sizeof(parent))) {
654                         error_loc = "getcwd";
655                         return -errno;
656                 }
657         } else {
658                 if (ptr == parent) /* leading '/' */
659                         ptr = parent + 1;
660                 *ptr = '\0';
661         }
662
663         /* even if the file is only read, WR mode is nedeed to allow
664          * layout swap on fd
665          */
666         /* Allow migrating even without the key on encrypted files */
667         rflags = O_RDWR | O_NOATIME | O_FILE_ENC;
668         if (!(migration_flags & LLAPI_MIGRATION_NONDIRECT))
669                 rflags |= O_DIRECT;
670 source_open:
671         fd = open(name, rflags);
672         if (fd < 0) {
673                 /* If encrypted file without the key,
674                  * retry mirror extend in O_DIRECT.
675                  */
676                 if (errno == ENOKEY && !(rflags & O_DIRECT) &&
677                     migration_flags & LLAPI_MIGRATION_MIRROR) {
678                         rflags |= O_DIRECT;
679                         goto source_open;
680                 }
681                 rc = -errno;
682                 error_loc = "cannot open source file";
683                 return rc;
684         }
685
686         rc = llapi_file_fget_mdtidx(fd, &mdt_index);
687         if (rc < 0) {
688                 error_loc = "cannot get MDT index";
689                 goto out;
690         }
691
692         do {
693                 int open_flags = O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW |
694                         /* Allow migrating without the key on encrypted files */
695                         O_FILE_ENC;
696                 mode_t open_mode = S_IRUSR | S_IWUSR;
697
698                 if (rflags & O_DIRECT)
699                         open_flags |= O_DIRECT;
700                 random_value = random();
701                 rc = snprintf(volatile_file, sizeof(volatile_file),
702                               "%s/%s:%.4X:%.4X:fd=%.2d", parent,
703                               LUSTRE_VOLATILE_HDR, mdt_index,
704                               random_value, fd);
705                 if (rc >= sizeof(volatile_file)) {
706                         rc = -ENAMETOOLONG;
707                         break;
708                 }
709
710                 /* create, open a volatile file, use caching (ie no directio) */
711                 if (layout) {
712                         /* Returns -1 and sets errno on error: */
713                         fdv = llapi_layout_file_open(volatile_file, open_flags,
714                                                      open_mode, layout);
715                         if (fdv < 0)
716                                 fdv = -errno;
717                 } else {
718                         /* Does the right thing on error: */
719                         fdv = llapi_file_open_param(volatile_file, open_flags,
720                                                     open_mode, param);
721                 }
722         } while (fdv < 0 && (rc = fdv) == -EEXIST);
723
724         if (rc < 0) {
725                 error_loc = "cannot create volatile file";
726                 goto out;
727         }
728
729         /*
730          * In case the MDT does not support creation of volatile files
731          * we should try to unlink it.
732          */
733         (void)unlink(volatile_file);
734
735         /*
736          * Not-owner (root?) special case.
737          * Need to set owner/group of volatile file like original.
738          * This will allow to pass related check during layout_swap.
739          */
740         rc = fstat(fd, &st);
741         if (rc != 0) {
742                 rc = -errno;
743                 error_loc = "cannot stat source file";
744                 goto out;
745         }
746
747         rc = fstat(fdv, &stv);
748         if (rc != 0) {
749                 rc = -errno;
750                 error_loc = "cannot stat volatile";
751                 goto out;
752         }
753
754         if (st.st_uid != stv.st_uid || st.st_gid != stv.st_gid) {
755                 rc = fchown(fdv, st.st_uid, st.st_gid);
756                 if (rc != 0) {
757                         rc = -errno;
758                         error_loc = "cannot change ownwership of volatile";
759                         goto out;
760                 }
761         }
762
763 out:
764         if (rc < 0) {
765                 if (fd > 0)
766                         close(fd);
767                 if (fdv > 0)
768                         close(fdv);
769         } else {
770                 *fd_src = fd;
771                 *fd_tgt = fdv;
772                 error_loc = NULL;
773         }
774         return rc;
775 }
776
777 static int migrate_copy_data(int fd_src, int fd_dst, int (*check_file)(int))
778 {
779         struct llapi_layout *layout;
780         size_t buf_size = 4 * 1024 * 1024;
781         void *buf = NULL;
782         off_t pos = 0;
783         off_t data_end = 0;
784         size_t page_size = sysconf(_SC_PAGESIZE);
785         bool sparse;
786         int rc;
787
788         layout = llapi_layout_get_by_fd(fd_src, 0);
789         if (layout) {
790                 uint64_t stripe_size;
791
792                 rc = llapi_layout_stripe_size_get(layout, &stripe_size);
793                 if (rc == 0)
794                         buf_size = stripe_size;
795
796                 llapi_layout_free(layout);
797         }
798
799         /* Use a page-aligned buffer for direct I/O */
800         rc = posix_memalign(&buf, page_size, buf_size);
801         if (rc != 0)
802                 return -rc;
803
804         sparse = llapi_file_is_sparse(fd_src);
805         if (sparse) {
806                 rc = ftruncate(fd_dst, pos);
807                 if (rc < 0) {
808                         rc = -errno;
809                         return rc;
810                 }
811         }
812
813         while (1) {
814                 off_t data_off;
815                 size_t to_read, to_write;
816                 ssize_t rsize;
817
818                 if (sparse && pos >= data_end) {
819                         size_t data_size;
820
821                         data_off = llapi_data_seek(fd_src, pos, &data_size);
822                         if (data_off < 0) {
823                                 /* Non-fatal, switch to full copy */
824                                 sparse = false;
825                                 continue;
826                         }
827                         /* hole at the end of file, truncate up to it */
828                         if (!data_size) {
829                                 rc = ftruncate(fd_dst, data_off);
830                                 if (rc < 0)
831                                         goto out;
832                         }
833                         pos = data_off & ~(page_size - 1);
834                         data_end = data_off + data_size;
835                         to_read = ((data_end - pos - 1) | (page_size - 1)) + 1;
836                         to_read = MIN(to_read, buf_size);
837                 } else {
838                         to_read = buf_size;
839                 }
840
841                 if (check_file) {
842                         rc = check_file(fd_src);
843                         if (rc < 0)
844                                 goto out;
845                 }
846
847                 rsize = pread(fd_src, buf, to_read, pos);
848                 if (rsize < 0) {
849                         rc = -errno;
850                         goto out;
851                 }
852                 /* EOF */
853                 if (rsize == 0)
854                         break;
855
856                 to_write = rsize;
857                 while (to_write > 0) {
858                         ssize_t written;
859
860                         written = pwrite(fd_dst, buf, to_write, pos);
861                         if (written < 0) {
862                                 rc = -errno;
863                                 goto out;
864                         }
865                         pos += written;
866                         to_write -= written;
867                 }
868                 if (rc || rsize < to_read)
869                         break;
870         }
871
872         rc = fsync(fd_dst);
873         if (rc < 0)
874                 rc = -errno;
875 out:
876         /* Try to avoid page cache pollution after migration. */
877         (void)posix_fadvise(fd_src, 0, 0, POSIX_FADV_DONTNEED);
878         (void)posix_fadvise(fd_dst, 0, 0, POSIX_FADV_DONTNEED);
879
880         free(buf);
881         return rc;
882 }
883
884 static int migrate_set_timestamps(int fd, const struct stat *st)
885 {
886         struct timeval tv[2] = {
887                 {.tv_sec = st->st_atime},
888                 {.tv_sec = st->st_mtime}
889         };
890
891         return futimes(fd, tv);
892 }
893
894 static int migrate_block(int fd, int fdv)
895 {
896         struct stat st;
897         __u64   dv1;
898         int     gid;
899         int     rc;
900         int     rc2;
901
902         rc = fstat(fd, &st);
903         if (rc < 0) {
904                 error_loc = "cannot stat source file";
905                 return -errno;
906         }
907
908         rc = llapi_get_data_version(fd, &dv1, LL_DV_RD_FLUSH);
909         if (rc < 0) {
910                 error_loc = "cannot get dataversion";
911                 return rc;
912         }
913
914         do
915                 gid = random();
916         while (gid == 0);
917
918         /*
919          * The grouplock blocks all concurrent accesses to the file.
920          * It has to be taken after llapi_get_data_version as it would
921          * block it too.
922          */
923         rc = llapi_group_lock(fd, gid);
924         if (rc < 0) {
925                 error_loc = "cannot get group lock";
926                 return rc;
927         }
928
929         rc = migrate_copy_data(fd, fdv, NULL);
930         if (rc < 0) {
931                 error_loc = "data copy failed";
932                 goto out_unlock;
933         }
934
935         /* Make sure we keep original atime/mtime values */
936         rc = migrate_set_timestamps(fdv, &st);
937         if (rc < 0) {
938                 error_loc = "set target file timestamp failed";
939                 goto out_unlock;
940         }
941
942         /*
943          * swap layouts
944          * for a migration we need to check data version on file did
945          * not change.
946          *
947          * Pass in gid=0 since we already own grouplock.
948          */
949         rc = llapi_fswap_layouts_grouplock(fd, fdv, dv1, 0, 0,
950                                            SWAP_LAYOUTS_CHECK_DV1);
951         if (rc == -EAGAIN) {
952                 error_loc = "file changed";
953                 goto out_unlock;
954         } else if (rc < 0) {
955                 error_loc = "cannot swap layout";
956                 goto out_unlock;
957         }
958
959 out_unlock:
960         rc2 = llapi_group_unlock(fd, gid);
961         if (rc2 < 0 && rc == 0) {
962                 error_loc = "unlock group lock";
963                 rc = rc2;
964         }
965
966         return rc;
967 }
968
969 /**
970  * Internal helper for migrate_copy_data(). Check lease and report error if
971  * need be.
972  *
973  * \param[in]  fd           File descriptor on which to check the lease.
974  *
975  * \retval 0       Migration can keep on going.
976  * \retval -errno  Error occurred, abort migration.
977  */
978 static int check_lease(int fd)
979 {
980         int rc;
981
982         rc = llapi_lease_check(fd);
983         if (rc > 0)
984                 return 0; /* llapi_check_lease returns > 0 on success. */
985
986         return -EBUSY;
987 }
988
989 static int migrate_nonblock(int fd, int fdv)
990 {
991         struct stat st;
992         __u64   dv1;
993         __u64   dv2;
994         int     rc;
995
996         rc = fstat(fd, &st);
997         if (rc < 0) {
998                 error_loc = "cannot stat source file";
999                 return -errno;
1000         }
1001
1002         rc = llapi_get_data_version(fd, &dv1, LL_DV_RD_FLUSH);
1003         if (rc < 0) {
1004                 error_loc = "cannot get data version";
1005                 return rc;
1006         }
1007
1008         rc = migrate_copy_data(fd, fdv, check_lease);
1009         if (rc < 0) {
1010                 error_loc = "data copy failed";
1011                 return rc;
1012         }
1013
1014         rc = llapi_get_data_version(fd, &dv2, LL_DV_RD_FLUSH);
1015         if (rc != 0) {
1016                 error_loc = "cannot get data version";
1017                 return rc;
1018         }
1019
1020         if (dv1 != dv2) {
1021                 rc = -EAGAIN;
1022                 error_loc = "source file changed";
1023                 return rc;
1024         }
1025
1026         /* Make sure we keep original atime/mtime values */
1027         rc = migrate_set_timestamps(fdv, &st);
1028         if (rc < 0) {
1029                 error_loc = "set target file timestamp failed";
1030                 return -errno;
1031         }
1032         return 0;
1033 }
1034
1035 static
1036 int lfs_layout_compid_by_pool(char *fname, const char *pool, int *comp_id)
1037 {
1038         struct pool_to_id_cbdata data = { .pool = pool };
1039         struct llapi_layout *layout = NULL;
1040         int rc;
1041
1042         layout = llapi_layout_get_by_path(fname, 0);
1043         if (!layout) {
1044                 fprintf(stderr,
1045                         "error %s: file '%s' couldn't get layout: rc=%d\n",
1046                         progname, fname, errno);
1047                 rc = -errno;
1048                 goto free_layout;
1049         }
1050         rc = llapi_layout_sanity(layout, fname, false, true);
1051         if (rc < 0) {
1052                 llapi_layout_sanity_perror(errno);
1053                 goto free_layout;
1054         }
1055         rc = llapi_layout_comp_iterate(layout, find_comp_id_by_pool, &data);
1056         if (rc < 0)
1057                 goto free_layout;
1058
1059         *comp_id = data.id;
1060         rc = 0;
1061
1062 free_layout:
1063         if (layout)
1064                 llapi_layout_free(layout);
1065         return rc;
1066 }
1067
1068 static int lfs_component_set(char *fname, int comp_id, const char *pool,
1069                              __u32 flags, __u32 neg_flags)
1070 {
1071         __u32 ids[2];
1072         __u32 flags_array[2];
1073         size_t count = 0;
1074         int rc;
1075
1076         if (!comp_id) {
1077                 if (pool == NULL) {
1078                         fprintf(stderr,
1079                                 "error %s: neither component id nor pool is specified\n",
1080                                 progname);
1081                         return -EINVAL;
1082                 }
1083                 rc = lfs_layout_compid_by_pool(fname, pool, &comp_id);
1084                 if (rc)
1085                         return rc;
1086         }
1087
1088         if (flags) {
1089                 ids[count] = comp_id;
1090                 flags_array[count] = flags;
1091                 ++count;
1092         }
1093
1094         if (neg_flags) {
1095                 if (neg_flags & LCME_FL_STALE) {
1096                         fprintf(stderr,
1097                                 "%s: cannot clear 'stale' flags from component. Please use lfs-mirror-resync(1) instead\n",
1098                                 progname);
1099                         return -EINVAL;
1100                 }
1101
1102                 ids[count] = comp_id;
1103                 flags_array[count] = neg_flags | LCME_FL_NEG;
1104                 ++count;
1105         }
1106
1107         rc = llapi_layout_file_comp_set(fname, ids, flags_array, count);
1108         if (rc) {
1109                 if (errno == EUCLEAN) {
1110                         rc = -errno;
1111                         fprintf(stderr,
1112                                 "%s: cannot set 'stale' flag on component '%#x' of the last non-stale mirror of '%s'\n",
1113                                 progname, comp_id, fname);
1114                 } else {
1115                         fprintf(stderr,
1116                                 "%s: cannot change the flags of component '%#x' of file '%s': %x / ^(%x)\n",
1117                                 progname, comp_id, fname, flags, neg_flags);
1118                 }
1119         }
1120
1121         return rc;
1122 }
1123
1124 static int lfs_component_del(char *fname, __u32 comp_id,
1125                              __u32 flags, __u32 neg_flags)
1126 {
1127         int     rc = 0;
1128
1129         if (flags && neg_flags) {
1130                 fprintf(stderr,
1131                         "%s: cannot specify both positive and negative flags\n",
1132                         progname);
1133                 return -EINVAL;
1134         }
1135
1136         if (!flags && neg_flags)
1137                 flags = neg_flags | LCME_FL_NEG;
1138
1139         if (flags && comp_id) {
1140                 fprintf(stderr,
1141                         "%s: cannot specify component ID and flags at the same time\n",
1142                         progname);
1143                 return -EINVAL;
1144         }
1145
1146         if (!flags && !comp_id) {
1147                 fprintf(stderr,
1148                         "%s: neither flags nor component ID is specified\n",
1149                         progname);
1150                 return -EINVAL;
1151         }
1152
1153         if (flags) {
1154                 if (flags & ~LCME_KNOWN_FLAGS) {
1155                         fprintf(stderr,
1156                                 "%s setstripe: unknown flags %#x\n",
1157                                 progname, flags);
1158                         return -EINVAL;
1159                 }
1160         } else if (comp_id > LCME_ID_MAX) {
1161                 fprintf(stderr, "%s setstripe: invalid component id %u\n",
1162                         progname, comp_id);
1163                 return -EINVAL;
1164         }
1165
1166         rc = llapi_layout_file_comp_del(fname, comp_id, flags);
1167         if (rc)
1168                 fprintf(stderr,
1169                         "%s setstripe: cannot delete component %#x from '%s': %s\n",
1170                         progname, comp_id, fname, strerror(errno));
1171         return rc;
1172 }
1173
1174 static int lfs_component_add(char *fname, struct llapi_layout *layout)
1175 {
1176         int     rc;
1177
1178         if (!layout)
1179                 return -EINVAL;
1180
1181         rc = llapi_layout_file_comp_add(fname, layout);
1182         if (rc)
1183                 fprintf(stderr, "Add layout component(s) to %s failed. %s\n",
1184                         fname, strerror(errno));
1185         return rc;
1186 }
1187
1188 static int lfs_component_create(char *fname, int open_flags, mode_t open_mode,
1189                                 struct llapi_layout *layout)
1190 {
1191         struct stat     st;
1192         int     fd;
1193
1194         if (!layout)
1195                 return -EINVAL;
1196
1197         fd = lstat(fname, &st);
1198         if (fd == 0 && S_ISDIR(st.st_mode))
1199                 open_flags = O_DIRECTORY | O_RDONLY;
1200
1201         fd = llapi_layout_file_open(fname, open_flags, open_mode, layout);
1202         if (fd < 0)
1203                 fprintf(stderr, "%s: cannot %s '%s': %s\n", progname,
1204                         S_ISDIR(st.st_mode) ?
1205                                 "set default composite layout for" :
1206                                 "create composite file",
1207                         fname, strerror(errno));
1208         return fd;
1209 }
1210
1211 static int lfs_migrate(char *name, __u64 migration_flags,
1212                        struct llapi_stripe_param *param,
1213                        struct llapi_layout *layout)
1214 {
1215         struct llapi_layout *existing;
1216         uint64_t dom_new, dom_cur;
1217         int fd = -1;
1218         int fdv = -1;
1219         int rc;
1220
1221         rc = migrate_open_files(name, migration_flags, param, layout,
1222                                 &fd, &fdv);
1223         if (rc < 0)
1224                 goto out;
1225
1226         rc = llapi_layout_dom_size(layout, &dom_new);
1227         if (rc) {
1228                 error_loc = "cannot get new layout DoM size";
1229                 goto out;
1230         }
1231         /* special case for migration to DOM layout*/
1232         existing = llapi_layout_get_by_fd(fd, 0);
1233         if (!existing) {
1234                 error_loc = "cannot get existing layout";
1235                 goto out;
1236         }
1237
1238         rc = llapi_layout_dom_size(existing, &dom_cur);
1239         if (rc) {
1240                 error_loc = "cannot get current layout DoM size";
1241                 goto out;
1242         }
1243
1244         /*
1245          * if file has DoM layout already then migration is possible to
1246          * the new layout with the same DoM component via swap layout,
1247          * if new layout used bigger DOM size, then mirroring is used
1248          */
1249         if (dom_new > dom_cur) {
1250                 rc = lfs_migrate_to_dom(fd, fdv, name, migration_flags);
1251                 if (rc)
1252                         error_loc = "cannot migrate to DOM layout";
1253                 goto out_closed;
1254         }
1255
1256         if (!(migration_flags & LLAPI_MIGRATION_NONBLOCK)) {
1257                 /*
1258                  * Blocking mode (forced if servers do not support file lease).
1259                  * It is also the default mode, since we cannot distinguish
1260                  * between a broken lease and a server that does not support
1261                  * atomic swap/close (LU-6785)
1262                  */
1263                 rc = migrate_block(fd, fdv);
1264                 goto out;
1265         }
1266
1267         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
1268         if (rc < 0) {
1269                 error_loc = "cannot get lease";
1270                 goto out;
1271         }
1272
1273         rc = migrate_nonblock(fd, fdv);
1274         if (rc < 0) {
1275                 llapi_lease_release(fd);
1276                 goto out;
1277         }
1278
1279         /*
1280          * Atomically put lease, swap layouts and close.
1281          * for a migration we need to check data version on file did
1282          * not change.
1283          */
1284         rc = llapi_fswap_layouts(fd, fdv, 0, 0, SWAP_LAYOUTS_CLOSE);
1285         if (rc < 0) {
1286                 error_loc = "cannot swap layout";
1287                 goto out;
1288         }
1289
1290 out:
1291         if (fd >= 0)
1292                 close(fd);
1293
1294         if (fdv >= 0)
1295                 close(fdv);
1296 out_closed:
1297         if (rc < 0)
1298                 fprintf(stderr, "error: %s: %s: %s: %s\n",
1299                         progname, name, error_loc, strerror(-rc));
1300         else if (migration_flags & LLAPI_MIGRATION_VERBOSE)
1301                 printf("%s\n", name);
1302
1303         return rc;
1304 }
1305
1306 static int comp_str2flags(char *string, __u32 *flags, __u32 *neg_flags)
1307 {
1308         char *name;
1309         char *dup_string = NULL;
1310         int rc = 0;
1311
1312         *flags = 0;
1313         *neg_flags = 0;
1314
1315         if (!string || !string[0])
1316                 return -EINVAL;
1317
1318         dup_string = strdup(string);
1319         if (!dup_string) {
1320                 llapi_printf(LLAPI_MSG_ERROR,
1321                              "%s: insufficient memory\n",
1322                              progname);
1323                 return -ENOMEM;
1324         }
1325
1326         for (name = strtok(dup_string, ","); name; name = strtok(NULL, ",")) {
1327                 bool found = false;
1328                 int i;
1329
1330                 for (i = 0; i < ARRAY_SIZE(comp_flags_table); i++) {
1331                         __u32 comp_flag = comp_flags_table[i].cfn_flag;
1332                         const char *comp_name = comp_flags_table[i].cfn_name;
1333
1334                         if (strcmp(name, comp_name) == 0) {
1335                                 *flags |= comp_flag;
1336                                 found = true;
1337                         } else if (strncmp(name, "^", 1) == 0 &&
1338                                    strcmp(name + 1, comp_name) == 0) {
1339                                 *neg_flags |= comp_flag;
1340                                 found = true;
1341                         }
1342                 }
1343                 if (!found) {
1344                         llapi_printf(LLAPI_MSG_ERROR,
1345                                      "%s: component flag '%s' not supported\n",
1346                                      progname, name);
1347                         rc = -EINVAL;
1348                         goto out_free;
1349                 }
1350         }
1351
1352         if (!*flags && !*neg_flags)
1353                 rc = -EINVAL;
1354
1355         /* don't allow to set and exclude the same flag */
1356         if (*flags & *neg_flags)
1357                 rc = -EINVAL;
1358
1359 out_free:
1360         free(dup_string);
1361         return rc;
1362 }
1363
1364 static int mdthash_input(char *string, __u32 *inflags,
1365                          __u32 *exflags, __u32 *type)
1366 {
1367         char *name;
1368         struct mhf_list {
1369                 char *name;
1370                 __u32 flag;
1371         } mhflist[] = {
1372                 {"migrating", LMV_HASH_FLAG_MIGRATION},
1373                 {"badtype", LMV_HASH_FLAG_BAD_TYPE},
1374                 {"lostlmv", LMV_HASH_FLAG_LOST_LMV},
1375         };
1376
1377         if (string == NULL)
1378                 return -EINVAL;
1379
1380         *inflags = 0;
1381         *exflags = 0;
1382         *type = 0;
1383         for (name = strtok(string, ","); name; name = strtok(NULL, ",")) {
1384                 bool found = false;
1385                 int i;
1386
1387                 for (i = 0; i < ARRAY_SIZE(mhflist); i++) {
1388                         if (strcmp(name, mhflist[i].name) == 0 ||
1389                             name[0] == mhflist[i].name[0]) {
1390                                 *inflags |= mhflist[i].flag;
1391                                 found = true;
1392                         } else if (name[0] == '^' &&
1393                                    (strcmp(name + 1, mhflist[i].name) == 0 ||
1394                                     name[1] == mhflist[i].name[0])) {
1395                                 *exflags |= mhflist[i].flag;
1396                                 found = true;
1397                         }
1398                 }
1399                 if (!found) {
1400                         i = check_hashtype(name);
1401                         if (i > 0) {
1402                                 *type |= 1 << i;
1403                                 continue;
1404                         }
1405                         llapi_printf(LLAPI_MSG_ERROR,
1406                                      "%s: invalid mdt_hash value '%s'\n",
1407                                      progname, name);
1408                         return -EINVAL;
1409                 }
1410         }
1411
1412         /* don't allow to include and exclude the same flag */
1413         if (*inflags & *exflags) {
1414                 llapi_printf(LLAPI_MSG_ERROR,
1415                              "%s: include and exclude same flag '%s'\n",
1416                              progname, string);
1417                 return -EINVAL;
1418         }
1419
1420         return 0;
1421 }
1422
1423 static int mirror_str2state(char *string, __u16 *state, __u16 *neg_state)
1424 {
1425         if (!string)
1426                 return -EINVAL;
1427
1428         *state = 0;
1429         *neg_state = 0;
1430
1431         if (strncmp(string, "^", 1) == 0) {
1432                 *neg_state = llapi_layout_string_flags(string + 1);
1433                 if (*neg_state != 0)
1434                         return 0;
1435         } else {
1436                 *state = llapi_layout_string_flags(string);
1437                 if (*state != 0)
1438                         return 0;
1439         }
1440
1441         llapi_printf(LLAPI_MSG_ERROR,
1442                      "%s: mirrored file state '%s' not supported\n",
1443                      progname, string);
1444         return -EINVAL;
1445 }
1446
1447 /**
1448  * struct mirror_args - Command-line arguments for mirror(s).
1449  * @m_count:  Number of mirrors to be created with this layout.
1450  * @m_flags:  Mirror level flags, only 'prefer' is supported.
1451  * @m_layout: Mirror layout.
1452  * @m_file:   A victim file. Its layout will be split and used as a mirror.
1453  * @m_next:   Point to the next node of the list.
1454  *
1455  * Command-line arguments for mirror(s) will be parsed and stored in
1456  * a linked list that consists of this structure.
1457  */
1458 struct mirror_args {
1459         __u32                   m_count;
1460         __u32                   m_flags;
1461         struct llapi_layout     *m_layout;
1462         const char              *m_file;
1463         struct mirror_args      *m_next;
1464         bool                    m_inherit;
1465 };
1466
1467 /**
1468  * enum mirror_flags - Flags for extending a mirrored file.
1469  * @MF_NO_VERIFY: Indicates not to verify the mirror(s) from victim file(s)
1470  *             in case the victim file(s) contains the same data as the
1471  *             original mirrored file.
1472  * @MF_DESTROY: Indicates to delete the mirror from the mirrored file.
1473  * @MF_COMP_ID: specified component id instead of mirror id
1474  *
1475  * Flags for extending a mirrored file.
1476  */
1477 enum mirror_flags {
1478         MF_NO_VERIFY    = 0x1,
1479         MF_DESTROY      = 0x2,
1480         MF_COMP_ID      = 0x4,
1481         MF_COMP_POOL    = 0x8,
1482 };
1483
1484 /**
1485  * mirror_create_sanity_check() - Check mirror list.
1486  * @list:  A linked list that stores the mirror arguments.
1487  *
1488  * This function does a sanity check on @list for creating
1489  * a mirrored file.
1490  *
1491  * Return: 0 on success or a negative error code on failure.
1492  */
1493 static int mirror_create_sanity_check(const char *fname,
1494                                       struct mirror_args *list,
1495                                       bool check_fname)
1496 {
1497         int rc = 0;
1498         bool has_m_file = false;
1499         bool has_m_layout = false;
1500
1501         if (!list)
1502                 return -EINVAL;
1503
1504         if (fname && check_fname) {
1505                 struct llapi_layout *layout;
1506
1507                 layout = llapi_layout_get_by_path(fname, 0);
1508                 if (!layout) {
1509                         fprintf(stderr,
1510                                 "error: %s: file '%s' couldn't get layout\n",
1511                                 progname, fname);
1512                         return -ENODATA;
1513                 }
1514
1515                 rc = llapi_layout_sanity(layout, fname, false, true);
1516
1517                 llapi_layout_free(layout);
1518
1519                 if (rc) {
1520                         llapi_layout_sanity_perror(rc);
1521                         return rc;
1522                 }
1523         }
1524
1525         while (list) {
1526                 if (list->m_file) {
1527                         has_m_file = true;
1528                         llapi_layout_free(list->m_layout);
1529
1530                         list->m_layout =
1531                                 llapi_layout_get_by_path(list->m_file, 0);
1532                         if (!list->m_layout) {
1533                                 fprintf(stderr,
1534                                         "error: %s: file '%s' has no layout\n",
1535                                         progname, list->m_file);
1536                                 return -ENODATA;
1537                         }
1538                 } else {
1539                         has_m_layout = true;
1540                         if (!list->m_layout) {
1541                                 fprintf(stderr, "error: %s: no mirror layout\n",
1542                                         progname);
1543                                 return -EINVAL;
1544                         }
1545                 }
1546
1547                 rc = llapi_layout_sanity(list->m_layout, fname, false, true);
1548                 if (rc) {
1549                         llapi_layout_sanity_perror(rc);
1550                         return rc;
1551                 }
1552
1553                 list = list->m_next;
1554         }
1555
1556         if (has_m_file && has_m_layout) {
1557                 fprintf(stderr,
1558                         "error: %s: -f <victim_file> option should not be specified with setstripe options\n",
1559                         progname);
1560                 return -EINVAL;
1561         }
1562
1563         return 0;
1564 }
1565
1566 static int mirror_set_flags(struct llapi_layout *layout, void *cbdata)
1567 {
1568         __u32 mirror_flags = *(__u32 *)cbdata;
1569         uint32_t flags;
1570         int rc;
1571
1572         rc = llapi_layout_comp_flags_get(layout, &flags);
1573         if (rc < 0)
1574                 return rc;
1575
1576         if (!flags) {
1577                 rc = llapi_layout_comp_flags_set(layout, mirror_flags);
1578                 if (rc)
1579                         return rc;
1580         }
1581
1582         return LLAPI_LAYOUT_ITER_CONT;
1583 }
1584
1585 /**
1586  * mirror_create() - Create a mirrored file.
1587  * @fname:        The file to be created.
1588  * @mirror_list:  A linked list that stores the mirror arguments.
1589  *
1590  * This function creates a mirrored file @fname with the mirror(s)
1591  * from @mirror_list.
1592  *
1593  * Return: 0 on success or a negative error code on failure.
1594  */
1595 static int mirror_create(char *fname, struct mirror_args *mirror_list)
1596 {
1597         struct llapi_layout *layout = NULL;
1598         struct mirror_args *cur_mirror = NULL;
1599         uint16_t mirror_count = 0;
1600         int i = 0;
1601         int rc = 0;
1602
1603         rc = mirror_create_sanity_check(fname, mirror_list, false);
1604         if (rc)
1605                 return rc;
1606
1607         cur_mirror = mirror_list;
1608         while (cur_mirror) {
1609                 rc = llapi_layout_comp_iterate(cur_mirror->m_layout,
1610                                                mirror_set_flags,
1611                                                &cur_mirror->m_flags);
1612                 if (rc) {
1613                         rc = -errno;
1614                         fprintf(stderr, "%s: failed to set mirror flags\n",
1615                                 progname);
1616                         goto error;
1617                 }
1618
1619                 for (i = 0; i < cur_mirror->m_count; i++) {
1620                         rc = llapi_layout_merge(&layout, cur_mirror->m_layout);
1621                         if (rc) {
1622                                 rc = -errno;
1623                                 fprintf(stderr,
1624                                         "error: %s: merge layout failed: %s\n",
1625                                         progname, strerror(errno));
1626                                 goto error;
1627                         }
1628                 }
1629                 mirror_count += cur_mirror->m_count;
1630                 cur_mirror = cur_mirror->m_next;
1631         }
1632
1633         if (!layout) {
1634                 fprintf(stderr, "error: %s: layout is NULL\n", progname);
1635                 return -EINVAL;
1636         }
1637
1638         rc = llapi_layout_mirror_count_set(layout, mirror_count);
1639         if (rc) {
1640                 rc = -errno;
1641                 fprintf(stderr, "error: %s: set mirror count failed: %s\n",
1642                         progname, strerror(errno));
1643                 goto error;
1644         }
1645
1646         rc = lfs_component_create(fname, O_CREAT | O_WRONLY, 0666,
1647                                   layout);
1648         if (rc >= 0) {
1649                 close(rc);
1650                 rc = 0;
1651         }
1652
1653 error:
1654         llapi_layout_free(layout);
1655         return rc;
1656 }
1657
1658 /**
1659  * Compare files and check lease on @fd.
1660  *
1661  * \retval bytes number of bytes are the same
1662  */
1663 static ssize_t mirror_file_compare(int fd, int fdv)
1664 {
1665         const size_t buflen = 4 * 1024 * 1024; /* 4M */
1666         void *buf;
1667         ssize_t bytes_done = 0;
1668         ssize_t bytes_read = 0;
1669
1670         buf = malloc(buflen * 2);
1671         if (!buf)
1672                 return -ENOMEM;
1673
1674         while (1) {
1675                 if (!llapi_lease_check(fd)) {
1676                         bytes_done = -EBUSY;
1677                         break;
1678                 }
1679
1680                 bytes_read = read(fd, buf, buflen);
1681                 if (bytes_read <= 0)
1682                         break;
1683
1684                 if (bytes_read != read(fdv, buf + buflen, buflen))
1685                         break;
1686
1687                 /*
1688                  * XXX: should compute the checksum on each buffer and then
1689                  * compare checksum to avoid cache collision
1690                  */
1691                 if (memcmp(buf, buf + buflen, bytes_read))
1692                         break;
1693
1694                 bytes_done += bytes_read;
1695         }
1696
1697         free(buf);
1698
1699         return bytes_done;
1700 }
1701
1702 static int mirror_extend_file(const char *fname, const char *victim_file,
1703                               enum mirror_flags mirror_flags)
1704 {
1705         int fd = -1;
1706         int fdv = -1;
1707         struct stat stbuf;
1708         struct stat stbuf_v;
1709         struct ll_ioc_lease *data = NULL;
1710         int rc;
1711
1712         fd = open(fname, O_RDWR);
1713         if (fd < 0) {
1714                 error_loc = "open source file";
1715                 rc = -errno;
1716                 goto out;
1717         }
1718
1719         fdv = open(victim_file, O_RDWR);
1720         if (fdv < 0) {
1721                 error_loc = "open target file";
1722                 rc = -errno;
1723                 goto out;
1724         }
1725
1726         if (fstat(fd, &stbuf) || fstat(fdv, &stbuf_v)) {
1727                 error_loc = "stat source or target file";
1728                 rc = -errno;
1729                 goto out;
1730         }
1731
1732         if (stbuf.st_dev != stbuf_v.st_dev) {
1733                 error_loc = "stat source and target file";
1734                 rc = -EXDEV;
1735                 goto out;
1736         }
1737
1738         /* mirrors should be of the same size */
1739         if (stbuf.st_size != stbuf_v.st_size) {
1740                 error_loc = "file sizes don't match";
1741                 rc = -EINVAL;
1742                 goto out;
1743         }
1744
1745         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
1746         if (rc < 0) {
1747                 error_loc = "cannot get lease";
1748                 goto out;
1749         }
1750
1751         if (!(mirror_flags & MF_NO_VERIFY)) {
1752                 ssize_t ret;
1753                 /* mirrors should have the same contents */
1754                 ret = mirror_file_compare(fd, fdv);
1755                 if (ret != stbuf.st_size) {
1756                         error_loc = "file busy or contents don't match";
1757                         rc = ret < 0 ? ret : -EINVAL;
1758                         goto out;
1759                 }
1760         }
1761
1762         /* Get rid of caching pages from clients */
1763         rc = llapi_file_flush(fd);
1764         if (rc < 0) {
1765                 error_loc = "cannot get data version";
1766                 goto out;
1767         }
1768
1769         rc = llapi_file_flush(fdv);
1770         if (rc < 0) {
1771                 error_loc = "cannot get data version";
1772                 goto out;
1773         }
1774
1775         rc = migrate_set_timestamps(fd, &stbuf);
1776         if (rc < 0) {
1777                 error_loc = "cannot set source file timestamp";
1778                 goto out;
1779         }
1780
1781         /* Atomically put lease, merge layouts and close. */
1782         data = calloc(1, offsetof(typeof(*data), lil_ids[1]));
1783         if (!data) {
1784                 error_loc = "memory allocation";
1785                 goto out;
1786         }
1787         data->lil_mode = LL_LEASE_UNLCK;
1788         data->lil_flags = LL_LEASE_LAYOUT_MERGE;
1789         data->lil_count = 1;
1790         data->lil_ids[0] = fdv;
1791         rc = llapi_lease_set(fd, data);
1792         if (rc < 0) {
1793                 error_loc = "cannot merge layout";
1794                 goto out;
1795         } else if (rc == 0) {
1796                 rc = -EBUSY;
1797                 error_loc = "lost lease lock";
1798                 goto out;
1799         }
1800         rc = 0;
1801
1802 out:
1803         if (data)
1804                 free(data);
1805         if (fd >= 0)
1806                 close(fd);
1807         if (fdv >= 0)
1808                 close(fdv);
1809         if (!rc)
1810                 (void) unlink(victim_file);
1811         if (rc < 0)
1812                 fprintf(stderr, "error: %s: %s: %s: %s\n",
1813                         progname, fname, error_loc, strerror(-rc));
1814         return rc;
1815 }
1816
1817 static int mirror_extend_layout(char *name, struct llapi_layout *m_layout,
1818                                 bool inherit, uint32_t flags)
1819 {
1820         struct llapi_layout *f_layout = NULL;
1821         struct ll_ioc_lease *data = NULL;
1822         struct stat st;
1823         int fd = -1;
1824         int fdv = -1;
1825         int rc = 0;
1826
1827         if (inherit) {
1828                 f_layout = llapi_layout_get_by_path(name, 0);
1829                 if (!f_layout) {
1830                         rc = -EINVAL;
1831                         fprintf(stderr, "%s: cannot get layout\n", progname);
1832                         goto out;
1833                 }
1834                 rc = llapi_layout_get_last_init_comp(f_layout);
1835                 if (rc) {
1836                         fprintf(stderr, "%s: cannot get the last init comp\n",
1837                                 progname);
1838                         goto out;
1839                 }
1840                 rc = llapi_layout_mirror_inherit(f_layout, m_layout);
1841                 if (rc) {
1842                         fprintf(stderr,
1843                                 "%s: cannot inherit from the last init comp\n",
1844                                 progname);
1845                         goto out;
1846                 }
1847         }
1848
1849         llapi_layout_comp_flags_set(m_layout, flags);
1850         rc = migrate_open_files(name,
1851                              LLAPI_MIGRATION_NONDIRECT | LLAPI_MIGRATION_MIRROR,
1852                              NULL, m_layout, &fd, &fdv);
1853         if (rc < 0)
1854                 goto out;
1855
1856         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
1857         if (rc < 0) {
1858                 error_loc = "cannot get lease";
1859                 goto out;
1860         }
1861
1862         rc = fstat(fd, &st);
1863         if (rc < 0) {
1864                 error_loc = "cannot stat source file";
1865                 goto out;
1866         }
1867
1868         rc = migrate_nonblock(fd, fdv);
1869         if (rc < 0) {
1870                 llapi_lease_release(fd);
1871                 goto out;
1872         }
1873
1874         rc = migrate_set_timestamps(fd, &st);
1875         if (rc < 0) {
1876                 error_loc = "cannot set source file timestamp";
1877                 goto out;
1878         }
1879
1880         /* Atomically put lease, merge layouts and close. */
1881         data = calloc(1, offsetof(typeof(*data), lil_ids[1]));
1882         if (!data) {
1883                 error_loc = "memory allocation";
1884                 goto out;
1885         }
1886         data->lil_mode = LL_LEASE_UNLCK;
1887         data->lil_flags = LL_LEASE_LAYOUT_MERGE;
1888         data->lil_count = 1;
1889         data->lil_ids[0] = fdv;
1890         rc = llapi_lease_set(fd, data);
1891         if (rc < 0) {
1892                 error_loc = "cannot merge layout";
1893                 goto out;
1894         } else if (rc == 0) {
1895                 rc = -EBUSY;
1896                 error_loc = "lost lease lock";
1897                 goto out;
1898         }
1899         rc = 0;
1900
1901 out:
1902         if (data)
1903                 free(data);
1904         if (fd >= 0)
1905                 close(fd);
1906         if (fdv >= 0)
1907                 close(fdv);
1908         if (rc < 0)
1909                 fprintf(stderr, "error: %s: %s: %s: %s\n",
1910                         progname, name, error_loc, strerror(-rc));
1911         return rc;
1912 }
1913
1914 static int mirror_extend(char *fname, struct mirror_args *mirror_list,
1915                          enum mirror_flags mirror_flags)
1916 {
1917         int rc = 0;
1918
1919         while (mirror_list) {
1920                 if (mirror_list->m_file) {
1921                         rc = mirror_extend_file(fname, mirror_list->m_file,
1922                                                 mirror_flags);
1923                 } else {
1924                         __u32 mirror_count = mirror_list->m_count;
1925
1926                         while (mirror_count > 0) {
1927                                 rc = mirror_extend_layout(fname,
1928                                                         mirror_list->m_layout,
1929                                                         mirror_list->m_inherit,
1930                                                         mirror_list->m_flags);
1931                                 if (rc)
1932                                         break;
1933
1934                                 --mirror_count;
1935                         }
1936                 }
1937                 if (rc)
1938                         break;
1939
1940                 mirror_list = mirror_list->m_next;
1941         }
1942
1943         return rc;
1944 }
1945
1946 static int find_mirror_id(struct llapi_layout *layout, void *cbdata)
1947 {
1948         uint32_t id;
1949         int rc;
1950
1951         rc = llapi_layout_mirror_id_get(layout, &id);
1952         if (rc < 0)
1953                 return rc;
1954
1955         if ((__u16)id == *(__u16 *)cbdata)
1956                 return LLAPI_LAYOUT_ITER_STOP;
1957
1958         return LLAPI_LAYOUT_ITER_CONT;
1959 }
1960
1961 static int find_comp_id(struct llapi_layout *layout, void *cbdata)
1962 {
1963         uint32_t id;
1964         int rc;
1965
1966         rc = llapi_layout_comp_id_get(layout, &id);
1967         if (rc < 0)
1968                 return rc;
1969
1970         if (id == *(__u32 *)cbdata)
1971                 return LLAPI_LAYOUT_ITER_STOP;
1972
1973         return LLAPI_LAYOUT_ITER_CONT;
1974 }
1975
1976 static int find_mirror_id_by_pool(struct llapi_layout *layout, void *cbdata)
1977 {
1978         char buf[LOV_MAXPOOLNAME + 1];
1979         struct pool_to_id_cbdata *d = (void *)cbdata;
1980         uint32_t id;
1981         int rc;
1982
1983         rc = llapi_layout_pool_name_get(layout, buf, sizeof(buf));
1984         if (rc < 0)
1985                 return rc;
1986         if (strcmp(d->pool, buf))
1987                 return LLAPI_LAYOUT_ITER_CONT;
1988
1989         rc = llapi_layout_mirror_id_get(layout, &id);
1990         if (rc < 0)
1991                 return rc;
1992         d->id = id;
1993
1994         return LLAPI_LAYOUT_ITER_STOP;
1995 }
1996
1997 static int find_comp_id_by_pool(struct llapi_layout *layout, void *cbdata)
1998 {
1999         char buf[LOV_MAXPOOLNAME + 1];
2000         struct pool_to_id_cbdata *d = (void *)cbdata;
2001         uint32_t id;
2002         int rc;
2003
2004         rc = llapi_layout_pool_name_get(layout, buf, sizeof(buf));
2005         if (rc < 0)
2006                 return rc;
2007         if (strcmp(d->pool, buf))
2008                 return LLAPI_LAYOUT_ITER_CONT;
2009
2010         rc = llapi_layout_comp_id_get(layout, &id);
2011         if (rc < 0)
2012                 return rc;
2013         d->id = id;
2014
2015         return LLAPI_LAYOUT_ITER_STOP;
2016 }
2017
2018 struct collect_ids_data {
2019         __u16   *cid_ids;
2020         int     cid_count;
2021         __u16   cid_exclude;
2022 };
2023
2024 static int collect_mirror_id(struct llapi_layout *layout, void *cbdata)
2025 {
2026         struct collect_ids_data *cid = cbdata;
2027         uint32_t id;
2028         int rc;
2029
2030         rc = llapi_layout_mirror_id_get(layout, &id);
2031         if (rc < 0)
2032                 return rc;
2033
2034         if ((__u16)id != cid->cid_exclude) {
2035                 int i;
2036
2037                 for (i = 0; i < cid->cid_count; i++) {
2038                         /* already collected the mirror id */
2039                         if (id == cid->cid_ids[i])
2040                                 return LLAPI_LAYOUT_ITER_CONT;
2041                 }
2042                 cid->cid_ids[cid->cid_count] = id;
2043                 cid->cid_count++;
2044         }
2045
2046         return LLAPI_LAYOUT_ITER_CONT;
2047 }
2048
2049 /**
2050  * last_non_stale_mirror() - Check if a mirror is the last non-stale mirror.
2051  * @mirror_id: Mirror id to be checked.
2052  * @layout:    Mirror component list.
2053  *
2054  * This function checks if a mirror with specified @mirror_id is the last
2055  * non-stale mirror of a layout @layout.
2056  *
2057  * Return: true or false.
2058  */
2059 static inline
2060 bool last_non_stale_mirror(__u16 mirror_id, struct llapi_layout *layout)
2061 {
2062         __u16 mirror_ids[128] = { 0 };
2063         struct collect_ids_data cid = { .cid_ids = mirror_ids,
2064                                         .cid_count = 0,
2065                                         .cid_exclude = mirror_id, };
2066         int i;
2067
2068         llapi_layout_comp_iterate(layout, collect_mirror_id, &cid);
2069
2070         for (i = 0; i < cid.cid_count; i++) {
2071                 struct llapi_resync_comp comp_array[1024] = { { 0 } };
2072                 int comp_size = 0;
2073
2074                 comp_size = llapi_mirror_find_stale(layout, comp_array,
2075                                                     ARRAY_SIZE(comp_array),
2076                                                     &mirror_ids[i], 1);
2077                 if (comp_size == 0)
2078                         return false;
2079         }
2080
2081         return true;
2082 }
2083
2084 static int mirror_split(const char *fname, __u32 id, const char *pool,
2085                         enum mirror_flags mflags, const char *victim_file)
2086 {
2087         struct llapi_layout *layout;
2088         char parent[PATH_MAX];
2089         char victim[PATH_MAX];
2090         int flags = O_CREAT | O_EXCL | O_LOV_DELAY_CREATE | O_NOFOLLOW;
2091         char *ptr;
2092         struct ll_ioc_lease *data;
2093         uint16_t mirror_count;
2094         __u32 mirror_id;
2095         int mdt_index;
2096         int fd, fdv;
2097         bool purge = true; /* delete mirror by setting fdv=fd */
2098         bool is_encrypted;
2099         int rc;
2100
2101         if (victim_file && (strcmp(fname, victim_file) == 0)) {
2102                 fprintf(stderr,
2103                         "error %s: the source file '%s' and -f file are the same\n",
2104                         progname, fname);
2105                 return -EINVAL;
2106         }
2107
2108         /* check fname contains mirror with mirror_id/comp_id */
2109         layout = llapi_layout_get_by_path(fname, 0);
2110         if (!layout) {
2111                 fprintf(stderr,
2112                         "error %s: file '%s' couldn't get layout\n",
2113                         progname, fname);
2114                 return -EINVAL;
2115         }
2116
2117         rc = llapi_layout_sanity(layout, fname, false, true);
2118         if (rc) {
2119                 llapi_layout_sanity_perror(rc);
2120                 goto free_layout;
2121         }
2122
2123         rc = llapi_layout_mirror_count_get(layout, &mirror_count);
2124         if (rc) {
2125                 fprintf(stderr,
2126                         "error %s: file '%s' couldn't get mirror count\n",
2127                         progname, fname);
2128                 goto free_layout;
2129         }
2130         if (mirror_count < 2) {
2131                 fprintf(stderr,
2132                         "error %s: file '%s' has %d component, cannot split\n",
2133                         progname, fname, mirror_count);
2134                 goto free_layout;
2135         }
2136
2137         if (mflags & MF_COMP_POOL) {
2138                 struct pool_to_id_cbdata data = { .pool = pool };
2139
2140                 rc = llapi_layout_comp_iterate(layout, find_mirror_id_by_pool,
2141                                                &data);
2142                 mirror_id = data.id;
2143         } else if (mflags & MF_COMP_ID) {
2144                 rc = llapi_layout_comp_iterate(layout, find_comp_id, &id);
2145                 mirror_id = mirror_id_of(id);
2146         } else {
2147                 rc = llapi_layout_comp_iterate(layout, find_mirror_id, &id);
2148                 mirror_id = id;
2149         }
2150         if (rc < 0) {
2151                 fprintf(stderr, "error %s: failed to iterate layout of '%s'\n",
2152                         progname, fname);
2153                 goto free_layout;
2154         } else if (rc == LLAPI_LAYOUT_ITER_CONT) {
2155                 if (mflags & MF_COMP_POOL) {
2156                         fprintf(stderr,
2157                                 "error %s: file '%s' does not contain mirror with pool '%s'\n",
2158                                 progname, fname, pool);
2159                         goto free_layout;
2160                 } else if (mflags & MF_COMP_ID) {
2161                         fprintf(stderr,
2162                                 "error %s: file '%s' does not contain mirror with comp-id %u\n",
2163                                 progname, fname, id);
2164                         goto free_layout;
2165                 } else {
2166                         fprintf(stderr,
2167                                 "error %s: file '%s' does not contain mirror with id %u\n",
2168                                 progname, fname, id);
2169                         goto free_layout;
2170                 }
2171         }
2172
2173         if (!victim_file && mflags & MF_DESTROY)
2174                 /* Allow mirror split even without the key on encrypted files,
2175                  * and in this case of a 'split -d', open file with O_DIRECT
2176                  * (no IOs will be done).
2177                  */
2178                 fd = open(fname, O_RDWR | O_DIRECT | O_FILE_ENC);
2179         else
2180                 fd = open(fname, O_RDWR);
2181
2182         if (fd < 0) {
2183                 fprintf(stderr,
2184                         "error %s: open file '%s' failed: %s\n",
2185                         progname, fname, strerror(errno));
2186                 goto free_layout;
2187         }
2188
2189         /* get victim file directory pathname */
2190         if (strlen(fname) > sizeof(parent) - 1) {
2191                 fprintf(stderr, "error %s: file name of '%s' too long\n",
2192                         progname, fname);
2193                 rc = -ERANGE;
2194                 goto close_fd;
2195         }
2196         strncpy(parent, fname, sizeof(parent));
2197         ptr = strrchr(parent, '/');
2198         if (!ptr) {
2199                 if (!getcwd(parent, sizeof(parent))) {
2200                         fprintf(stderr, "error %s: getcwd failed: %s\n",
2201                                 progname, strerror(errno));
2202                         rc = -errno;
2203                         goto close_fd;
2204                 }
2205         } else {
2206                 if (ptr == parent)
2207                         ptr = parent + 1;
2208                 *ptr = '\0';
2209         }
2210
2211         rc = llapi_file_fget_mdtidx(fd, &mdt_index);
2212         if (rc < 0) {
2213                 fprintf(stderr, "%s: cannot get MDT index of '%s'\n",
2214                         progname, fname);
2215                 goto close_fd;
2216         }
2217
2218         rc = llapi_file_is_encrypted(fd);
2219         if (rc < 0) {
2220                 fprintf(stderr, "%s: cannot get flags of '%s': %d\n",
2221                         progname, fname, rc);
2222                 goto close_fd;
2223         }
2224         is_encrypted = rc;
2225
2226 again:
2227         if (!victim_file) {
2228                 /* use a temp file to store the splitted layout */
2229                 if (mflags & MF_DESTROY) {
2230                         char file_path[PATH_MAX];
2231                         unsigned int rnumber;
2232                         int open_flags;
2233
2234                         if (last_non_stale_mirror(mirror_id, layout)) {
2235                                 rc = -EUCLEAN;
2236                                 fprintf(stderr,
2237                                         "%s: cannot destroy the last non-stale mirror of file '%s'\n",
2238                                         progname, fname);
2239                                 goto close_fd;
2240                         }
2241
2242                         if (purge) {
2243                                 /* don't use volatile file for mirror destroy */
2244                                 fdv = fd;
2245                         } else {
2246                                 /**
2247                                  * try the old way to delete mirror using
2248                                  * volatile file.
2249                                  */
2250                                 do {
2251                                         rnumber = random();
2252                                         rc = snprintf(file_path,
2253                                                       sizeof(file_path),
2254                                                       "%s/" LUSTRE_VOLATILE_HDR ":%.4X:%.4X:fd=%.2d",
2255                                                       parent, mdt_index,
2256                                                       rnumber, fd);
2257                                         if (rc < 0 ||
2258                                             rc >= sizeof(file_path)) {
2259                                                 fdv = -ENAMETOOLONG;
2260                                                 break;
2261                                         }
2262
2263                                         open_flags = O_RDWR |
2264                                              (O_LOV_DELAY_CREATE & ~O_ACCMODE) |
2265                                              O_CREAT | O_EXCL | O_NOFOLLOW |
2266                                              /* O_DIRECT for mirror split -d */
2267                                              O_DIRECT |
2268                                              /* Allow split without the key */
2269                                              O_FILE_ENC;
2270                                         fdv = open(file_path, open_flags,
2271                                                    S_IRUSR | S_IWUSR);
2272                                         if (fdv < 0)
2273                                                 rc = -errno;
2274                                 } while (fdv < 0 && rc == -EEXIST);
2275                         }
2276                 } else {
2277                         if (is_encrypted) {
2278                                 rc = -1;
2279                                 fprintf(stderr,
2280                                         "error %s: not permitted on encrypted file '%s': %d\n",
2281                                         progname, fname, rc);
2282                                 goto close_fd;
2283                         }
2284
2285                         snprintf(victim, sizeof(victim), "%s.mirror~%u",
2286                                  fname, mirror_id);
2287                         fdv = open(victim, flags, S_IRUSR | S_IWUSR);
2288                 }
2289         } else {
2290                 /* user specified victim file */
2291                 if (is_encrypted) {
2292                         rc = -1;
2293                         fprintf(stderr,
2294                                 "error %s: not permitted on encrypted file '%s': %d\n",
2295                                 progname, fname, rc);
2296                         goto close_fd;
2297                 }
2298                 fdv = open(victim_file, flags, S_IRUSR | S_IWUSR);
2299         }
2300
2301         if (fdv < 0) {
2302                 fprintf(stderr,
2303                         "error %s: create victim file failed: %s\n",
2304                         progname, strerror(errno));
2305                 goto close_fd;
2306         }
2307
2308         /* get lease lock of fname */
2309         rc = llapi_lease_acquire(fd, LL_LEASE_WRLCK);
2310         if (rc < 0) {
2311                 fprintf(stderr,
2312                         "error %s: cannot get lease of file '%s': %d\n",
2313                         progname, fname, rc);
2314                 goto close_victim;
2315         }
2316
2317         /* Atomatically put lease, split layouts and close. */
2318         data = malloc(offsetof(typeof(*data), lil_ids[2]));
2319         if (!data) {
2320                 rc = -ENOMEM;
2321                 goto close_victim;
2322         }
2323
2324         data->lil_mode = LL_LEASE_UNLCK;
2325         data->lil_flags = LL_LEASE_LAYOUT_SPLIT;
2326         data->lil_count = 2;
2327         data->lil_ids[0] = fdv;
2328         data->lil_ids[1] = mirror_id;
2329         rc = llapi_lease_set(fd, data);
2330         if (rc <= 0) {
2331                 if (rc == -EINVAL && purge) {
2332                         /* could be old MDS which prohibit fd==fdv */
2333                         purge = false;
2334                         goto again;
2335
2336                 }
2337                 if (rc == 0) /* lost lease lock */
2338                         rc = -EBUSY;
2339                 fprintf(stderr,
2340                         "error %s: cannot split '%s': %s\n",
2341                         progname, fname, strerror(-rc));
2342         } else {
2343                 rc = 0;
2344         }
2345         free(data);
2346
2347 close_victim:
2348         if (!purge)
2349                 close(fdv);
2350 close_fd:
2351         close(fd);
2352 free_layout:
2353         llapi_layout_free(layout);
2354         return rc;
2355 }
2356
2357 static inline
2358 int lfs_mirror_resync_file(const char *fname, struct ll_ioc_lease *ioc,
2359                            __u16 *mirror_ids, int ids_nr);
2360
2361 static int lfs_migrate_to_dom(int fd, int fdv, char *name,
2362                               __u64 migration_flags)
2363 {
2364         struct ll_ioc_lease *data = NULL;
2365         int rc;
2366
2367         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
2368         if (rc < 0) {
2369                 error_loc = "cannot get lease";
2370                 goto out_close;
2371         }
2372
2373         rc = migrate_nonblock(fd, fdv);
2374         if (rc < 0)
2375                 goto out_release;
2376
2377         /* Atomically put lease, merge layouts, resync and close. */
2378         data = calloc(1, offsetof(typeof(*data), lil_ids[1]));
2379         if (!data) {
2380                 error_loc = "memory allocation";
2381                 goto out_release;
2382         }
2383         data->lil_mode = LL_LEASE_UNLCK;
2384         data->lil_flags = LL_LEASE_LAYOUT_MERGE;
2385         data->lil_count = 1;
2386         data->lil_ids[0] = fdv;
2387         rc = llapi_lease_set(fd, data);
2388         if (rc < 0) {
2389                 error_loc = "cannot merge layout";
2390                 goto out_close;
2391         } else if (rc == 0) {
2392                 rc = -EBUSY;
2393                 error_loc = "lost lease lock";
2394                 goto out_close;
2395         }
2396         close(fd);
2397         close(fdv);
2398
2399         rc = lfs_mirror_resync_file(name, data, NULL, 0);
2400         if (rc) {
2401                 error_loc = "cannot resync file";
2402                 goto out;
2403         }
2404
2405         /* delete first mirror now */
2406         rc = mirror_split(name, 1, NULL, MF_DESTROY, NULL);
2407         if (rc < 0)
2408                 error_loc = "cannot delete old layout";
2409         goto out;
2410
2411 out_release:
2412         llapi_lease_release(fd);
2413 out_close:
2414         close(fd);
2415         close(fdv);
2416 out:
2417         if (rc < 0)
2418                 fprintf(stderr, "error: %s: %s: %s: %s\n",
2419                         progname, name, error_loc, strerror(-rc));
2420         else if (migration_flags & LLAPI_MIGRATION_VERBOSE)
2421                 printf("%s\n", name);
2422         if (data)
2423                 free(data);
2424         return rc;
2425 }
2426
2427 /**
2428  * Parse a string containing an target index list into an array of integers.
2429  *
2430  * The input string contains a comma delimited list of individual
2431  * indices and ranges, for example "1,2-4,7". Add the indices into the
2432  * \a tgts array and remove duplicates.
2433  *
2434  * \param[out] tgts             array to store indices in
2435  * \param[in] size              size of \a tgts array
2436  * \param[in] offset            starting index in \a tgts
2437  * \param[in] arg               string containing OST index list
2438  * \param[in/out] overstriping  index list may contain duplicates
2439  *
2440  * \retval positive    number of indices in \a tgts
2441  * \retval -EINVAL     unable to parse \a arg
2442  */
2443 static int parse_targets(__u32 *tgts, int size, int offset, char *arg,
2444                          unsigned long long *pattern)
2445 {
2446         int rc;
2447         int nr = offset;
2448         int slots = size - offset;
2449         char *ptr = NULL;
2450         bool overstriped = false;
2451         bool end_of_loop;
2452
2453         if (!arg)
2454                 return -EINVAL;
2455
2456         end_of_loop = false;
2457         while (!end_of_loop) {
2458                 int start_index = 0;
2459                 int end_index = 0;
2460                 int i;
2461                 char *endptr = NULL;
2462
2463                 rc = -EINVAL;
2464
2465                 ptr = strchrnul(arg, ',');
2466
2467                 end_of_loop = *ptr == '\0';
2468                 *ptr = '\0';
2469
2470                 errno = 0;
2471                 start_index = strtol(arg, &endptr, 0);
2472                 if (endptr == arg) /* no data at all */
2473                         break;
2474                 if (errno != 0 || start_index < -1 ||
2475                     (*endptr != '-' && *endptr != '\0'))
2476                         break;
2477
2478                 end_index = start_index;
2479                 if (*endptr == '-') {
2480                         errno = 0;
2481                         end_index = strtol(endptr + 1, &endptr, 0);
2482                         if (errno != 0 || *endptr != '\0' || end_index < -1)
2483                                 break;
2484                         if (end_index < start_index)
2485                                 break;
2486                 }
2487
2488                 for (i = start_index; i <= end_index && slots > 0; i++) {
2489                         int j;
2490
2491                         /* remove duplicate */
2492                         for (j = 0; j < offset; j++) {
2493                                 if (tgts[j] == i && pattern &&
2494                                     *pattern == LLAPI_LAYOUT_OVERSTRIPING)
2495                                         overstriped = true;
2496                                 else if (tgts[j] == i)
2497                                         return -EINVAL;
2498                         }
2499
2500                         j = offset;
2501
2502                         if (j == offset) { /* check complete */
2503                                 tgts[nr++] = i;
2504                                 --slots;
2505                         }
2506                 }
2507
2508                 if (slots == 0 && i < end_index)
2509                         break;
2510
2511                 *ptr = ',';
2512                 arg = ++ptr;
2513                 offset = nr;
2514                 rc = 0;
2515         }
2516         if (!end_of_loop && ptr)
2517                 *ptr = ',';
2518
2519         if (!overstriped && pattern)
2520                 *pattern = LLAPI_LAYOUT_DEFAULT;
2521
2522         return rc < 0 ? rc : nr;
2523 }
2524
2525 struct lfs_setstripe_args {
2526         unsigned long long       lsa_comp_end;
2527         unsigned long long       lsa_stripe_size;
2528         unsigned long long       lsa_extension_size;
2529         long long                lsa_stripe_count;
2530         long long                lsa_stripe_off;
2531         __u32                    lsa_comp_flags;
2532         __u32                    lsa_comp_neg_flags;
2533         unsigned long long       lsa_pattern;
2534         unsigned int             lsa_mirror_count;
2535         int                      lsa_nr_tgts;
2536         bool                     lsa_first_comp;
2537         bool                     lsa_extension_comp;
2538         __u32                   *lsa_tgts;
2539         char                    *lsa_pool_name;
2540 };
2541
2542 static inline void setstripe_args_init(struct lfs_setstripe_args *lsa)
2543 {
2544         unsigned int mirror_count = lsa->lsa_mirror_count;
2545         bool first_comp = lsa->lsa_first_comp;
2546
2547         memset(lsa, 0, sizeof(*lsa));
2548
2549         lsa->lsa_stripe_size = LLAPI_LAYOUT_DEFAULT;
2550         lsa->lsa_stripe_count = LLAPI_LAYOUT_DEFAULT;
2551         lsa->lsa_stripe_off = LLAPI_LAYOUT_DEFAULT;
2552         lsa->lsa_pattern = LLAPI_LAYOUT_RAID0;
2553         lsa->lsa_pool_name = NULL;
2554
2555         lsa->lsa_mirror_count = mirror_count;
2556         lsa->lsa_first_comp = first_comp;
2557 }
2558
2559 /**
2560  * setstripe_args_init_inherit() - Initialize and inherit stripe options.
2561  * @lsa: Stripe options to be initialized and inherited.
2562  *
2563  * This function initializes stripe options in @lsa and inherit
2564  * stripe_size, stripe_count and OST pool_name options.
2565  *
2566  * Return: void.
2567  */
2568 static inline void setstripe_args_init_inherit(struct lfs_setstripe_args *lsa)
2569 {
2570         unsigned long long stripe_size;
2571         long long stripe_count;
2572         char *pool_name = NULL;
2573
2574         stripe_size = lsa->lsa_stripe_size;
2575         stripe_count = lsa->lsa_stripe_count;
2576         pool_name = lsa->lsa_pool_name;
2577
2578         setstripe_args_init(lsa);
2579
2580         lsa->lsa_stripe_size = stripe_size;
2581         lsa->lsa_stripe_count = stripe_count;
2582         lsa->lsa_pool_name = pool_name;
2583 }
2584
2585 static inline bool setstripe_args_specified(struct lfs_setstripe_args *lsa)
2586 {
2587         return (lsa->lsa_stripe_size != LLAPI_LAYOUT_DEFAULT ||
2588                 lsa->lsa_stripe_count != LLAPI_LAYOUT_DEFAULT ||
2589                 lsa->lsa_stripe_off != LLAPI_LAYOUT_DEFAULT ||
2590                 lsa->lsa_pattern != LLAPI_LAYOUT_RAID0 ||
2591                 lsa->lsa_comp_end != 0);
2592 }
2593
2594 static int lsa_args_stripe_count_check(struct lfs_setstripe_args *lsa)
2595 {
2596         if (lsa->lsa_nr_tgts) {
2597                 if (lsa->lsa_nr_tgts < 0 ||
2598                     lsa->lsa_nr_tgts >= LOV_MAX_STRIPE_COUNT) {
2599                         fprintf(stderr, "Invalid nr_tgts(%d)\n",
2600                                 lsa->lsa_nr_tgts);
2601                         errno = EINVAL;
2602                         return -1;
2603                 }
2604
2605                 if (lsa->lsa_stripe_count > 0 &&
2606                     lsa->lsa_stripe_count != LLAPI_LAYOUT_DEFAULT &&
2607                     lsa->lsa_stripe_count != LLAPI_LAYOUT_WIDE &&
2608                     lsa->lsa_nr_tgts != lsa->lsa_stripe_count) {
2609                         fprintf(stderr, "stripe_count(%lld) != nr_tgts(%d)\n",
2610                                 lsa->lsa_stripe_count,
2611                                 lsa->lsa_nr_tgts);
2612                         errno = EINVAL;
2613                         return -1;
2614                 }
2615         }
2616
2617         return 0;
2618
2619 }
2620
2621 /**
2622  * comp_args_to_layout() - Create or extend a composite layout.
2623  * @composite:       Pointer to the composite layout.
2624  * @lsa:             Stripe options for the new component.
2625  *
2626  * This function creates or extends a composite layout by adding a new
2627  * component with stripe options from @lsa.
2628  *
2629  * When modified, adjust llapi_stripe_param_verify() if needed as well.
2630  *
2631  * Return: 0 on success or an error code on failure.
2632  */
2633 static int comp_args_to_layout(struct llapi_layout **composite,
2634                                struct lfs_setstripe_args *lsa,
2635                                bool set_extent)
2636 {
2637         struct llapi_layout *layout = *composite;
2638         uint64_t prev_end = 0;
2639         uint64_t size;
2640         int i = 0, rc;
2641
2642 new_comp:
2643         if (!layout) {
2644                 layout = llapi_layout_alloc();
2645                 if (!layout) {
2646                         fprintf(stderr, "Alloc llapi_layout failed. %s\n",
2647                                 strerror(errno));
2648                         errno = ENOMEM;
2649                         return -1;
2650                 }
2651                 *composite = layout;
2652                 lsa->lsa_first_comp = true;
2653         } else {
2654                 uint64_t start;
2655
2656                 /*
2657                  * Get current component extent, current component
2658                  * must be the tail component.
2659                  */
2660                 rc = llapi_layout_comp_extent_get(layout, &start, &prev_end);
2661                 if (rc) {
2662                         fprintf(stderr, "Get comp extent failed. %s\n",
2663                                 strerror(errno));
2664                         return rc;
2665                 }
2666
2667                 if (lsa->lsa_first_comp) {
2668                         prev_end = 0;
2669                         rc = llapi_layout_add_first_comp(layout);
2670                 } else {
2671                         rc = llapi_layout_comp_add(layout);
2672                 }
2673                 if (rc) {
2674                         fprintf(stderr, "Add component failed. %s\n",
2675                                 strerror(errno));
2676                         return rc;
2677                 }
2678         }
2679
2680         rc = llapi_layout_comp_flags_set(layout, lsa->lsa_comp_flags);
2681         if (rc) {
2682                 fprintf(stderr, "Set flags 0x%x failed: %s\n",
2683                         lsa->lsa_comp_flags, strerror(errno));
2684                 return rc;
2685         }
2686
2687         if (set_extent) {
2688                 uint64_t comp_end = lsa->lsa_comp_end;
2689
2690                 /*
2691                  * The extendable component is 0-length, so it can be removed
2692                  * if there is insufficient space to extend it.
2693                  */
2694                 if (lsa->lsa_extension_comp)
2695                         comp_end = prev_end;
2696
2697                 rc = llapi_layout_comp_extent_set(layout, prev_end,
2698                                                   comp_end);
2699                 if (rc) {
2700                         fprintf(stderr, "Set extent [%lu, %lu) failed. %s\n",
2701                                 prev_end, comp_end, strerror(errno));
2702                         return rc;
2703                 }
2704         }
2705         /* reset lsa_first_comp */
2706         lsa->lsa_first_comp = false;
2707
2708         /* Data-on-MDT component setting */
2709         if (lsa->lsa_pattern == LLAPI_LAYOUT_MDT) {
2710                 /* Yaml support */
2711                 if (lsa->lsa_stripe_count == 0)
2712                         lsa->lsa_stripe_count = LLAPI_LAYOUT_DEFAULT;
2713                 if (lsa->lsa_stripe_size == lsa->lsa_comp_end)
2714                         lsa->lsa_stripe_size = LLAPI_LAYOUT_DEFAULT;
2715                 if (lsa->lsa_stripe_off == -1 ||
2716                     lsa->lsa_stripe_off == 0)
2717                         lsa->lsa_stripe_off = LLAPI_LAYOUT_DEFAULT;
2718                 /*
2719                  * In case of Data-on-MDT patterns the only extra option
2720                  * applicable is stripe size option.
2721                  */
2722                 if (lsa->lsa_stripe_count != LLAPI_LAYOUT_DEFAULT) {
2723                         fprintf(stderr,
2724                                 "Option 'stripe-count' can't be specified with Data-on-MDT component: %lld\n",
2725                                 lsa->lsa_stripe_count);
2726                         errno = EINVAL;
2727                         return -1;
2728                 }
2729                 if (lsa->lsa_stripe_size != LLAPI_LAYOUT_DEFAULT &&
2730                     lsa->lsa_stripe_size != lsa->lsa_comp_end - prev_end) {
2731                         fprintf(stderr,
2732                                 "Option 'stripe-size' can't be specified with Data-on-MDT component: %llu\n",
2733                                 lsa->lsa_stripe_size);
2734                         errno = EINVAL;
2735                         return -1;
2736                 }
2737                 if (lsa->lsa_nr_tgts != 0) {
2738                         fprintf(stderr,
2739                                 "Option 'ost-list' can't be specified with Data-on-MDT component: '%i'\n",
2740                                 lsa->lsa_nr_tgts);
2741                         errno = EINVAL;
2742                         return -1;
2743                 }
2744                 if (lsa->lsa_stripe_off != LLAPI_LAYOUT_DEFAULT) {
2745                         fprintf(stderr,
2746                                 "Option 'stripe-offset' can't be specified with Data-on-MDT component: %lld\n",
2747                                 lsa->lsa_stripe_off);
2748                         errno = EINVAL;
2749                         return -1;
2750                 }
2751                 if (lsa->lsa_pool_name != 0) {
2752                         fprintf(stderr,
2753                                 "Option 'pool' can't be specified with Data-on-MDT component: '%s'\n",
2754                                 lsa->lsa_pool_name);
2755                         errno = EINVAL;
2756                         return -1;
2757                 }
2758
2759                 rc = llapi_layout_pattern_set(layout, lsa->lsa_pattern);
2760                 if (rc) {
2761                         fprintf(stderr, "Set stripe pattern %#llx failed. %s\n",
2762                                 lsa->lsa_pattern,
2763                                 strerror(errno));
2764                         return rc;
2765                 }
2766                 /* Data-on-MDT component has always single stripe up to end */
2767                 lsa->lsa_stripe_size = lsa->lsa_comp_end;
2768         } else if (lsa->lsa_pattern == LLAPI_LAYOUT_OVERSTRIPING) {
2769                 rc = llapi_layout_pattern_set(layout, lsa->lsa_pattern);
2770                 if (rc) {
2771                         fprintf(stderr, "Set stripe pattern %#llx failed. %s\n",
2772                                 lsa->lsa_pattern,
2773                                 strerror(errno));
2774                         return rc;
2775                 }
2776         }
2777
2778         size = lsa->lsa_comp_flags & LCME_FL_EXTENSION ?
2779                 lsa->lsa_extension_size : lsa->lsa_stripe_size;
2780
2781         if (lsa->lsa_comp_flags & LCME_FL_EXTENSION)
2782                 rc = llapi_layout_extension_size_set(layout, size);
2783         else
2784                 rc = llapi_layout_stripe_size_set(layout, size);
2785
2786         if (rc) {
2787                 fprintf(stderr, "Set stripe size %lu failed: %s\n",
2788                         size, strerror(errno));
2789                 return rc;
2790         }
2791
2792         rc = llapi_layout_stripe_count_set(layout, lsa->lsa_stripe_count);
2793         if (rc) {
2794                 fprintf(stderr, "Set stripe count %lld failed: %s\n",
2795                         lsa->lsa_stripe_count, strerror(errno));
2796                 return rc;
2797         }
2798
2799         if (lsa->lsa_pool_name) {
2800                 rc = llapi_layout_pool_name_set(layout, lsa->lsa_pool_name);
2801                 if (rc) {
2802                         fprintf(stderr, "Set pool name: %s failed. %s\n",
2803                                 lsa->lsa_pool_name, strerror(errno));
2804                         return rc;
2805                 }
2806         } else {
2807                 rc = llapi_layout_pool_name_set(layout, "");
2808                 if (rc) {
2809                         fprintf(stderr, "Clear pool name failed: %s\n",
2810                                 strerror(errno));
2811                         return rc;
2812                 }
2813         }
2814
2815         rc = lsa_args_stripe_count_check(lsa);
2816         if (rc)
2817                 return rc;
2818
2819         if (lsa->lsa_nr_tgts > 0) {
2820                 bool found = false;
2821
2822                 for (i = 0; i < lsa->lsa_nr_tgts; i++) {
2823                         rc = llapi_layout_ost_index_set(layout, i,
2824                                                         lsa->lsa_tgts[i]);
2825                         if (rc)
2826                                 break;
2827
2828                         /* Make sure stripe offset is in OST list. */
2829                         if (lsa->lsa_tgts[i] == lsa->lsa_stripe_off)
2830                                 found = true;
2831                 }
2832                 if (!found) {
2833                         fprintf(stderr, "Invalid stripe offset '%lld', not in the target list",
2834                                 lsa->lsa_stripe_off);
2835                         errno = EINVAL;
2836                         return -1;
2837                 }
2838         } else if (lsa->lsa_stripe_off != LLAPI_LAYOUT_DEFAULT &&
2839                    lsa->lsa_stripe_off != -1) {
2840                 rc = llapi_layout_ost_index_set(layout, 0, lsa->lsa_stripe_off);
2841         }
2842         if (rc) {
2843                 fprintf(stderr, "Set ost index %d failed. %s\n",
2844                         i, strerror(errno));
2845                 return rc;
2846         }
2847
2848         /* Create the second, virtual component of extension space */
2849         if (lsa->lsa_extension_comp) {
2850                 lsa->lsa_comp_flags |= LCME_FL_EXTENSION;
2851                 lsa->lsa_extension_comp = false;
2852                 goto new_comp;
2853         }
2854
2855         return rc;
2856 }
2857
2858 static int build_component(struct llapi_layout **layout,
2859                            struct lfs_setstripe_args *lsa, bool set_extent)
2860 {
2861         int rc;
2862
2863         rc = comp_args_to_layout(layout, lsa, set_extent);
2864         if (rc)
2865                 return rc;
2866
2867         if (lsa->lsa_mirror_count > 0) {
2868                 rc = llapi_layout_mirror_count_set(*layout,
2869                                                    lsa->lsa_mirror_count);
2870                 if (rc)
2871                         return rc;
2872
2873                 rc = llapi_layout_flags_set(*layout, LCM_FL_RDONLY);
2874                 if (rc)
2875                         return rc;
2876                 lsa->lsa_mirror_count = 0;
2877         }
2878
2879         return rc;
2880 }
2881
2882 static int build_prev_component(struct llapi_layout **layout,
2883                                 struct lfs_setstripe_args *prev,
2884                                 struct lfs_setstripe_args *lsa,
2885                                 bool set_extent)
2886 {
2887         int extension = lsa->lsa_comp_flags & LCME_FL_EXTENSION;
2888         int rc;
2889
2890         if (prev->lsa_stripe_size) {
2891                 if (extension) {
2892                         prev->lsa_comp_end = lsa->lsa_comp_end;
2893                         prev->lsa_extension_size = lsa->lsa_extension_size;
2894                         prev->lsa_extension_comp = true;
2895                 }
2896
2897                 rc = build_component(layout, prev, true);
2898                 if (rc)
2899                         return rc;
2900         }
2901
2902         /*
2903          * Copy lsa to previous lsa;
2904          * if this is an extension component, make the previous invalid;
2905          */
2906         if (extension)
2907                 prev->lsa_stripe_size = 0;
2908         else
2909                 *prev = *lsa;
2910
2911         return 0;
2912 }
2913
2914 #ifndef LCME_TEMPLATE_FLAGS
2915 #define LCME_TEMPLATE_FLAGS     (LCME_FL_PREF_RW | LCME_FL_NOSYNC | \
2916                                  LCME_FL_EXTENSION)
2917 #endif
2918
2919 static int build_layout_from_yaml_node(struct cYAML *node,
2920                                        struct llapi_layout **layout,
2921                                        struct lfs_setstripe_args *lsa,
2922                                        struct lfs_setstripe_args *prevp)
2923 {
2924         struct lfs_setstripe_args prev = { 0 };
2925         __u32 *osts = lsa->lsa_tgts;
2926         char *string;
2927         int rc = 0;
2928
2929         if (!prevp)
2930                 prevp = &prev;
2931
2932         while (node) {
2933                 string = node->cy_string;
2934
2935                 if (node->cy_type == CYAML_TYPE_OBJECT) {
2936                         /* go deep to sub blocks */
2937                         if (string && !strncmp(string, "component", 9) &&
2938                             strncmp(string, "component0", 10) &&
2939                             strncmp(string, "components", 10)) {
2940                                 rc = build_prev_component(layout, prevp, lsa,
2941                                                           true);
2942                                 if (rc)
2943                                         return rc;
2944
2945                                 /* initialize lsa. */
2946                                 setstripe_args_init(lsa);
2947                                 lsa->lsa_first_comp = false;
2948                                 lsa->lsa_tgts = osts;
2949                         }
2950
2951                         rc = build_layout_from_yaml_node(node->cy_child, layout,
2952                                                          lsa, prevp);
2953                         if (rc)
2954                                 return rc;
2955                 } else {
2956                         if (!node->cy_string)
2957                                 return -EINVAL;
2958
2959                         /* skip leading lmm_ if present, to simplify parsing */
2960                         if (strncmp(string, "lmm_", 4) == 0)
2961                                 string += 4;
2962
2963                         if (node->cy_type == CYAML_TYPE_STRING) {
2964                                 if (!strcmp(string, "lcme_extent.e_end")) {
2965                                         if (!strcmp(node->cy_valuestring, "EOF") ||
2966                                             !strcmp(node->cy_valuestring, "eof"))
2967                                                 lsa->lsa_comp_end = LUSTRE_EOF;
2968                                 } else if (!strcmp(string, "pool")) {
2969                                         lsa->lsa_pool_name = node->cy_valuestring;
2970                                 } else if (!strcmp(string, "pattern")) {
2971                                         if (!strcmp(node->cy_valuestring, "mdt"))
2972                                                 lsa->lsa_pattern = LLAPI_LAYOUT_MDT;
2973                                         if (!strcmp(node->cy_valuestring,
2974                                                     "raid0,overstriped"))
2975                                                 lsa->lsa_pattern =
2976                                                         LLAPI_LAYOUT_OVERSTRIPING;
2977                                 } else if (!strcmp(string, "lcme_flags")) {
2978                                         rc = comp_str2flags(node->cy_valuestring,
2979                                                             &lsa->lsa_comp_flags,
2980                                                             &lsa->lsa_comp_neg_flags);
2981                                         if (rc)
2982                                                 return rc;
2983                                         /*
2984                                          * Only template flags have meaning in
2985                                          * the layout for a new file
2986                                          */
2987                                         lsa->lsa_comp_flags &= LCME_TEMPLATE_FLAGS;
2988                                 }
2989                         } else if (node->cy_type == CYAML_TYPE_NUMBER) {
2990                                 if (!strcmp(string, "lcm_mirror_count")) {
2991                                         lsa->lsa_mirror_count = node->cy_valueint;
2992                                 } else if (!strcmp(string, "lcme_extent.e_start")) {
2993                                         if (node->cy_valueint == 0)
2994                                                 lsa->lsa_first_comp = true;
2995                                 } else if (!strcmp(string, "lcme_extent.e_end")) {
2996                                         if (node->cy_valueint == -1)
2997                                                 lsa->lsa_comp_end = LUSTRE_EOF;
2998                                         else
2999                                                 lsa->lsa_comp_end = node->cy_valueint;
3000                                 } else if (!strcmp(string, "stripe_count")) {
3001                                         lsa->lsa_stripe_count = node->cy_valueint;
3002                                 } else if (!strcmp(string, "stripe_size")) {
3003                                         lsa->lsa_stripe_size = node->cy_valueint;
3004                                 } else if (!strcmp(string, "extension_size")) {
3005                                         lsa->lsa_extension_size = node->cy_valueint;
3006                                         lsa->lsa_extension_comp = true;
3007                                 } else if (!strcmp(string, "stripe_offset")) {
3008                                         lsa->lsa_stripe_off = node->cy_valueint;
3009                                 } else if (!strcmp(string, "l_ost_idx")) {
3010                                         osts[lsa->lsa_nr_tgts] = node->cy_valueint;
3011                                         lsa->lsa_nr_tgts++;
3012                                 }
3013                         }
3014                 }
3015                 node = node->cy_next;
3016         }
3017
3018         if (prevp == &prev) {
3019                 rc = build_prev_component(layout, prevp, lsa, true);
3020                 if (rc)
3021                         return rc;
3022
3023                 if (!(lsa->lsa_comp_flags & LCME_FL_EXTENSION))
3024                         rc = build_component(layout, lsa, *layout != NULL);
3025         }
3026
3027         return rc;
3028 }
3029
3030 static int lfs_comp_create_from_yaml(char *template,
3031                                      struct llapi_layout **layout,
3032                                      struct lfs_setstripe_args *lsa,
3033                                      __u32 *osts)
3034 {
3035         struct cYAML *tree = NULL, *err_rc = NULL;
3036         int rc = 0;
3037
3038         tree = cYAML_build_tree(template, NULL, 0, &err_rc, false);
3039         if (!tree) {
3040                 fprintf(stderr, "%s: cannot parse YAML file %s\n",
3041                         progname, template);
3042                 cYAML_build_error(-EINVAL, -1, "yaml", "from comp yaml",
3043                                   "can't parse", &err_rc);
3044                 cYAML_print_tree2file(stderr, err_rc);
3045                 cYAML_free_tree(err_rc);
3046                 rc = -EINVAL;
3047                 goto err;
3048         }
3049
3050         /* initialize lsa for plain file */
3051         setstripe_args_init(lsa);
3052         lsa->lsa_tgts = osts;
3053
3054         rc = build_layout_from_yaml_node(tree, layout, lsa, NULL);
3055         if (rc) {
3056                 fprintf(stderr, "%s: cannot build layout from YAML file %s.\n",
3057                         progname, template);
3058                 goto err;
3059         }
3060         /* clean clean lsa */
3061         setstripe_args_init(lsa);
3062
3063 err:
3064         if (tree)
3065                 cYAML_free_tree(tree);
3066         return rc;
3067 }
3068
3069 /**
3070  * Get the extension size from the next (SEL) component and extend the
3071  * current component on it. The start of the next component is to be
3072  * adjusted as well.
3073  *
3074  * \param[in] layout    the current layout
3075  * \param[in] start     the start of the current component
3076  * \param[in,out] end   the end of the current component
3077  * \param[in] offset    the offset to adjust the end position to instead of
3078  *                      extension size
3079  *
3080  * \retval 0            - extended successfully
3081  * \retval < 0          - error
3082  */
3083 static int layout_extend_comp(struct llapi_layout *layout,
3084                               uint64_t start, uint64_t *end,
3085                               uint64_t offset)
3086 {
3087         uint64_t size, next_start, next_end;
3088         int rc;
3089
3090         rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_NEXT);
3091         if (rc < 0) {
3092                 fprintf(stderr,
3093                         "%s setstripe: cannot move component cursor: %s\n",
3094                         progname, strerror(errno));
3095                 return rc;
3096         }
3097
3098         /*
3099          * Even if the @size will not be used below, this will fail if
3100          * this is not a SEL component - a good confirmation we are
3101          * working on right components.
3102          */
3103         rc = llapi_layout_extension_size_get(layout, &size);
3104         if (rc < 0) {
3105                 fprintf(stderr,
3106                         "%s setstripe: cannot get component ext size: %s\n",
3107                         progname, strerror(errno));
3108                 return rc;
3109         }
3110
3111         rc = llapi_layout_comp_extent_get(layout, &next_start, &next_end);
3112         if (rc) {
3113                 fprintf(stderr, "%s setstripe: cannot get extent: %s\n",
3114                         progname, strerror(errno));
3115                 return rc;
3116         }
3117
3118         next_start += offset ?: size;
3119         rc = llapi_layout_comp_extent_set(layout, next_start, next_end);
3120         if (rc) {
3121                 fprintf(stderr, "%s setstripe: cannot set extent: %s\n",
3122                         progname, strerror(errno));
3123                 return rc;
3124         }
3125
3126         rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_PREV);
3127         if (rc < 0) {
3128                 fprintf(stderr,
3129                         "%s setstripe: cannot move component cursor: %s\n",
3130                         progname, strerror(errno));
3131                 return rc;
3132         }
3133
3134         *end += offset ?: size;
3135         rc = llapi_layout_comp_extent_set(layout, start, *end);
3136         if (rc) {
3137                 fprintf(stderr, "%s setstripe: cannot set extent: %s\n",
3138                         progname, strerror(errno));
3139                 return rc;
3140         }
3141
3142         return 0;
3143 }
3144
3145 /**
3146  * In 'lfs setstripe --component-add' mode, we need to fetch the extent
3147  * end of the last component in the existing file, and adjust the
3148  * first extent start of the components to be added accordingly.
3149  *
3150  * In the create mode, we need to check if the first component is an extendable
3151  * SEL component and extend its length to the extension size (first component
3152  * of the PFL file is initialised at the create time, cannot be 0-lenght.
3153  */
3154 static int layout_adjust_first_extent(char *fname, struct llapi_layout *layout,
3155                                       bool comp_add)
3156 {
3157         struct llapi_layout *head;
3158         uint64_t start = 0, prev_end = 0;
3159         uint64_t end;
3160         int rc, ret = 0;
3161
3162         if (!layout || !(comp_add || llapi_layout_is_composite(layout)))
3163                 return 0;
3164
3165         errno = 0;
3166         while (comp_add) {
3167                 head = llapi_layout_get_by_path(fname, 0);
3168                 if (!head) {
3169                         fprintf(stderr,
3170                                 "%s setstripe: cannot read layout from '%s': %s\n",
3171                                 progname, fname, strerror(errno));
3172                         return -EINVAL;
3173                 } else if (errno == ENODATA) {
3174                         /*
3175                          * file without LOVEA, this component-add will be turned
3176                          * into a component-create.
3177                          */
3178                         llapi_layout_free(head);
3179                         ret = -ENODATA;
3180
3181                         /*
3182                          * the new layout will be added to an empty one, it
3183                          * still needs to be adjusted below
3184                          */
3185                         comp_add = 0;
3186                         break;
3187                 } else if (!llapi_layout_is_composite(head)) {
3188                         fprintf(stderr,
3189                                 "%s setstripe: '%s' not a composite file\n",
3190                                 progname, fname);
3191                         llapi_layout_free(head);
3192                         return -EINVAL;
3193                 }
3194
3195                 rc = llapi_layout_comp_extent_get(head, &start, &prev_end);
3196                 if (rc) {
3197                         fprintf(stderr,
3198                                 "%s setstripe: cannot get prev extent: %s\n",
3199                                 progname, strerror(errno));
3200                         llapi_layout_free(head);
3201                         return rc;
3202                 }
3203
3204                 llapi_layout_free(head);
3205                 break;
3206         }
3207
3208         /* Make sure we use the first component of the layout to be added. */
3209         rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_FIRST);
3210         if (rc < 0) {
3211                 fprintf(stderr,
3212                         "%s setstripe: cannot move component cursor: %s\n",
3213                         progname, strerror(errno));
3214                 return rc;
3215         }
3216
3217         rc = llapi_layout_comp_extent_get(layout, &start, &end);
3218         if (rc) {
3219                 fprintf(stderr, "%s setstripe: cannot get extent: %s\n",
3220                         progname, strerror(errno));
3221                 return rc;
3222         }
3223
3224         if (start == 0 && end == 0) {
3225                 rc = layout_extend_comp(layout, start, &end,
3226                                         comp_add ? prev_end : 0);
3227                 if (rc)
3228                         return rc;
3229         }
3230
3231         if (start > prev_end || end < prev_end) {
3232                 fprintf(stderr,
3233                         "%s setstripe: first extent [%lu, %lu) not adjacent with extent end %lu\n",
3234                         progname, start, end, prev_end);
3235                 return -EINVAL;
3236         }
3237
3238         rc = llapi_layout_comp_extent_set(layout, prev_end, end);
3239         if (rc) {
3240                 fprintf(stderr,
3241                         "%s setstripe: cannot set component extent [%lu, %lu): %s\n",
3242                         progname, prev_end, end, strerror(errno));
3243                 return rc;
3244         }
3245
3246         return ret;
3247 }
3248
3249 static int mirror_adjust_first_extents(struct mirror_args *list)
3250 {
3251         int rc = 0;
3252
3253         if (!list)
3254                 return 0;
3255
3256         while (list) {
3257                 rc = layout_adjust_first_extent(NULL, list->m_layout, false);
3258                 if (rc)
3259                         break;
3260                 list = list->m_next;
3261         }
3262
3263         return rc;
3264 }
3265
3266 static inline bool arg_is_eof(char *arg)
3267 {
3268         return !strncmp(arg, "-1", strlen("-1")) ||
3269                !strncmp(arg, "EOF", strlen("EOF")) ||
3270                !strncmp(arg, "eof", strlen("eof"));
3271 }
3272
3273 /**
3274  * lfs_mirror_alloc() - Allocate a mirror argument structure.
3275  *
3276  * Return: Valid mirror_args pointer on success and
3277  *         NULL if memory allocation fails.
3278  */
3279 static struct mirror_args *lfs_mirror_alloc(void)
3280 {
3281         struct mirror_args *mirror = NULL;
3282
3283         while (1) {
3284                 mirror = calloc(1, sizeof(*mirror));
3285                 if (mirror) {
3286                         mirror->m_inherit = false;
3287                         break;
3288                 }
3289
3290                 sleep(1);
3291         }
3292
3293         return mirror;
3294 }
3295
3296 /**
3297  * lfs_mirror_free() - Free memory allocated for a mirror argument
3298  *                     structure.
3299  * @mirror: Previously allocated mirror argument structure by
3300  *          lfs_mirror_alloc().
3301  *
3302  * Free memory allocated for @mirror.
3303  *
3304  * Return: void.
3305  */
3306 static void lfs_mirror_free(struct mirror_args *mirror)
3307 {
3308         if (mirror->m_layout)
3309                 llapi_layout_free(mirror->m_layout);
3310         free(mirror);
3311 }
3312
3313 /**
3314  * lfs_mirror_list_free() - Free memory allocated for a mirror list.
3315  * @mirror_list: Previously allocated mirror list.
3316  *
3317  * Free memory allocated for @mirror_list.
3318  *
3319  * Return: void.
3320  */
3321 static void lfs_mirror_list_free(struct mirror_args *mirror_list)
3322 {
3323         struct mirror_args *next_mirror = NULL;
3324
3325         while (mirror_list) {
3326                 next_mirror = mirror_list->m_next;
3327                 lfs_mirror_free(mirror_list);
3328                 mirror_list = next_mirror;
3329         }
3330 }
3331
3332 enum {
3333         LFS_POOL_OPT = 3,
3334         LFS_COMP_COUNT_OPT,
3335         LFS_COMP_START_OPT,
3336         LFS_COMP_FLAGS_OPT,
3337         LFS_COMP_DEL_OPT,
3338         LFS_COMP_SET_OPT,
3339         LFS_COMP_ADD_OPT,
3340         LFS_COMP_NO_VERIFY_OPT,
3341         LFS_PROJID_OPT,
3342         LFS_LAYOUT_FLAGS_OPT, /* used for mirror and foreign flags */
3343         LFS_MIRROR_ID_OPT,
3344         LFS_MIRROR_STATE_OPT,
3345         LFS_LAYOUT_COPY,
3346         LFS_MIRROR_INDEX_OPT,
3347         LFS_LAYOUT_FOREIGN_OPT,
3348         LFS_MODE_OPT,
3349         LFS_NEWERXY_OPT,
3350         LFS_INHERIT_RR_OPT,
3351         LFS_FIND_PERM,
3352 };
3353
3354 #ifndef LCME_USER_MIRROR_FLAGS
3355 /* The mirror flags can be set by users at creation time. */
3356 #define LCME_USER_MIRROR_FLAGS  (LCME_FL_PREF_RW)
3357 #endif
3358
3359 /* functions */
3360 static int lfs_setstripe_internal(int argc, char **argv,
3361                                   enum setstripe_origin opc)
3362 {
3363         struct lfs_setstripe_args        lsa = { 0 };
3364         struct llapi_stripe_param       *param = NULL;
3365         struct find_param                migrate_mdt_param = {
3366                 .fp_max_depth = -1,
3367                 .fp_mdt_index = -1,
3368         };
3369         char                            *fname;
3370         int                              result = 0;
3371         int                              result2 = 0;
3372         char                            *end;
3373         int                              c;
3374         int                              delete = 0;
3375         unsigned long long               size_units = 1;
3376         bool                             migrate_mode = false;
3377         bool                             migrate_mdt_mode = false;
3378         bool                             setstripe_mode = false;
3379         bool                             migration_block = false;
3380         __u64                            migration_flags = 0;
3381         __u32                            tgts[LOV_MAX_STRIPE_COUNT] = { 0 };
3382         int                              comp_del = 0, comp_set = 0;
3383         int                              comp_add = 0;
3384         __u32                            comp_id = 0;
3385         struct llapi_layout             *layout = NULL;
3386         struct llapi_layout             **lpp = &layout;
3387         bool                             mirror_mode = false;
3388         bool                             has_m_file = false;
3389         __u32                            mirror_count = 0;
3390         enum mirror_flags                mirror_flags = 0;
3391         struct mirror_args              *mirror_list = NULL;
3392         struct mirror_args              *new_mirror = NULL;
3393         struct mirror_args              *last_mirror = NULL;
3394         __u16                            mirror_id = 0;
3395         char                             cmd[PATH_MAX];
3396         bool from_yaml = false;
3397         bool from_copy = false;
3398         char *template = NULL;
3399         bool foreign_mode = false;
3400         char *xattr = NULL;
3401         uint32_t type = LU_FOREIGN_TYPE_NONE, flags = 0;
3402         char *mode_opt = NULL;
3403         mode_t previous_umask = 0;
3404         mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
3405
3406         struct option long_opts[] = {
3407 /* find { .val = '0',   .name = "null",         .has_arg = no_argument }, */
3408 /* find { .val = 'A',   .name = "atime",        .has_arg = required_argument }*/
3409         /* --block is only valid in migrate mode */
3410         { .val = 'b',   .name = "block",        .has_arg = no_argument },
3411 /* find { .val = 'B',   .name = "btime",        .has_arg = required_argument }*/
3412         { .val = LFS_COMP_ADD_OPT,
3413                         .name = "comp-add",     .has_arg = no_argument },
3414         { .val = LFS_COMP_ADD_OPT,
3415                         .name = "component-add", .has_arg = no_argument },
3416         { .val = LFS_COMP_DEL_OPT,
3417                         .name = "comp-del",     .has_arg = no_argument },
3418         { .val = LFS_COMP_DEL_OPT,
3419                         .name = "component-del", .has_arg = no_argument },
3420         { .val = LFS_COMP_FLAGS_OPT,
3421                         .name = "comp-flags",   .has_arg = required_argument },
3422         { .val = LFS_COMP_FLAGS_OPT,
3423                         .name = "component-flags",
3424                                                 .has_arg = required_argument },
3425         { .val = LFS_COMP_SET_OPT,
3426                         .name = "comp-set",     .has_arg = no_argument },
3427         { .val = LFS_COMP_SET_OPT,
3428                         .name = "component-set",
3429                                                 .has_arg = no_argument},
3430         { .val = LFS_COMP_NO_VERIFY_OPT,
3431                         .name = "no-verify",    .has_arg = no_argument},
3432         { .val = LFS_LAYOUT_FLAGS_OPT,
3433                         .name = "flags",        .has_arg = required_argument},
3434         { .val = LFS_LAYOUT_FOREIGN_OPT,
3435                         .name = "foreign",      .has_arg = optional_argument},
3436         { .val = LFS_MIRROR_ID_OPT,
3437                         .name = "mirror-id",    .has_arg = required_argument},
3438         { .val = LFS_MODE_OPT,
3439                         .name = "mode",         .has_arg = required_argument},
3440         { .val = LFS_LAYOUT_COPY,
3441                         .name = "copy",         .has_arg = required_argument},
3442         { .val = 'c',   .name = "stripe-count", .has_arg = required_argument},
3443         { .val = 'c',   .name = "stripe_count", .has_arg = required_argument},
3444         { .val = 'c',   .name = "mdt-count",    .has_arg = required_argument},
3445         { .val = 'C',   .name = "overstripe-count",
3446                                                 .has_arg = required_argument},
3447         { .val = 'd',   .name = "delete",       .has_arg = no_argument},
3448         { .val = 'd',   .name = "destroy",      .has_arg = no_argument},
3449         /* used with "lfs migrate -m" */
3450         { .val = 'd',   .name = "directory",    .has_arg = no_argument},
3451         /* --non-direct is only valid in migrate mode */
3452         { .val = 'D',   .name = "non-direct",   .has_arg = no_argument },
3453         { .val = 'E',   .name = "comp-end",     .has_arg = required_argument},
3454         { .val = 'E',   .name = "component-end",
3455                                                 .has_arg = required_argument},
3456         { .val = 'f',   .name = "file",         .has_arg = required_argument },
3457 /* find { .val = 'F',   .name = "fid",          .has_arg = no_argument }, */
3458 /* find { .val = 'g',   .name = "gid",          .has_arg = no_argument }, */
3459 /* find { .val = 'G',   .name = "group",        .has_arg = required_argument }*/
3460         { .val = 'h',   .name = "help",         .has_arg = no_argument },
3461         { .val = 'H',   .name = "mdt-hash",     .has_arg = required_argument},
3462         { .val = 'i',   .name = "stripe-index", .has_arg = required_argument},
3463         { .val = 'i',   .name = "stripe_index", .has_arg = required_argument},
3464         { .val = 'I',   .name = "comp-id",      .has_arg = required_argument},
3465         { .val = 'I',   .name = "component-id", .has_arg = required_argument},
3466 /* find { .val = 'l',   .name = "lazy",         .has_arg = no_argument }, */
3467         { .val = 'L',   .name = "layout",       .has_arg = required_argument },
3468         { .val = 'm',   .name = "mdt",          .has_arg = required_argument},
3469         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument},
3470         { .val = 'm',   .name = "mdt_index",    .has_arg = required_argument},
3471         /* --non-block is only valid in migrate mode */
3472         { .val = 'n',   .name = "non-block",    .has_arg = no_argument },
3473         { .val = 'N',   .name = "mirror-count", .has_arg = optional_argument},
3474         { .val = 'o',   .name = "ost",          .has_arg = required_argument },
3475 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
3476         { .val = 'o',   .name = "ost-list",     .has_arg = required_argument },
3477         { .val = 'o',   .name = "ost_list",     .has_arg = required_argument },
3478 #endif
3479         { .val = 'p',   .name = "pool",         .has_arg = required_argument },
3480 /* find { .val = 'P',   .name = "print",        .has_arg = no_argument }, */
3481 /* getstripe { .val = 'q', .name = "quiet",     .has_arg = no_argument }, */
3482 /* getstripe { .val = 'R', .name = "raw",       .has_arg = no_argument }, */
3483         { .val = 'S',   .name = "stripe-size",  .has_arg = required_argument },
3484         { .val = 'S',   .name = "stripe_size",  .has_arg = required_argument },
3485 /* find { .val = 't',   .name = "type",         .has_arg = required_argument }*/
3486 /* dirstripe { .val = 'T', .name = "mdt-count", .has_arg = required_argument }*/
3487 /* find { .val = 'u',   .name = "uid",          .has_arg = required_argument }*/
3488 /* find { .val = 'U',   .name = "user",         .has_arg = required_argument }*/
3489         /* --verbose is only valid in migrate mode */
3490         { .val = 'v',   .name = "verbose",      .has_arg = no_argument},
3491         { .val = 'x',   .name = "xattr",        .has_arg = required_argument },
3492 /* dirstripe { .val = 'X',.name = "max-inherit",.has_arg = required_argument }*/
3493         { .val = 'y',   .name = "yaml",         .has_arg = required_argument },
3494         { .val = 'z',   .name = "ext-size",     .has_arg = required_argument},
3495         { .val = 'z',   .name = "extension-size", .has_arg = required_argument},
3496         { .name = NULL } };
3497
3498         setstripe_args_init(&lsa);
3499
3500         migrate_mode = (opc == SO_MIGRATE);
3501         mirror_mode = (opc == SO_MIRROR_CREATE || opc == SO_MIRROR_EXTEND);
3502         setstripe_mode = (opc == SO_SETSTRIPE);
3503         if (opc == SO_MIRROR_DELETE) {
3504                 delete = 1;
3505                 mirror_flags = MF_DESTROY;
3506         }
3507
3508         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
3509         progname = cmd;
3510         while ((c = getopt_long(argc, argv,
3511                                 "bc:C:dDE:f:hH:i:I:m:N::no:p:L:s:S:vx:y:z:",
3512                                 long_opts, NULL)) >= 0) {
3513                 size_units = 1;
3514                 switch (c) {
3515                 case 0:
3516                         /* Long options. */
3517                         break;
3518                 case LFS_COMP_ADD_OPT:
3519                         comp_add = 1;
3520                         break;
3521                 case LFS_COMP_DEL_OPT:
3522                         comp_del = 1;
3523                         break;
3524                 case LFS_COMP_FLAGS_OPT:
3525                         result = comp_str2flags(optarg, &lsa.lsa_comp_flags,
3526                                                 &lsa.lsa_comp_neg_flags);
3527                         if (result != 0)
3528                                 goto usage_error;
3529                         if (mirror_mode && lsa.lsa_comp_neg_flags) {
3530                                 fprintf(stderr,
3531                                         "%s: inverted flags are not supported\n",
3532                                         progname);
3533                                 goto usage_error;
3534                         }
3535                         break;
3536                 case LFS_COMP_SET_OPT:
3537                         comp_set = 1;
3538                         break;
3539                 case LFS_COMP_NO_VERIFY_OPT:
3540                         mirror_flags |= MF_NO_VERIFY;
3541                         break;
3542                 case LFS_MIRROR_ID_OPT: {
3543                         unsigned long int id;
3544
3545                         errno = 0;
3546                         id = strtoul(optarg, &end, 0);
3547                         if (errno != 0 || *end != '\0' || id == 0 ||
3548                             id > UINT16_MAX) {
3549                                 fprintf(stderr,
3550                                         "%s %s: invalid mirror ID '%s'\n",
3551                                         progname, argv[0], optarg);
3552                                 goto usage_error;
3553                         }
3554
3555                         mirror_id = (__u16)id;
3556                         break;
3557                 }
3558                 case LFS_LAYOUT_FLAGS_OPT: {
3559                         uint32_t neg_flags;
3560
3561                         /* check for numeric flags (foreign and mirror cases) */
3562                         if (setstripe_mode && !mirror_mode && !last_mirror) {
3563                                 errno = 0;
3564                                 flags = strtoul(optarg, &end, 16);
3565                                 if (errno != 0 || *end != '\0' ||
3566                                     flags >= UINT32_MAX) {
3567                                         fprintf(stderr,
3568                                                 "%s %s: invalid hex flags '%s'\n",
3569                                                 progname, argv[0], optarg);
3570                                         return CMD_HELP;
3571                                 }
3572                                 if (!foreign_mode) {
3573                                         fprintf(stderr,
3574                                                 "%s %s: hex flags must be specified with --foreign option\n",
3575                                                 progname, argv[0]);
3576                                         return CMD_HELP;
3577                                 }
3578                                 break;
3579                         }
3580
3581                         if (!mirror_mode || !last_mirror) {
3582                                 fprintf(stderr,
3583                                         "error: %s: --flags must be specified with --mirror-count|-N option\n",
3584                                         progname);
3585                                 goto usage_error;
3586                         }
3587
3588                         result = comp_str2flags(optarg, &last_mirror->m_flags,
3589                                                 &neg_flags);
3590                         if (result != 0)
3591                                 goto usage_error;
3592
3593                         if (neg_flags) {
3594                                 fprintf(stderr,
3595                                         "%s: inverted flags are not supported\n",
3596                                         progname);
3597                                 result = -EINVAL;
3598                                 goto usage_error;
3599                         }
3600                         if (last_mirror->m_flags & ~LCME_USER_MIRROR_FLAGS) {
3601                                 fprintf(stderr,
3602                                         "%s: unsupported mirror flags: %s\n",
3603                                         progname, optarg);
3604                                 result = -EINVAL;
3605                                 goto error;
3606                         }
3607                         break;
3608                 }
3609                 case LFS_LAYOUT_FOREIGN_OPT:
3610                         if (optarg) {
3611                                 /* check pure numeric */
3612                                 type = strtoul(optarg, &end, 0);
3613                                 if (*end) {
3614                                         /* check name */
3615                                         type = check_foreign_type_name(optarg);
3616                                         if (type == LU_FOREIGN_TYPE_UNKNOWN) {
3617                                                 fprintf(stderr,
3618                                                         "%s %s: unrecognized foreign type '%s'\n",
3619                                                         progname, argv[0],
3620                                                         optarg);
3621                                                 return CMD_HELP;
3622                                         }
3623                                 } else if (type >= UINT32_MAX) {
3624                                         fprintf(stderr,
3625                                                 "%s %s: invalid foreign type '%s'\n",
3626                                                 progname, argv[0], optarg);
3627                                         return CMD_HELP;
3628                                 }
3629                         }
3630                         foreign_mode = true;
3631                         break;
3632                 case LFS_MODE_OPT:
3633                         mode_opt = optarg;
3634                         if (mode_opt) {
3635                                 mode = strtoul(mode_opt, &end, 8);
3636                                 if (*end != '\0') {
3637                                         fprintf(stderr,
3638                                                 "%s %s: bad mode '%s'\n",
3639                                                 progname, argv[0], mode_opt);
3640                                         return CMD_HELP;
3641                                 }
3642                                 previous_umask = umask(0);
3643                         }
3644                         break;
3645                 case LFS_LAYOUT_COPY:
3646                         from_copy = true;
3647                         template = optarg;
3648                         break;
3649                 case 'b':
3650                         if (!migrate_mode) {
3651                                 fprintf(stderr,
3652                                         "%s %s: -b|--block valid only for migrate command\n",
3653                                         progname, argv[0]);
3654                                 goto usage_error;
3655                         }
3656                         migration_block = true;
3657                         break;
3658                 case 'C':
3659                         if (lsa.lsa_pattern == LLAPI_LAYOUT_MDT) {
3660                                 fprintf(stderr,
3661                                         "%s %s: -C|--overstripe-count incompatible with DoM layout\n",
3662                                         progname, argv[0]);
3663                                 goto usage_error;
3664                         }
3665                         lsa.lsa_pattern = LLAPI_LAYOUT_OVERSTRIPING;
3666                         /* fall through */
3667                 case 'c':
3668                         errno = 0;
3669                         lsa.lsa_stripe_count = strtoul(optarg, &end, 0);
3670                         if (errno != 0 || *end != '\0'||
3671                             lsa.lsa_stripe_count < -1 ||
3672                             lsa.lsa_stripe_count > LOV_MAX_STRIPE_COUNT) {
3673                                 fprintf(stderr,
3674                                         "%s %s: invalid stripe count '%s'\n",
3675                                         progname, argv[0], optarg);
3676                                 goto usage_error;
3677                         }
3678
3679                         if (lsa.lsa_stripe_count == -1)
3680                                 lsa.lsa_stripe_count = LLAPI_LAYOUT_WIDE;
3681                         break;
3682                 case 'd':
3683                         if (migrate_mode) {
3684                                 migrate_mdt_param.fp_max_depth = 1;
3685                         } else {
3686                                 /* delete the default striping pattern */
3687                                 delete = 1;
3688                                 if (opc == SO_MIRROR_SPLIT) {
3689                                         if (has_m_file) {
3690                                                 fprintf(stderr,
3691                                                       "%s %s: -d cannot used with -f\n",
3692                                                         progname, argv[0]);
3693                                                 goto usage_error;
3694                                         }
3695                                         mirror_flags |= MF_DESTROY;
3696                                 }
3697                         }
3698                         break;
3699                 case 'D':
3700                         if (!migrate_mode) {
3701                                 fprintf(stderr,
3702                                         "%s %s: -D|--non-direct is valid only for migrate command\n",
3703                                         progname, argv[0]);
3704                                 goto usage_error;
3705                         }
3706                         migration_flags |= LLAPI_MIGRATION_NONDIRECT;
3707                         break;
3708                 case 'E':
3709                         if (lsa.lsa_comp_end != 0) {
3710                                 result = comp_args_to_layout(lpp, &lsa, true);
3711                                 if (result) {
3712                                         fprintf(stderr, "%s: invalid layout\n",
3713                                                 progname);
3714                                         goto usage_error;
3715                                 }
3716
3717                                 setstripe_args_init_inherit(&lsa);
3718                         }
3719
3720                         if (arg_is_eof(optarg)) {
3721                                 lsa.lsa_comp_end = LUSTRE_EOF;
3722                         } else {
3723                                 result = llapi_parse_size(optarg,
3724                                                           &lsa.lsa_comp_end,
3725                                                           &size_units, 0);
3726                                 /* assume units of KB if too small */
3727                                 if (lsa.lsa_comp_end < 4096)
3728                                         lsa.lsa_comp_end *= 1024;
3729                                 if (result ||
3730                                     lsa.lsa_comp_end & (LOV_MIN_STRIPE_SIZE - 1)) {
3731                                         fprintf(stderr,
3732                                                 "%s %s: invalid component end '%s'\n",
3733                                                 progname, argv[0], optarg);
3734                                         goto usage_error;
3735                                 }
3736                         }
3737                         break;
3738                 case 'H':
3739                         if (!migrate_mode) {
3740                                 fprintf(stderr,
3741                                         "--mdt-hash is valid only for migrate command\n");
3742                                 return CMD_HELP;
3743                         }
3744
3745                         lsa.lsa_pattern = check_hashtype(optarg);
3746                         if (lsa.lsa_pattern == 0) {
3747                                 fprintf(stderr,
3748                                         "%s %s: bad stripe hash type '%s'\n",
3749                                         progname, argv[0], optarg);
3750                                 return CMD_HELP;
3751                         }
3752                         break;
3753                 case 'i':
3754                         errno = 0;
3755                         lsa.lsa_stripe_off = strtol(optarg, &end, 0);
3756                         if (errno != 0 || *end != '\0' ||
3757                             lsa.lsa_stripe_off < -1 ||
3758                             lsa.lsa_stripe_off > LOV_V1_INSANE_STRIPE_COUNT) {
3759                                 fprintf(stderr,
3760                                         "%s %s: invalid stripe offset '%s'\n",
3761                                         progname, argv[0], optarg);
3762                                 goto usage_error;
3763                         }
3764                         if (lsa.lsa_stripe_off == -1)
3765                                 lsa.lsa_stripe_off = LLAPI_LAYOUT_DEFAULT;
3766                         break;
3767                 case 'I':
3768                         comp_id = strtoul(optarg, &end, 0);
3769                         if (*end != '\0' || comp_id == 0 ||
3770                             comp_id > LCME_ID_MAX) {
3771                                 fprintf(stderr,
3772                                         "%s %s: invalid component ID '%s'\n",
3773                                         progname, argv[0], optarg);
3774                                 goto usage_error;
3775                         }
3776                         break;
3777                 case 'f':
3778                         if (opc != SO_MIRROR_EXTEND && opc != SO_MIRROR_SPLIT) {
3779                                 fprintf(stderr,
3780                                         "error: %s: invalid option: %s\n",
3781                                         progname, argv[optopt + 1]);
3782                                 goto usage_error;
3783                         }
3784                         if (opc == SO_MIRROR_EXTEND) {
3785                                 if (!last_mirror) {
3786                                         fprintf(stderr,
3787                                 "error: %s: '-N' must exist in front of '%s'\n",
3788                                                 progname, argv[optopt + 1]);
3789                                         goto usage_error;
3790                                 }
3791                                 last_mirror->m_file = optarg;
3792                                 last_mirror->m_count = 1;
3793                         } else {
3794                                 /* mirror split */
3795                                 if (!mirror_list)
3796                                         mirror_list = lfs_mirror_alloc();
3797                                 mirror_list->m_file = optarg;
3798                         }
3799                         has_m_file = true;
3800                         break;
3801                 case 'L':
3802                         if (strcmp(argv[optind - 1], "mdt") == 0) {
3803                                 /* Can be only the first component */
3804                                 if (layout) {
3805                                         result = -EINVAL;
3806                                         fprintf(stderr,
3807                                                 "error: 'mdt' layout can be only the first one\n");
3808                                         goto error;
3809                                 }
3810                                 if (lsa.lsa_comp_end > (1ULL << 30)) { /* 1Gb */
3811                                         result = -EFBIG;
3812                                         fprintf(stderr,
3813                                                 "error: 'mdt' layout size is too big\n");
3814                                         goto error;
3815                                 }
3816                                 lsa.lsa_pattern = LLAPI_LAYOUT_MDT;
3817                                 lsa.lsa_stripe_size = LLAPI_LAYOUT_DEFAULT;
3818                         } else if (strcmp(argv[optind - 1], "raid0") != 0) {
3819                                 result = -EINVAL;
3820                                 fprintf(stderr,
3821                                         "error: layout '%s' is unknown, supported layouts are: 'mdt', 'raid0'\n",
3822                                         argv[optind]);
3823                                 goto error;
3824                         }
3825                         break;
3826                 case 'm':
3827                         if (!migrate_mode) {
3828                                 fprintf(stderr,
3829                                         "%s %s: -m|--mdt-index is valid only for migrate command\n",
3830                                         progname, argv[0]);
3831                                 goto usage_error;
3832                         }
3833                         migrate_mdt_mode = true;
3834                         lsa.lsa_nr_tgts = parse_targets(tgts,
3835                                                 sizeof(tgts) / sizeof(__u32),
3836                                                 lsa.lsa_nr_tgts, optarg, NULL);
3837                         if (lsa.lsa_nr_tgts < 0) {
3838                                 fprintf(stderr,
3839                                         "%s: invalid MDT target(s) '%s'\n",
3840                                         progname, optarg);
3841                                 goto usage_error;
3842                         }
3843
3844                         lsa.lsa_tgts = tgts;
3845                         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
3846                                 lsa.lsa_stripe_off = tgts[0];
3847                         break;
3848                 case 'n':
3849                         if (!migrate_mode) {
3850                                 fprintf(stderr,
3851                                         "%s %s: -n|--non-block valid only for migrate command\n",
3852                                         progname, argv[0]);
3853                                 goto usage_error;
3854                         }
3855                         migration_flags |= LLAPI_MIGRATION_NONBLOCK;
3856                         break;
3857                 case 'N':
3858                         if (opc == SO_SETSTRIPE) {
3859                                 opc = SO_MIRROR_CREATE;
3860                                 mirror_mode = true;
3861                         }
3862                         mirror_count = 1;
3863                         if (optarg) {
3864                                 errno = 0;
3865                                 mirror_count = strtoul(optarg, &end, 0);
3866                                 if (errno != 0 || *end != '\0' ||
3867                                     mirror_count == 0 ||
3868                                     mirror_count > LUSTRE_MIRROR_COUNT_MAX) {
3869                                         fprintf(stderr,
3870                                                 "error: %s: bad mirror count: %s\n",
3871                                                 progname, optarg);
3872                                         result = -EINVAL;
3873                                         goto error;
3874                                 }
3875                         }
3876
3877                         new_mirror = lfs_mirror_alloc();
3878                         new_mirror->m_count = mirror_count;
3879
3880                         if (!mirror_list)
3881                                 mirror_list = new_mirror;
3882
3883                         if (last_mirror) {
3884                                 /* wrap up last mirror */
3885                                 if (!setstripe_args_specified(&lsa))
3886                                         last_mirror->m_inherit = true;
3887                                 if (lsa.lsa_comp_end == 0)
3888                                         lsa.lsa_comp_end = LUSTRE_EOF;
3889
3890                                 result = comp_args_to_layout(lpp, &lsa, true);
3891                                 if (result) {
3892                                         lfs_mirror_free(new_mirror);
3893                                         goto error;
3894                                 }
3895
3896                                 setstripe_args_init_inherit(&lsa);
3897
3898                                 last_mirror->m_next = new_mirror;
3899                         }
3900
3901                         last_mirror = new_mirror;
3902                         lpp = &last_mirror->m_layout;
3903                         break;
3904                 case 'o':
3905 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
3906                         if (strcmp(argv[optind - 1], "--ost-list") == 0)
3907                                 fprintf(stderr,
3908                                         "warning: '--ost-list' is deprecated, use '--ost' instead\n");
3909 #endif
3910                         if (lsa.lsa_pattern == LLAPI_LAYOUT_MDT) {
3911                                 fprintf(stderr,
3912                                         "%s %s: -o|--ost incompatible with DoM layout\n",
3913                                         progname, argv[0]);
3914                                 goto usage_error;
3915                         }
3916                         /*
3917                          * -o allows overstriping, and must note it because
3918                          * parse_targets is shared with MDT striping, which
3919                          * does not allow duplicates
3920                          */
3921                         lsa.lsa_pattern = LLAPI_LAYOUT_OVERSTRIPING;
3922                         lsa.lsa_nr_tgts = parse_targets(tgts,
3923                                                 sizeof(tgts) / sizeof(__u32),
3924                                                 lsa.lsa_nr_tgts, optarg,
3925                                                 &lsa.lsa_pattern);
3926                         if (lsa.lsa_nr_tgts < 0) {
3927                                 fprintf(stderr,
3928                                         "%s %s: invalid OST target(s) '%s'\n",
3929                                         progname, argv[0], optarg);
3930                                 goto usage_error;
3931                         }
3932
3933                         lsa.lsa_tgts = tgts;
3934                         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
3935                                 lsa.lsa_stripe_off = tgts[0];
3936                         break;
3937                 case 'p':
3938                         if (!optarg)
3939                                 goto usage_error;
3940                         lsa.lsa_pool_name = optarg;
3941
3942                         if (strlen(lsa.lsa_pool_name) == 0 ||
3943                             strncmp(lsa.lsa_pool_name, "none",
3944                                     LOV_MAXPOOLNAME) == 0)
3945                                 lsa.lsa_pool_name = NULL;
3946                         break;
3947                 case 'S':
3948                         result = llapi_parse_size(optarg, &lsa.lsa_stripe_size,
3949                                                   &size_units, 0);
3950                         /* assume units of KB if too small to be valid */
3951                         if (lsa.lsa_stripe_size < 4096)
3952                                 lsa.lsa_stripe_size *= 1024;
3953                         if (result ||
3954                             lsa.lsa_stripe_size & (LOV_MIN_STRIPE_SIZE - 1)) {
3955                                 fprintf(stderr,
3956                                         "%s %s: invalid stripe size '%s'\n",
3957                                         progname, argv[0], optarg);
3958                                 goto usage_error;
3959                         }
3960                         break;
3961                 case 'v':
3962                         if (!migrate_mode) {
3963                                 fprintf(stderr,
3964                                         "%s %s: -v|--verbose valid only for migrate command\n",
3965                                         progname, argv[0]);
3966                                 goto usage_error;
3967                         }
3968                         migrate_mdt_param.fp_verbose = VERBOSE_DETAIL;
3969                         migration_flags = LLAPI_MIGRATION_VERBOSE;
3970                         break;
3971                 case 'x':
3972                         xattr = optarg;
3973                         break;
3974                 case 'y':
3975                         from_yaml = true;
3976                         template = optarg;
3977                         break;
3978                 case 'z':
3979                         result = llapi_parse_size(optarg,
3980                                                   &lsa.lsa_extension_size,
3981                                                   &size_units, 0);
3982                         if (result) {
3983                                 fprintf(stderr,
3984                                         "%s %s: invalid extension size '%s'\n",
3985                                         progname, argv[0], optarg);
3986                                 goto usage_error;
3987                         }
3988
3989                         lsa.lsa_extension_comp = true;
3990                         break;
3991                 default:
3992                         fprintf(stderr, "%s: unrecognized option '%s'\n",
3993                                 progname, argv[optind - 1]);
3994                 case 'h':
3995                         goto usage_error;
3996                 }
3997         }
3998
3999         fname = argv[optind];
4000
4001         if (optind == argc) {
4002                 fprintf(stderr, "%s %s: FILE must be specified\n",
4003                         progname, argv[0]);
4004                 goto usage_error;
4005         }
4006
4007         /* lfs migrate $filename should keep the file's layout by default */
4008         if (migrate_mode && !layout && !from_yaml &&
4009             !setstripe_args_specified(&lsa) && !lsa.lsa_pool_name)
4010                 from_copy = true;
4011
4012         if (xattr && !foreign_mode) {
4013                 /*
4014                  * only print a warning as this is harmless and will be ignored
4015                  */
4016                 fprintf(stderr,
4017                         "%s %s: xattr has been specified for non-foreign layout\n",
4018                         progname, argv[0]);
4019         } else if (foreign_mode && !xattr) {
4020                 fprintf(stderr,
4021                         "%s %s: xattr must be provided in foreign mode\n",
4022                         progname, argv[0]);
4023                 goto usage_error;
4024         }
4025
4026         if (foreign_mode && (!setstripe_mode || comp_add | comp_del ||
4027             comp_set || comp_id || delete || from_copy ||
4028             setstripe_args_specified(&lsa) || lsa.lsa_nr_tgts ||
4029             lsa.lsa_tgts)) {
4030                 fprintf(stderr,
4031                         "%s %s: only --xattr/--flags/--mode options are valid with --foreign\n",
4032                         progname, argv[0]);
4033                 return CMD_HELP;
4034         }
4035
4036         if (mirror_mode && mirror_count == 0) {
4037                 fprintf(stderr,
4038                         "error: %s: --mirror-count|-N option is required\n",
4039                         progname);
4040                 result = -EINVAL;
4041                 goto error;
4042         }
4043
4044         if (mirror_mode) {
4045                 if (!setstripe_args_specified(&lsa))
4046                         last_mirror->m_inherit = true;
4047                 if (lsa.lsa_comp_end == 0)
4048                         lsa.lsa_comp_end = LUSTRE_EOF;
4049         }
4050
4051         if (lsa.lsa_comp_end != 0) {
4052                 result = comp_args_to_layout(lpp, &lsa, true);
4053                 if (result) {
4054                         fprintf(stderr, "error: %s: invalid layout\n",
4055                                 progname);
4056                         result = -EINVAL;
4057                         goto error;
4058                 }
4059         }
4060
4061         if (mirror_flags & MF_NO_VERIFY) {
4062                 if (opc != SO_MIRROR_EXTEND) {
4063                         fprintf(stderr,
4064                                 "error: %s: --no-verify is valid only for lfs mirror extend command\n",
4065                                 progname);
4066                         result = -EINVAL;
4067                         goto error;
4068                 } else if (!has_m_file) {
4069                         fprintf(stderr,
4070                                 "error: %s: --no-verify must be specified with -f <victim_file> option\n",
4071                                 progname);
4072                         result = -EINVAL;
4073                         goto error;
4074                 }
4075         }
4076
4077         if (comp_set && !comp_id && !lsa.lsa_pool_name) {
4078                 fprintf(stderr,
4079                         "%s %s: --component-set doesn't have component-id set\n",
4080                         progname, argv[0]);
4081                 goto usage_error;
4082         }
4083
4084         if ((delete + comp_set + comp_del + comp_add) > 1) {
4085                 fprintf(stderr,
4086                         "%s %s: options --component-set, --component-del, --component-add and -d are mutually exclusive\n",
4087                         progname, argv[0]);
4088                 goto usage_error;
4089         }
4090
4091         if (delete && (setstripe_args_specified(&lsa) || comp_id != 0 ||
4092                        lsa.lsa_comp_flags != 0 || layout != NULL)) {
4093                 fprintf(stderr,
4094                         "%s %s: option -d is mutually exclusive with -s, -c, -o, -p, -I, -F and -E options\n",
4095                         progname, argv[0]);
4096                 goto usage_error;
4097         }
4098
4099         if ((comp_set || comp_del) &&
4100             (setstripe_args_specified(&lsa) || layout != NULL)) {
4101                 fprintf(stderr,
4102                         "%s %s: options --component-del and --component-set are mutually exclusive when used with -c, -E, -o, -p, or -s\n",
4103                         progname, argv[0]);
4104                 goto usage_error;
4105         }
4106
4107         if (comp_del && comp_id != 0 && lsa.lsa_comp_flags != 0) {
4108                 fprintf(stderr,
4109                         "%s %s: options -I and -F are mutually exclusive when used with --component-del\n",
4110                         progname, argv[0]);
4111                 goto usage_error;
4112         }
4113
4114         if (comp_add || comp_del) {
4115                 struct stat st;
4116
4117                 result = lstat(fname, &st);
4118                 if (result == 0 && S_ISDIR(st.st_mode)) {
4119                         fprintf(stderr,
4120                                 "%s setstripe: cannot use --component-add or --component-del for directory\n",
4121                                 progname);
4122                         goto usage_error;
4123                 }
4124
4125                 if (mirror_mode) {
4126                         fprintf(stderr,
4127                                 "error: %s: can't use --component-add or --component-del for mirror operation\n",
4128                                 progname);
4129                         goto usage_error;
4130                 }
4131         }
4132
4133         if (comp_add) {
4134                 if (!layout) {
4135                         fprintf(stderr,
4136                                 "%s %s: option -E must be specified with --component-add\n",
4137                                 progname, argv[0]);
4138                         goto usage_error;
4139                 }
4140         }
4141
4142         if (from_yaml && from_copy) {
4143                 fprintf(stderr,
4144                         "%s: can't specify --yaml and --copy together\n",
4145                         progname);
4146                 goto error;
4147         }
4148
4149         if ((from_yaml || from_copy) &&
4150             (setstripe_args_specified(&lsa) || layout != NULL)) {
4151                 fprintf(stderr,
4152                         "error: %s: can't specify --yaml or --copy with -c, -S, -i, -o, -p or -E options.\n",
4153                         argv[0]);
4154                 goto error;
4155         }
4156
4157         if ((migration_flags & LLAPI_MIGRATION_NONBLOCK) && migration_block) {
4158                 fprintf(stderr,
4159                         "%s %s: options --non-block and --block are mutually exclusive\n",
4160                         progname, argv[0]);
4161                 goto usage_error;
4162         }
4163
4164         if (!comp_del && !comp_set && opc != SO_MIRROR_SPLIT &&
4165             opc != SO_MIRROR_DELETE && comp_id != 0) {
4166                 fprintf(stderr,
4167                         "%s: option -I can only be used with --component-del or --component-set or lfs mirror split\n",
4168                         progname);
4169                 goto usage_error;
4170         }
4171
4172         if (migrate_mdt_mode) {
4173                 struct lmv_user_md *lmu;
4174
4175                 /* initialize migrate mdt parameters */
4176                 lmu = calloc(1, lmv_user_md_size(lsa.lsa_nr_tgts,
4177                                                  LMV_USER_MAGIC_SPECIFIC));
4178                 if (!lmu) {
4179                         fprintf(stderr,
4180                                 "%s %s: cannot allocate memory for lmv_user_md: %s\n",
4181                                 progname, argv[0], strerror(ENOMEM));
4182                         result = -ENOMEM;
4183                         goto error;
4184                 }
4185                 if (lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT)
4186                         lmu->lum_stripe_count = lsa.lsa_stripe_count;
4187                 if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT) {
4188                         fprintf(stderr,
4189                                 "%s %s: migrate should specify MDT index\n",
4190                                 progname, argv[0]);
4191                         free(lmu);
4192                         goto usage_error;
4193                 }
4194                 lmu->lum_stripe_offset = lsa.lsa_stripe_off;
4195                 if (lsa.lsa_pattern != LLAPI_LAYOUT_RAID0)
4196                         lmu->lum_hash_type = lsa.lsa_pattern;
4197                 else
4198                         lmu->lum_hash_type = LMV_HASH_TYPE_UNKNOWN;
4199                 if (lsa.lsa_pool_name) {
4200                         strncpy(lmu->lum_pool_name, lsa.lsa_pool_name,
4201                                 sizeof(lmu->lum_pool_name) - 1);
4202                         lmu->lum_pool_name[sizeof(lmu->lum_pool_name) - 1] = 0;
4203                 }
4204                 if (lsa.lsa_nr_tgts > 1) {
4205                         int i;
4206
4207                         if (lsa.lsa_stripe_count > 0 &&
4208                             lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT &&
4209                             lsa.lsa_stripe_count != lsa.lsa_nr_tgts) {
4210                                 fprintf(stderr,
4211                                         "error: %s: stripe count %lld doesn't match the number of MDTs: %d\n",
4212                                         progname, lsa.lsa_stripe_count,
4213                                         lsa.lsa_nr_tgts);
4214                                 free(lmu);
4215                                 goto usage_error;
4216                         }
4217
4218                         lmu->lum_magic = LMV_USER_MAGIC_SPECIFIC;
4219                         lmu->lum_stripe_count = lsa.lsa_nr_tgts;
4220                         for (i = 0; i < lsa.lsa_nr_tgts; i++)
4221                                 lmu->lum_objects[i].lum_mds = lsa.lsa_tgts[i];
4222                 } else {
4223                         lmu->lum_magic = LMV_USER_MAGIC;
4224                 }
4225
4226                 migrate_mdt_param.fp_lmv_md = lmu;
4227                 migrate_mdt_param.fp_migrate = 1;
4228         } else if (!layout) {
4229                 if (lsa_args_stripe_count_check(&lsa))
4230                         goto usage_error;
4231
4232                 /* initialize stripe parameters */
4233                 param = calloc(1, offsetof(typeof(*param),
4234                                lsp_osts[lsa.lsa_nr_tgts]));
4235                 if (!param) {
4236                         fprintf(stderr,
4237                                 "%s %s: cannot allocate memory for parameters: %s\n",
4238                                 progname, argv[0], strerror(ENOMEM));
4239                         result = -ENOMEM;
4240                         goto error;
4241                 }
4242
4243                 if (lsa.lsa_stripe_size != LLAPI_LAYOUT_DEFAULT)
4244                         param->lsp_stripe_size = lsa.lsa_stripe_size;
4245                 if (lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT) {
4246                         if (lsa.lsa_stripe_count == LLAPI_LAYOUT_WIDE)
4247                                 param->lsp_stripe_count = -1;
4248                         else
4249                                 param->lsp_stripe_count = lsa.lsa_stripe_count;
4250                 }
4251                 if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
4252                         param->lsp_stripe_offset = -1;
4253                 else
4254                         param->lsp_stripe_offset = lsa.lsa_stripe_off;
4255                 param->lsp_stripe_pattern =
4256                                 llapi_pattern_to_lov(lsa.lsa_pattern);
4257                 if (param->lsp_stripe_pattern == EINVAL) {
4258                         fprintf(stderr, "error: %s: invalid stripe pattern\n",
4259                                 argv[0]);
4260                         free(param);
4261                         goto usage_error;
4262                 }
4263                 param->lsp_pool = lsa.lsa_pool_name;
4264                 param->lsp_is_specific = false;
4265
4266                 if (lsa.lsa_nr_tgts > 0) {
4267                         param->lsp_is_specific = true;
4268                         param->lsp_stripe_count = lsa.lsa_nr_tgts;
4269                         memcpy(param->lsp_osts, tgts,
4270                                sizeof(*tgts) * lsa.lsa_nr_tgts);
4271                 }
4272         }
4273
4274         if (from_yaml) {
4275                 /* generate a layout from a YAML template */
4276                 result = lfs_comp_create_from_yaml(template, &layout,
4277                                                    &lsa, tgts);
4278                 if (result) {
4279                         fprintf(stderr,
4280                                 "error: %s: can't create composite layout from template file %s\n",
4281                                 argv[0], template);
4282                         goto error;
4283                 }
4284         }
4285
4286         if (layout != NULL || mirror_list != NULL) {
4287                 if (mirror_list)
4288                         result = mirror_adjust_first_extents(mirror_list);
4289                 else
4290                         result = layout_adjust_first_extent(fname, layout,
4291                                                             comp_add);
4292                 if (result == -ENODATA)
4293                         comp_add = 0;
4294                 else if (result != 0) {
4295                         fprintf(stderr, "error: %s: invalid layout\n",
4296                                 progname);
4297                         goto error;
4298                 }
4299         }
4300
4301         for (fname = argv[optind]; fname != NULL; fname = argv[++optind]) {
4302                 if (from_copy) {
4303                         layout = llapi_layout_get_by_path(template ?: fname, 0);
4304                         if (!layout) {
4305                                 fprintf(stderr,
4306                                         "%s: can't create composite layout from file %s: %s\n",
4307                                         progname, template ?: fname,
4308                                         strerror(errno));
4309                                 result = -errno;
4310                                 goto error;
4311                         }
4312                 }
4313
4314                 if (migrate_mdt_mode) {
4315                         result = llapi_migrate_mdt(fname, &migrate_mdt_param);
4316                 } else if (migrate_mode) {
4317                         result = lfs_migrate(fname, migration_flags, param,
4318                                              layout);
4319                 } else if (comp_set != 0) {
4320                         result = lfs_component_set(fname, comp_id,
4321                                                    lsa.lsa_pool_name,
4322                                                    lsa.lsa_comp_flags,
4323                                                    lsa.lsa_comp_neg_flags);
4324                 } else if (comp_del != 0) {
4325                         result = lfs_component_del(fname, comp_id,
4326                                                    lsa.lsa_comp_flags,
4327                                                    lsa.lsa_comp_neg_flags);
4328                 } else if (comp_add != 0) {
4329                         result = lfs_component_add(fname, layout);
4330                 } else if (opc == SO_MIRROR_CREATE) {
4331                         result = mirror_create(fname, mirror_list);
4332                 } else if (opc == SO_MIRROR_EXTEND) {
4333                         result = mirror_extend(fname, mirror_list,
4334                                                mirror_flags);
4335                 } else if (opc == SO_MIRROR_SPLIT || opc == SO_MIRROR_DELETE) {
4336                         if (!mirror_id && !comp_id && !lsa.lsa_pool_name) {
4337                                 fprintf(stderr,
4338                                         "%s: no mirror id, component id, or pool name specified to delete from '%s'\n",
4339                                         progname, fname);
4340                                 goto usage_error;
4341                         }
4342                         if (lsa.lsa_pool_name)
4343                                 mirror_flags |= MF_COMP_POOL;
4344                         else if (mirror_id != 0)
4345                                 comp_id = mirror_id;
4346                         else
4347                                 mirror_flags |= MF_COMP_ID;
4348                         if (has_m_file && !strcmp(fname, mirror_list->m_file)) {
4349                                 fprintf(stderr,
4350                                         "%s: the file specified by -f cannot be same as the source file '%s'\n",
4351                                         progname, fname);
4352                                 goto usage_error;
4353                         }
4354                         result = mirror_split(fname, comp_id, lsa.lsa_pool_name,
4355                                               mirror_flags,
4356                                               has_m_file ? mirror_list->m_file :
4357                                               NULL);
4358                 } else if (layout) {
4359                         result = lfs_component_create(fname, O_CREAT | O_WRONLY,
4360                                                       mode, layout);
4361                         if (result >= 0) {
4362                                 close(result);
4363                                 result = 0;
4364                         }
4365                 } else if (foreign_mode) {
4366                         result = llapi_file_create_foreign(fname, mode, type,
4367                                                            flags, xattr);
4368                         if (result >= 0) {
4369                                 close(result);
4370                                 result = 0;
4371                         }
4372                 } else {
4373                         result = llapi_file_open_param(fname,
4374                                                        O_CREAT | O_WRONLY,
4375                                                        mode, param);
4376                         if (result >= 0) {
4377                                 close(result);
4378                                 result = 0;
4379                         }
4380                 }
4381                 if (result) {
4382                         /* Save the first error encountered. */
4383                         if (result2 == 0)
4384                                 result2 = result;
4385                         continue;
4386                 }
4387         }
4388
4389         if (mode_opt)
4390                 umask(previous_umask);
4391
4392         free(param);
4393         free(migrate_mdt_param.fp_lmv_md);
4394         llapi_layout_free(layout);
4395         lfs_mirror_list_free(mirror_list);
4396         return result2;
4397 usage_error:
4398         result = CMD_HELP;
4399 error:
4400         llapi_layout_free(layout);
4401         lfs_mirror_list_free(mirror_list);
4402         return result;
4403 }
4404
4405 static int lfs_poollist(int argc, char **argv)
4406 {
4407         if (argc != 2)
4408                 return CMD_HELP;
4409
4410         return llapi_poollist(argv[1]);
4411 }
4412
4413 #define FP_DEFAULT_TIME_MARGIN (24 * 60 * 60)
4414 static time_t set_time(struct find_param *param, time_t *time, time_t *set,
4415                        char *str)
4416 {
4417         long long t = 0;
4418         int sign = 0;
4419         char *endptr = "AD";
4420         char *timebuf;
4421
4422         if (str[0] == '+')
4423                 sign = 1;
4424         else if (str[0] == '-')
4425                 sign = -1;
4426
4427         if (sign)
4428                 str++;
4429
4430         for (timebuf = str; *endptr && *(endptr + 1); timebuf = endptr + 1) {
4431                 long long val = strtoll(timebuf, &endptr, 0);
4432                 int unit = 1;
4433
4434                 switch (*endptr) {
4435                 case  'y':
4436                         unit *= 52; /* 52 weeks + 1 day below */
4437                 case  'w':      /* fallthrough */
4438                         unit *= 7;
4439                         if (param->fp_time_margin == FP_DEFAULT_TIME_MARGIN)
4440                                 param->fp_time_margin *= (1 + unit / 52);
4441                         unit += (*endptr == 'y'); /* +1 day for 365 days/year */
4442                 case '\0': /* days are default unit if none used */
4443                 case  'd':      /* fallthrough */
4444                         unit *= 24;
4445                 case  'h':      /* fallthrough */
4446                         unit *= 60;
4447                 case  'm':      /* fallthrough */
4448                         unit *= 60;
4449                 case  's':      /* fallthrough */
4450                         break;
4451                         /* don't need to multiply by 1 for seconds */
4452                 default:
4453                         fprintf(stderr,
4454                                 "%s find: bad time string '%s': %s\n",
4455                                 progname, timebuf, strerror(EINVAL));
4456                         return LONG_MAX;
4457                 }
4458
4459                 if (param->fp_time_margin == 0 ||
4460                     (*endptr && unit < param->fp_time_margin))
4461                         param->fp_time_margin = unit;
4462
4463                 t += val * unit;
4464         }
4465         if (*time < t) {
4466                 if (sign != 0)
4467                         str--;
4468                 fprintf(stderr, "%s find: bad time '%s': too large\n",
4469                         progname, str);
4470                 return LONG_MAX;
4471         }
4472
4473         *set = *time - t;
4474
4475         return sign;
4476 }
4477
4478 static int str2quotaid(__u32 *id, const char *arg)
4479 {
4480         unsigned long int projid_tmp = 0;
4481         char *endptr = NULL;
4482
4483         projid_tmp = strtoul(arg, &endptr, 10);
4484         if (*endptr != '\0')
4485                 return -EINVAL;
4486         /* UINT32_MAX is not allowed - see projid_valid()/INVALID_PROJID */
4487         if (projid_tmp >= UINT32_MAX)
4488                 return -ERANGE;
4489
4490         *id = projid_tmp;
4491         return 0;
4492 }
4493
4494 static int name2uid(unsigned int *id, const char *name)
4495 {
4496         struct passwd *passwd;
4497
4498         passwd = getpwnam(name);
4499         if (!passwd)
4500                 return -ENOENT;
4501         *id = passwd->pw_uid;
4502
4503         return 0;
4504 }
4505
4506 static int name2gid(unsigned int *id, const char *name)
4507 {
4508         struct group *group;
4509
4510         group = getgrnam(name);
4511         if (!group)
4512                 return -ENOENT;
4513         *id = group->gr_gid;
4514
4515         return 0;
4516 }
4517
4518 static inline int name2projid(unsigned int *id, const char *name)
4519 {
4520         return -ENOTSUP;
4521 }
4522
4523 static int uid2name(char **name, unsigned int id)
4524 {
4525         struct passwd *passwd;
4526
4527         passwd = getpwuid(id);
4528         if (!passwd)
4529                 return -ENOENT;
4530         *name = passwd->pw_name;
4531
4532         return 0;
4533 }
4534
4535 static inline int gid2name(char **name, unsigned int id)
4536 {
4537         struct group *group;
4538
4539         group = getgrgid(id);
4540         if (!group)
4541                 return -ENOENT;
4542         *name = group->gr_name;
4543
4544         return 0;
4545 }
4546
4547 static int name2layout(__u32 *layout, char *name)
4548 {
4549         char *ptr, *layout_name;
4550
4551         *layout = 0;
4552         for (ptr = name; ; ptr = NULL) {
4553                 layout_name = strtok(ptr, ",");
4554                 if (!layout_name)
4555                         break;
4556                 if (strcmp(layout_name, "released") == 0)
4557                         *layout |= LOV_PATTERN_F_RELEASED;
4558                 else if (strcmp(layout_name, "raid0") == 0)
4559                         *layout |= LOV_PATTERN_RAID0;
4560                 else if (strcmp(layout_name, "mdt") == 0)
4561                         *layout |= LOV_PATTERN_MDT;
4562                 else if (strcmp(layout_name, "overstriping") == 0)
4563                         *layout |= LOV_PATTERN_OVERSTRIPING;
4564                 else
4565                         return -1;
4566         }
4567         return 0;
4568 }
4569
4570 static int parse_symbolic(const char *input, mode_t *outmode, const char **end)
4571 {
4572         int loop;
4573         int user, group, other;
4574         int who, all;
4575         char c, op;
4576         mode_t perm;
4577         mode_t usermask;
4578         mode_t previous_flags;
4579
4580         user = group = other = 0;
4581         all = 0;
4582         loop = 1;
4583         perm = 0;
4584         previous_flags = 0;
4585         *end = input;
4586         usermask = 0;
4587
4588         while (loop) {
4589                 switch (*input) {
4590                 case 'u':
4591                         user = 1;
4592                         break;
4593                 case 'g':
4594                         group = 1;
4595                         break;
4596                 case 'o':
4597                         other = 1;
4598                         break;
4599                 case 'a':
4600                         user = group = other = 1;
4601                         all = 1;
4602                         break;
4603                 default:
4604                         loop = 0;
4605                 }
4606
4607                 if (loop)
4608                         input++;
4609         }
4610
4611         who = user || group || other;
4612         if (!who) {
4613                 /* get the umask */
4614                 usermask = umask(0022);
4615                 umask(usermask);
4616                 usermask &= 07777;
4617         }
4618
4619         if (*input == '-' || *input == '+' || *input == '=')
4620                 op = *input++;
4621         else
4622                 /* operation is required */
4623                 return -1;
4624
4625         /* get the flags in *outmode */
4626         switch (*input) {
4627         case 'u':
4628                 previous_flags = (*outmode & 0700);
4629                 perm |= user  ? previous_flags : 0;
4630                 perm |= group ? (previous_flags >> 3) : 0;
4631                 perm |= other ? (previous_flags >> 6) : 0;
4632                 input++;
4633                 goto write_perm;
4634         case 'g':
4635                 previous_flags = (*outmode & 0070);
4636                 perm |= user  ? (previous_flags << 3) : 0;
4637                 perm |= group ? previous_flags : 0;
4638                 perm |= other ? (previous_flags >> 3) : 0;
4639                 input++;
4640                 goto write_perm;
4641         case 'o':
4642                 previous_flags = (*outmode & 0007);
4643                 perm |= user  ? (previous_flags << 6) : 0;
4644                 perm |= group ? (previous_flags << 3) : 0;
4645                 perm |= other ? previous_flags : 0;
4646                 input++;
4647                 goto write_perm;
4648         default:
4649                 break;
4650         }
4651
4652         /* this part is optional,
4653          * if empty perm = 0 and *outmode is not modified
4654          */
4655         loop = 1;
4656         while (loop) {
4657                 c = *input;
4658                 switch (c) {
4659                 case 'r':
4660                         perm |= user  ? 0400 : 0;
4661                         perm |= group ? 0040 : 0;
4662                         perm |= other ? 0004 : 0;
4663                         /* set read permission for uog except for umask's
4664                          * permissions
4665                          */
4666                         perm |= who   ? 0 : (0444 & ~usermask);
4667                         break;
4668                 case 'w':
4669                         perm |= user  ? 0200 : 0;
4670                         perm |= group ? 0020 : 0;
4671                         perm |= other ? 0002 : 0;
4672                         /* set write permission for uog except for umask'
4673                          * permissions
4674                          */
4675                         perm |= who   ? 0 : (0222 & ~usermask);
4676                         break;
4677                 case 'x':
4678                         perm |= user  ? 0100 : 0;
4679                         perm |= group ? 0010 : 0;
4680                         perm |= other ? 0001 : 0;
4681                         /* set execute permission for uog except for umask'
4682                          * permissions
4683                          */
4684                         perm |= who   ? 0 : (0111 & ~usermask);
4685                         break;
4686                 case 'X':
4687                         /*
4688                          * Adds execute permission to 'u', 'g' and/or 'g' if
4689                          * specified and either 'u', 'g' or 'o' already has
4690                          * execute permissions.
4691                          */
4692                         if ((*outmode & 0111) != 0) {
4693                                 perm |= user  ? 0100 : 0;
4694                                 perm |= group ? 0010 : 0;
4695                                 perm |= other ? 0001 : 0;
4696                                 perm |= !who  ? 0111 : 0;
4697                         }
4698                         break;
4699                 case 's':
4700                         /* s is ignored if o is given, but it's not an error */
4701                         if (other && !group && !user)
4702                                 break;
4703                         perm |= user  ? S_ISUID : 0;
4704                         perm |= group ? S_ISGID : 0;
4705                         break;
4706                 case 't':
4707                         /* 't' should be used when 'a' is given
4708                          * or who is empty
4709                          */
4710                         perm |= (!who || all) ? S_ISVTX : 0;
4711                         /* using ugo with t is not an error */
4712                         break;
4713                 default:
4714                         loop = 0;
4715                         break;
4716                 }
4717                 if (loop)
4718                         input++;
4719         }
4720
4721 write_perm:
4722         /* uog flags should be only one character long */
4723         if (previous_flags && (*input != '\0' && *input != ','))
4724                 return -1;
4725
4726         switch (op) {
4727         case '-':
4728                 /* remove the flags from outmode */
4729                 *outmode &= ~perm;
4730                 break;
4731         case '+':
4732                 /* add the flags to outmode */
4733                 *outmode |= perm;
4734                 break;
4735         case '=':
4736                 /* set the flags of outmode to perm */
4737                 if (perm != 0)
4738                         *outmode = perm;
4739                 break;
4740         }
4741
4742         *end = input;
4743         return 0;
4744 }
4745
4746 static int str2mode_t(const char *input, mode_t *outmode)
4747 {
4748         int ret;
4749         const char *iter;
4750
4751         ret = 0;
4752
4753         if (*input >= '0' && *input <= '7') {
4754                 /* parse octal representation */
4755                 char *end;
4756
4757                 iter = input;
4758
4759                 /* look for invalid digits in octal representation */
4760                 while (isdigit(*iter))
4761                         if (*iter++ > '7')
4762                                 return -1;
4763
4764                 errno = 0;
4765                 *outmode = strtoul(input, &end, 8);
4766
4767                 if (errno != 0 || *outmode > 07777) {
4768                         *outmode = 0;
4769                         ret = -1;
4770                 }
4771
4772         } else if (*input == '8' || *input == '9') {
4773                 /* error: invalid octal number */
4774                 ret = -1;
4775         } else {
4776                 /* parse coma seperated list of symbolic representation */
4777                 int rc;
4778                 const char *end;
4779
4780                 *outmode = 0;
4781                 rc = 0;
4782                 end = NULL;
4783
4784                 do {
4785                         rc = parse_symbolic(input, outmode, &end);
4786                         if (rc)
4787                                 return -1;
4788
4789                         input = end+1;
4790                 } while (*end == ',');
4791
4792                 if (*end != '\0')
4793                         ret = -1;
4794         }
4795         return ret;
4796 }
4797
4798 static int lfs_find(int argc, char **argv)
4799 {
4800         int c, rc;
4801         int ret = 0;
4802         time_t t;
4803         struct find_param param = {
4804                 .fp_max_depth = -1,
4805                 .fp_quiet = 1,
4806                 .fp_time_margin = FP_DEFAULT_TIME_MARGIN,
4807         };
4808         struct option long_opts[] = {
4809         { .val = 'A',   .name = "atime",        .has_arg = required_argument },
4810         { .val = 'b',   .name = "blocks",       .has_arg = required_argument },
4811         { .val = 'B',   .name = "btime",        .has_arg = required_argument },
4812         { .val = 'B',   .name = "Btime",        .has_arg = required_argument },
4813         { .val = LFS_COMP_COUNT_OPT,
4814                         .name = "comp-count",   .has_arg = required_argument },
4815         { .val = LFS_COMP_COUNT_OPT,
4816                         .name = "component-count",
4817                                                 .has_arg = required_argument },
4818         { .val = LFS_COMP_FLAGS_OPT,
4819                         .name = "comp-flags",   .has_arg = required_argument },
4820         { .val = LFS_COMP_FLAGS_OPT,
4821                         .name = "component-flags",
4822                                                 .has_arg = required_argument },
4823         { .val = LFS_COMP_START_OPT,
4824                         .name = "comp-start",   .has_arg = required_argument },
4825         { .val = LFS_COMP_START_OPT,
4826                         .name = "component-start",
4827                                                 .has_arg = required_argument },
4828         { .val = LFS_MIRROR_STATE_OPT,
4829                         .name = "mirror-state", .has_arg = required_argument },
4830         { .val = LFS_NEWERXY_OPT,
4831                         .name = "newer",        .has_arg = required_argument},
4832         { .val = LFS_NEWERXY_OPT,
4833                         .name = "neweraa",      .has_arg = required_argument},
4834         { .val = LFS_NEWERXY_OPT,
4835                         .name = "neweram",      .has_arg = required_argument},
4836         { .val = LFS_NEWERXY_OPT,
4837                         .name = "newerac",      .has_arg = required_argument},
4838         { .val = LFS_NEWERXY_OPT,
4839                         .name = "newerab",      .has_arg = required_argument},
4840         { .val = LFS_NEWERXY_OPT,
4841                         .name = "newerma",      .has_arg = required_argument},
4842         { .val = LFS_NEWERXY_OPT,
4843                         .name = "newermm",      .has_arg = required_argument},
4844         { .val = LFS_NEWERXY_OPT,
4845                         .name = "newermc",      .has_arg = required_argument},
4846         { .val = LFS_NEWERXY_OPT,
4847                         .name = "newermb",      .has_arg = required_argument},
4848         { .val = LFS_NEWERXY_OPT,
4849                         .name = "newerca",      .has_arg = required_argument},
4850         { .val = LFS_NEWERXY_OPT,
4851                         .name = "newercm",      .has_arg = required_argument},
4852         { .val = LFS_NEWERXY_OPT,
4853                         .name = "newercc",      .has_arg = required_argument},
4854         { .val = LFS_NEWERXY_OPT,
4855                         .name = "newercb",      .has_arg = required_argument},
4856         { .val = LFS_NEWERXY_OPT,
4857                         .name = "newerba",      .has_arg = required_argument},
4858         { .val = LFS_NEWERXY_OPT,
4859                         .name = "newerbm",      .has_arg = required_argument},
4860         { .val = LFS_NEWERXY_OPT,
4861                         .name = "newerbc",      .has_arg = required_argument},
4862         { .val = LFS_NEWERXY_OPT,
4863                         .name = "newerbb",      .has_arg = required_argument},
4864         { .val = LFS_NEWERXY_OPT,
4865                         .name = "newerBa",      .has_arg = required_argument},
4866         { .val = LFS_NEWERXY_OPT,
4867                         .name = "newerBm",      .has_arg = required_argument},
4868         { .val = LFS_NEWERXY_OPT,
4869                         .name = "newerBc",      .has_arg = required_argument},
4870         { .val = LFS_NEWERXY_OPT,
4871                         .name = "newerBB",      .has_arg = required_argument},
4872         { .val = LFS_NEWERXY_OPT,
4873                         .name = "newerat",      .has_arg = required_argument},
4874         { .val = LFS_NEWERXY_OPT,
4875                         .name = "newermt",      .has_arg = required_argument},
4876         { .val = LFS_NEWERXY_OPT,
4877                         .name = "newerct",      .has_arg = required_argument},
4878         { .val = LFS_NEWERXY_OPT,
4879                         .name = "newerbt",      .has_arg = required_argument},
4880         { .val = LFS_NEWERXY_OPT,
4881                         .name = "newerBt",      .has_arg = required_argument},
4882         { .val = 'c',   .name = "stripe-count", .has_arg = required_argument },
4883         { .val = 'c',   .name = "stripe_count", .has_arg = required_argument },
4884         { .val = 'C',   .name = "ctime",        .has_arg = required_argument },
4885 /* getstripe { .val = 'd', .name = "directory", .has_arg = no_argument }, */
4886         { .val = 'D',   .name = "maxdepth",     .has_arg = required_argument },
4887         { .val = 'E',   .name = "comp-end",     .has_arg = required_argument },
4888         { .val = 'E',   .name = "component-end",
4889                                                 .has_arg = required_argument },
4890 /* find { .val = 'F',   .name = "fid",          .has_arg = no_argument }, */
4891         { .val = LFS_LAYOUT_FOREIGN_OPT,
4892                         .name = "foreign",      .has_arg = optional_argument},
4893         { .val = 'g',   .name = "gid",          .has_arg = required_argument },
4894         { .val = 'G',   .name = "group",        .has_arg = required_argument },
4895         { .val = 'h',   .name = "help",         .has_arg = no_argument },
4896         { .val = 'H',   .name = "mdt-hash",     .has_arg = required_argument },
4897         { .val = 'i',   .name = "stripe-index", .has_arg = required_argument },
4898         { .val = 'i',   .name = "stripe_index", .has_arg = required_argument },
4899 /* getstripe { .val = 'I', .name = "comp-id",   .has_arg = required_argument }*/
4900         { .val = 'l',   .name = "lazy",         .has_arg = no_argument },
4901         { .val = 'L',   .name = "layout",       .has_arg = required_argument },
4902         { .val = 'm',   .name = "mdt",          .has_arg = required_argument },
4903         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument },
4904         { .val = 'm',   .name = "mdt_index",    .has_arg = required_argument },
4905         { .val = 'M',   .name = "mtime",        .has_arg = required_argument },
4906         { .val = 'n',   .name = "name",         .has_arg = required_argument },
4907         { .val = 'N',   .name = "mirror-count", .has_arg = required_argument },
4908 /* find { .val = 'o'    .name = "or", .has_arg = no_argument }, like find(1) */
4909         { .val = 'O',   .name = "obd",          .has_arg = required_argument },
4910         { .val = 'O',   .name = "ost",          .has_arg = required_argument },
4911         { .val = LFS_FIND_PERM,
4912                         .name = "perm",         .has_arg = required_argument },
4913         /* no short option for pool yet, can be 'p' after 2.18 */
4914         { .val = LFS_POOL_OPT,
4915                         .name = "pool",         .has_arg = required_argument },
4916         { .val = '0',   .name = "print0",       .has_arg = no_argument },
4917         { .val = 'P',   .name = "print",        .has_arg = no_argument },
4918         { .val = LFS_PROJID_OPT,
4919                         .name = "projid",       .has_arg = required_argument },
4920 /* getstripe { .val = 'q', .name = "quiet",     .has_arg = no_argument }, */
4921 /* getstripe { .val = 'r', .name = "recursive", .has_arg = no_argument }, */
4922 /* getstripe { .val = 'R', .name = "raw",       .has_arg = no_argument }, */
4923         { .val = 's',   .name = "size",         .has_arg = required_argument },
4924         { .val = 'S',   .name = "stripe-size",  .has_arg = required_argument },
4925         { .val = 'S',   .name = "stripe_size",  .has_arg = required_argument },
4926         { .val = 't',   .name = "type",         .has_arg = required_argument },
4927         { .val = 'T',   .name = "mdt-count",    .has_arg = required_argument },
4928         { .val = 'u',   .name = "uid",          .has_arg = required_argument },
4929         { .val = 'U',   .name = "user",         .has_arg = required_argument },
4930         { .val = 'z',   .name = "extension-size",
4931                                                 .has_arg = required_argument },
4932         { .val = 'z',   .name = "ext-size",     .has_arg = required_argument },
4933 /* getstripe { .val = 'v', .name = "verbose",   .has_arg = no_argument }, */
4934 /* getstripe { .val = 'y', .name = "yaml",      .has_arg = no_argument }, */
4935         { .name = NULL } };
4936         int optidx = 0;
4937         int pathstart = -1;
4938         int pathend = -1;
4939         int pathbad = -1;
4940         int neg_opt = 0;
4941         time_t *xtime;
4942         int *xsign;
4943         int isoption;
4944         char *endptr;
4945
4946         time(&t);
4947
4948         /* when getopt_long_only() hits '!' it returns 1, puts "!" in optarg */
4949         while ((c = getopt_long_only(argc, argv,
4950                 "-0A:b:B:c:C:D:E:g:G:hH:i:L:m:M:n:N:O:Ppqrs:S:t:T:u:U:vz:",
4951                 long_opts, &optidx)) >= 0) {
4952                 xtime = NULL;
4953                 xsign = NULL;
4954                 if (neg_opt)
4955                         --neg_opt;
4956                 /* '!' is part of option */
4957                 /*
4958                  * when getopt_long_only() finds a string which is not
4959                  * an option nor a known option argument it returns 1
4960                  * in that case if we already have found pathstart and pathend
4961                  * (i.e. we have the list of pathnames),
4962                  * the only supported value is "!"
4963                  */
4964                 isoption = (c != 1) || (strcmp(optarg, "!") == 0);
4965                 if (!isoption && pathend != -1) {
4966                         fprintf(stderr,
4967                                 "err: %s: filename|dirname must either precede options or follow options\n",
4968                                 argv[0]);
4969                         ret = CMD_HELP;
4970                         goto err;
4971                 }
4972                 if (!isoption && pathstart == -1)
4973                         pathstart = optind - 1;
4974                 if (isoption && pathstart != -1 && pathend == -1)
4975                         pathend = optind - 2;
4976                 switch (c) {
4977                 case 0:
4978                         /* Long options. */
4979                         break;
4980                 case 1:
4981                         /*
4982                          * unknown; opt is "!" or path component,
4983                          * checking done above.
4984                          */
4985                         if (strcmp(optarg, "!") == 0)
4986                                 neg_opt = 2;
4987                         break;
4988                 case 'A':
4989                         xtime = &param.fp_atime;
4990                         xsign = &param.fp_asign;
4991                         param.fp_exclude_atime = !!neg_opt;
4992                         /* no break, this falls through to 'B' for btime */
4993                 case 'B':
4994                         if (c == 'B') {
4995                                 xtime = &param.fp_btime;
4996                                 xsign = &param.fp_bsign;
4997                                 param.fp_exclude_btime = !!neg_opt;
4998                         }
4999                         /* no break, this falls through to 'C' for ctime */
5000                 case 'C':
5001                         if (c == 'C') {
5002                                 xtime = &param.fp_ctime;
5003                                 xsign = &param.fp_csign;
5004                                 param.fp_exclude_ctime = !!neg_opt;
5005                         }
5006                         /* no break, this falls through to 'M' for mtime */
5007                 case 'M':
5008                         if (c == 'M') {
5009                                 xtime = &param.fp_mtime;
5010                                 xsign = &param.fp_msign;
5011                                 param.fp_exclude_mtime = !!neg_opt;
5012                         }
5013                         rc = set_time(&param, &t, xtime, optarg);
5014                         if (rc == LONG_MAX) {
5015                                 ret = -1;
5016                                 goto err;
5017                         }
5018                         if (rc)
5019                                 *xsign = rc;
5020                         break;
5021                 case 'b':
5022                         if (optarg[0] == '+') {
5023                                 param.fp_blocks_sign = -1;
5024                                 optarg++;
5025                         } else if (optarg[0] == '-') {
5026                                 param.fp_blocks_sign =  1;
5027                                 optarg++;
5028                         }
5029
5030                         param.fp_blocks_units = 1024;
5031                         ret = llapi_parse_size(optarg, &param.fp_blocks,
5032                                                &param.fp_blocks_units, 0);
5033                         if (ret) {
5034                                 fprintf(stderr, "error: bad blocks '%s'\n",
5035                                         optarg);
5036                                 goto err;
5037                         }
5038                         param.fp_check_blocks = 1;
5039                         param.fp_exclude_blocks = !!neg_opt;
5040                         break;
5041                 case LFS_COMP_COUNT_OPT:
5042                         if (optarg[0] == '+') {
5043                                 param.fp_comp_count_sign = -1;
5044                                 optarg++;
5045                         } else if (optarg[0] == '-') {
5046                                 param.fp_comp_count_sign =  1;
5047                                 optarg++;
5048                         }
5049
5050                         errno = 0;
5051                         param.fp_comp_count = strtoul(optarg, &endptr, 0);
5052                         if (errno != 0 || *endptr != '\0' ||
5053                             param.fp_comp_count > UINT32_MAX) {
5054                                 fprintf(stderr,
5055                                         "error: bad component count '%s'\n",
5056                                         optarg);
5057                                 goto err;
5058                         }
5059                         param.fp_check_comp_count = 1;
5060                         param.fp_exclude_comp_count = !!neg_opt;
5061                         break;
5062                 case LFS_COMP_FLAGS_OPT:
5063                         rc = comp_str2flags(optarg, &param.fp_comp_flags,
5064                                             &param.fp_comp_neg_flags);
5065                         if (rc) {
5066                                 fprintf(stderr,
5067                                         "error: bad component flags '%s'\n",
5068                                         optarg);
5069                                 goto err;
5070                         }
5071                         param.fp_check_comp_flags = 1;
5072                         if (neg_opt) {
5073                                 __u32 flags = param.fp_comp_neg_flags;
5074
5075                                 param.fp_comp_neg_flags = param.fp_comp_flags;
5076                                 param.fp_comp_flags = flags;
5077                         }
5078                         break;
5079                 case LFS_COMP_START_OPT:
5080                         if (optarg[0] == '+') {
5081                                 param.fp_comp_start_sign = -1;
5082                                 optarg++;
5083                         } else if (optarg[0] == '-') {
5084                                 param.fp_comp_start_sign =  1;
5085                                 optarg++;
5086                         }
5087
5088                         rc = llapi_parse_size(optarg, &param.fp_comp_start,
5089                                               &param.fp_comp_start_units, 0);
5090                         if (rc) {
5091                                 fprintf(stderr,
5092                                         "error: bad component start '%s'\n",
5093                                         optarg);
5094                                 goto err;
5095                         }
5096                         param.fp_check_comp_start = 1;
5097                         param.fp_exclude_comp_start = !!neg_opt;
5098                         break;
5099                 case LFS_MIRROR_STATE_OPT:
5100                         rc = mirror_str2state(optarg, &param.fp_mirror_state,
5101                                               &param.fp_mirror_neg_state);
5102                         if (rc) {
5103                                 fprintf(stderr,
5104                                         "error: bad mirrored file state '%s'\n",
5105                                         optarg);
5106                                 goto err;
5107                         }
5108                         param.fp_check_mirror_state = 1;
5109                         if (neg_opt) {
5110                                 __u16 state = param.fp_mirror_neg_state;
5111
5112                                 param.fp_mirror_neg_state =
5113                                         param.fp_mirror_state;
5114                                 param.fp_mirror_state = state;
5115                         }
5116                         break;
5117                 case 'c':
5118                         if (optarg[0] == '+') {
5119                                 param.fp_stripe_count_sign = -1;
5120                                 optarg++;
5121                         } else if (optarg[0] == '-') {
5122                                 param.fp_stripe_count_sign =  1;
5123                                 optarg++;
5124                         }
5125
5126                         errno = 0;
5127                         param.fp_stripe_count = strtoul(optarg, &endptr, 0);
5128                         if (errno != 0 || *endptr != '\0' ||
5129                             param.fp_stripe_count > LOV_MAX_STRIPE_COUNT) {
5130                                 fprintf(stderr,
5131                                         "error: bad stripe_count '%s'\n",
5132                                         optarg);
5133                                 ret = -1;
5134                                 goto err;
5135                         }
5136                         param.fp_check_stripe_count = 1;
5137                         param.fp_exclude_stripe_count = !!neg_opt;
5138                         break;
5139                 case 'D':
5140                         errno = 0;
5141                         param.fp_max_depth = strtol(optarg, 0, 0);
5142                         if (errno != 0 || param.fp_max_depth < 0) {
5143                                 fprintf(stderr,
5144                                         "error: bad maxdepth '%s'\n",
5145                                         optarg);
5146                                 ret = -1;
5147                                 goto err;
5148                         }
5149                         break;
5150                 case 'E':
5151                         if (optarg[0] == '+') {
5152                                 param.fp_comp_end_sign = -1;
5153                                 optarg++;
5154                         } else if (optarg[0] == '-') {
5155                                 param.fp_comp_end_sign =  1;
5156                                 optarg++;
5157                         }
5158
5159                         if (arg_is_eof(optarg)) {
5160                                 param.fp_comp_end = LUSTRE_EOF;
5161                                 param.fp_comp_end_units = 1;
5162                                 rc = 0;
5163                         } else {
5164                                 rc = llapi_parse_size(optarg,
5165                                                 &param.fp_comp_end,
5166                                                 &param.fp_comp_end_units, 0);
5167                                 /* assume units of KB if too small */
5168                                 if (param.fp_comp_end < 4096)
5169                                         param.fp_comp_end *= 1024;
5170                         }
5171                         if (rc) {
5172                                 fprintf(stderr,
5173                                         "error: bad component end '%s'\n",
5174                                         optarg);
5175                                 goto err;
5176                         }
5177                         param.fp_check_comp_end = 1;
5178                         param.fp_exclude_comp_end = !!neg_opt;
5179                         break;
5180                 case LFS_LAYOUT_FOREIGN_OPT: {
5181                         /* all types by default */
5182                         uint32_t type = LU_FOREIGN_TYPE_UNKNOWN;
5183
5184                         if (optarg) {
5185                                 /* check pure numeric */
5186                                 type = strtoul(optarg, &endptr, 0);
5187                                 if (*endptr) {
5188                                         /* check name */
5189                                         type = check_foreign_type_name(optarg);
5190                                         if (type == LU_FOREIGN_TYPE_UNKNOWN) {
5191                                                 fprintf(stderr,
5192                                                         "%s %s: unknown foreign type '%s'\n",
5193                                                         progname, argv[0],
5194                                                         optarg);
5195                                                 return CMD_HELP;
5196                                         }
5197                                 } else if (type >= UINT32_MAX) {
5198                                         fprintf(stderr,
5199                                                 "%s %s: invalid foreign type '%s'\n",
5200                                                 progname, argv[0], optarg);
5201                                         return CMD_HELP;
5202                                 }
5203                         }
5204                         param.fp_foreign_type = type;
5205                         param.fp_check_foreign = 1;
5206                         param.fp_exclude_foreign = !!neg_opt;
5207                         break;
5208                 }
5209                 case LFS_NEWERXY_OPT: {
5210                         char x = 'm';
5211                         char y = 'm';
5212                         int xidx;
5213                         int negidx;
5214                         time_t *newery;
5215                         time_t ref = time(NULL);
5216
5217                         /* no need to check bad options, they won't get here */
5218                         if (strlen(long_opts[optidx].name) == 7) {
5219                                 x = long_opts[optidx].name[5];
5220                                 y = long_opts[optidx].name[6];
5221                         }
5222
5223                         if (y == 't') {
5224                                 static const char *const fmts[] = {
5225                                         "%Y-%m-%d %H:%M:%S",
5226                                         "%Y-%m-%d %H:%M",
5227                                         "%Y-%m-%d",
5228                                         "%H:%M:%S", /* sometime today */
5229                                         "%H:%M",
5230                                         "@%s",
5231                                         "%s",
5232                                         NULL };
5233                                 struct tm tm;
5234                                 bool found = false;
5235                                 int i;
5236
5237                                 for (i = 0; fmts[i] != NULL; i++) {
5238                                         char *ptr;
5239
5240                                         /* Init for times relative to today */
5241                                         if (strncmp(fmts[i], "%H", 2) == 0)
5242                                                 localtime_r(&ref, &tm);
5243                                         else
5244                                                 memset(&tm, 0, sizeof(tm));
5245                                         ptr = strptime(optarg, fmts[i], &tm);
5246                                         /* Skip spaces */
5247                                         while (ptr && isspace(*ptr))
5248                                                 ptr++;
5249                                         if (ptr == optarg + strlen(optarg)) {
5250                                                 found = true;
5251                                                 break;
5252                                         }
5253                                 }
5254
5255                                 if (!found) {
5256                                         fprintf(stderr,
5257                                                 "%s: invalid time '%s'\n",
5258                                                 progname, optarg);
5259                                         fprintf(stderr,
5260                                                 "supported formats are:\n  ");
5261                                         for (i = 0; fmts[i] != NULL; i++)
5262                                                 fprintf(stderr, "'%s', ",
5263                                                         fmts[i]);
5264                                         fprintf(stderr, "\n");
5265                                         ret = -EINVAL;
5266                                         goto err;
5267                                 }
5268
5269                                 ref = mktime(&tm);
5270                         } else if (y == 'b' || y == 'B') {
5271                                 lstatx_t stx;
5272
5273                                 rc = llapi_get_lum_file(optarg, NULL, &stx,
5274                                                         NULL, 0);
5275                                 if (rc || !(stx.stx_mask & STATX_BTIME)) {
5276                                         if (!(stx.stx_mask & STATX_BTIME))
5277                                                 ret = -EOPNOTSUPP;
5278                                         else
5279                                                 ret = -errno;
5280                                         fprintf(stderr,
5281                                                 "%s: get btime failed '%s': %s\n",
5282                                                 progname, optarg,
5283                                                 strerror(-ret));
5284                                         goto err;
5285                                 }
5286
5287                                 ref = stx.stx_btime.tv_sec;
5288                         } else {
5289                                 struct stat statbuf;
5290
5291                                 if (stat(optarg, &statbuf) < 0) {
5292                                         fprintf(stderr,
5293                                                 "%s: cannot stat file '%s': %s\n",
5294                                                 progname, optarg,
5295                                                 strerror(errno));
5296                                         ret = -errno;
5297                                         goto err;
5298                                 }
5299
5300                                 switch (y) {
5301                                 case 'a':
5302                                         ref = statbuf.st_atime;
5303                                         break;
5304                                 case 'm':
5305                                         ref = statbuf.st_mtime;
5306                                         break;
5307                                 case 'c':
5308                                         ref = statbuf.st_ctime;
5309                                         break;
5310                                 default:
5311                                         fprintf(stderr,
5312                                                 "%s: invalid Y argument: '%c'\n",
5313                                                 progname, x);
5314                                         ret = -EINVAL;
5315                                         goto err;
5316                                 }
5317                         }
5318
5319                         switch (x) {
5320                         case 'a':
5321                                 xidx = NEWERXY_ATIME;
5322                                 break;
5323                         case 'm':
5324                                 xidx = NEWERXY_MTIME;
5325                                 break;
5326                         case 'c':
5327                                 xidx = NEWERXY_CTIME;
5328                                 break;
5329                         case 'b':
5330                         case 'B':
5331                                 xidx = NEWERXY_BTIME;
5332                                 break;
5333                         default:
5334                                 fprintf(stderr,
5335                                         "%s: invalid X argument: '%c'\n",
5336                                         progname, x);
5337                                 ret = -EINVAL;
5338                                 goto err;
5339                         }
5340
5341                         negidx = !!neg_opt;
5342                         newery = &param.fp_newery[xidx][negidx];
5343
5344                         if (*newery == 0) {
5345                                 *newery = ref;
5346                         } else {
5347                                 if (negidx)
5348                                         *newery = *newery > ref ? ref : *newery;
5349                                 else
5350                                         *newery = *newery > ref ? *newery : ref;
5351                         }
5352                         param.fp_newerxy = 1;
5353                         break;
5354                 }
5355                 case 'g':
5356                 case 'G':
5357                         rc = name2gid(&param.fp_gid, optarg);
5358                         if (rc) {
5359                                 if (str2quotaid(&param.fp_gid, optarg)) {
5360                                         fprintf(stderr,
5361                                                 "Group/GID: %s cannot be found.\n",
5362                                                 optarg);
5363                                         ret = -1;
5364                                         goto err;
5365                                 }
5366                         }
5367                         param.fp_exclude_gid = !!neg_opt;
5368                         param.fp_check_gid = 1;
5369                         break;
5370                 case 'H':
5371                         rc = mdthash_input(optarg, &param.fp_hash_inflags,
5372                                            &param.fp_hash_exflags,
5373                                            &param.fp_hash_type);
5374                         if (rc) {
5375                                 ret = -1;
5376                                 goto err;
5377                         }
5378                         if (param.fp_hash_inflags || param.fp_hash_exflags)
5379                                 param.fp_check_hash_flag = 1;
5380                         param.fp_exclude_hash_type = !!neg_opt;
5381                         break;
5382                 case 'l':
5383                         param.fp_lazy = 1;
5384                         break;
5385                 case 'L':
5386                         ret = name2layout(&param.fp_layout, optarg);
5387                         if (ret)
5388                                 goto err;
5389                         param.fp_exclude_layout = !!neg_opt;
5390                         param.fp_check_layout = 1;
5391                         break;
5392                 case 'u':
5393                 case 'U':
5394                         rc = name2uid(&param.fp_uid, optarg);
5395                         if (rc) {
5396                                 if (str2quotaid(&param.fp_uid, optarg)) {
5397                                         fprintf(stderr,
5398                                                 "User/UID: %s cannot be found.\n",
5399                                                 optarg);
5400                                         ret = -1;
5401                                         goto err;
5402                                 }
5403                         }
5404                         param.fp_exclude_uid = !!neg_opt;
5405                         param.fp_check_uid = 1;
5406                         break;
5407                 case 'n':
5408                         param.fp_pattern = (char *)optarg;
5409                         param.fp_exclude_pattern = !!neg_opt;
5410                         break;
5411                 case 'N':
5412                         if (optarg[0] == '+') {
5413                                 param.fp_mirror_count_sign = -1;
5414                                 optarg++;
5415                         } else if (optarg[0] == '-') {
5416                                 param.fp_mirror_count_sign =  1;
5417                                 optarg++;
5418                         }
5419
5420                         errno = 0;
5421                         param.fp_mirror_count = strtoul(optarg, &endptr, 0);
5422                         if (errno != 0 || *endptr != '\0' ||
5423                             param.fp_mirror_count > LUSTRE_MIRROR_COUNT_MAX) {
5424                                 fprintf(stderr,
5425                                         "error: bad mirror count '%s'\n",
5426                                         optarg);
5427                                 goto err;
5428                         }
5429                         param.fp_check_mirror_count = 1;
5430                         param.fp_exclude_mirror_count = !!neg_opt;
5431                         break;
5432                 case 'm':
5433                 case 'i':
5434                 case 'O': {
5435                         char *buf, *token, *next, *p;
5436                         int len = 1;
5437                         void *tmp;
5438
5439                         buf = strdup(optarg);
5440                         if (!buf) {
5441                                 ret = -ENOMEM;
5442                                 goto err;
5443                         }
5444
5445                         param.fp_exclude_obd = !!neg_opt;
5446
5447                         token = buf;
5448                         while (token && *token) {
5449                                 token = strchr(token, ',');
5450                                 if (token) {
5451                                         len++;
5452                                         token++;
5453                                 }
5454                         }
5455                         if (c == 'm') {
5456                                 param.fp_exclude_mdt = !!neg_opt;
5457                                 param.fp_num_alloc_mdts += len;
5458                                 tmp = realloc(param.fp_mdt_uuid,
5459                                               param.fp_num_alloc_mdts *
5460                                               sizeof(*param.fp_mdt_uuid));
5461                                 if (!tmp) {
5462                                         ret = -ENOMEM;
5463                                         goto err_free;
5464                                 }
5465
5466                                 param.fp_mdt_uuid = tmp;
5467                         } else {
5468                                 param.fp_exclude_obd = !!neg_opt;
5469                                 param.fp_num_alloc_obds += len;
5470                                 tmp = realloc(param.fp_obd_uuid,
5471                                               param.fp_num_alloc_obds *
5472                                               sizeof(*param.fp_obd_uuid));
5473                                 if (!tmp) {
5474                                         ret = -ENOMEM;
5475                                         goto err_free;
5476                                 }
5477
5478                                 param.fp_obd_uuid = tmp;
5479                         }
5480                         for (token = buf; token && *token; token = next) {
5481                                 struct obd_uuid *puuid;
5482
5483                                 if (c == 'm') {
5484                                         puuid =
5485                                         &param.fp_mdt_uuid[param.fp_num_mdts++];
5486                                 } else {
5487                                         puuid =
5488                                         &param.fp_obd_uuid[param.fp_num_obds++];
5489                                 }
5490                                 p = strchr(token, ',');
5491                                 next = 0;
5492                                 if (p) {
5493                                         *p = 0;
5494                                         next = p+1;
5495                                 }
5496
5497                                 if (strlen(token) > sizeof(puuid->uuid) - 1) {
5498                                         ret = -E2BIG;
5499                                         goto err_free;
5500                                 }
5501
5502                                 strncpy(puuid->uuid, token,
5503                                         sizeof(puuid->uuid));
5504                         }
5505 err_free:
5506                         if (buf)
5507                                 free(buf);
5508                         break;
5509                 }
5510 #if LUSTRE_VERSION_CODE >= OBD_OCD_VERSION(2, 18, 53, 0)
5511                 case 'p':
5512 #endif
5513                 case LFS_POOL_OPT:
5514                         if (strlen(optarg) > LOV_MAXPOOLNAME) {
5515                                 fprintf(stderr,
5516                                         "Pool name %s is too long (max %d)\n",
5517                                         optarg, LOV_MAXPOOLNAME);
5518                                 ret = -1;
5519                                 goto err;
5520                         }
5521                         /*
5522                          * We do check for empty pool because empty pool
5523                          * is used to find V1 LOV attributes
5524                          */
5525                         strncpy(param.fp_poolname, optarg, LOV_MAXPOOLNAME);
5526                         param.fp_poolname[LOV_MAXPOOLNAME] = '\0';
5527                         param.fp_exclude_pool = !!neg_opt;
5528                         param.fp_check_pool = 1;
5529                         break;
5530 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 14, 53, 0)
5531                 case 'p': /* want this for --pool, to match getstripe/find */
5532                         fprintf(stderr,
5533                                 "warning: -p deprecated, use --print0 or -0\n");
5534 #endif
5535                 case '0':
5536                         param.fp_zero_end = 1;
5537                         break;
5538                 case 'P': /* we always print, this option is a no-op */
5539                         break;
5540                 case LFS_PROJID_OPT:
5541                         rc = name2projid(&param.fp_projid, optarg);
5542                         if (rc) {
5543                                 if (str2quotaid(&param.fp_projid, optarg)) {
5544                                         fprintf(stderr,
5545                                                 "Invalid project ID: %s\n",
5546                                                 optarg);
5547                                         ret = -1;
5548                                         goto err;
5549                                 }
5550                         }
5551                         param.fp_exclude_projid = !!neg_opt;
5552                         param.fp_check_projid = 1;
5553                         break;
5554                 case 's':
5555                         if (optarg[0] == '+') {
5556                                 param.fp_size_sign = -1;
5557                                 optarg++;
5558                         } else if (optarg[0] == '-') {
5559                                 param.fp_size_sign =  1;
5560                                 optarg++;
5561                         }
5562
5563                         ret = llapi_parse_size(optarg, &param.fp_size,
5564                                                &param.fp_size_units, 0);
5565                         if (ret) {
5566                                 fprintf(stderr, "error: bad file size '%s'\n",
5567                                         optarg);
5568                                 goto err;
5569                         }
5570                         param.fp_check_size = 1;
5571                         param.fp_exclude_size = !!neg_opt;
5572                         break;
5573                 case 'S':
5574                         if (optarg[0] == '+') {
5575                                 param.fp_stripe_size_sign = -1;
5576                                 optarg++;
5577                         } else if (optarg[0] == '-') {
5578                                 param.fp_stripe_size_sign =  1;
5579                                 optarg++;
5580                         }
5581
5582                         ret = llapi_parse_size(optarg, &param.fp_stripe_size,
5583                                                &param.fp_stripe_size_units, 0);
5584                         /* assume units of KB if too small to be valid */
5585                         if (param.fp_stripe_size < 4096)
5586                                 param.fp_stripe_size *= 1024;
5587                         if (ret) {
5588                                 fprintf(stderr, "error: bad stripe_size '%s'\n",
5589                                         optarg);
5590                                 goto err;
5591                         }
5592                         param.fp_check_stripe_size = 1;
5593                         param.fp_exclude_stripe_size = !!neg_opt;
5594                         break;
5595                 case 't':
5596                         param.fp_exclude_type = !!neg_opt;
5597                         switch (optarg[0]) {
5598                         case 'b':
5599                                 param.fp_type = S_IFBLK;
5600                                 break;
5601                         case 'c':
5602                                 param.fp_type = S_IFCHR;
5603                                 break;
5604                         case 'd':
5605                                 param.fp_type = S_IFDIR;
5606                                 break;
5607                         case 'f':
5608                                 param.fp_type = S_IFREG;
5609                                 break;
5610                         case 'l':
5611                                 param.fp_type = S_IFLNK;
5612                                 break;
5613                         case 'p':
5614                                 param.fp_type = S_IFIFO;
5615                                 break;
5616                         case 's':
5617                                 param.fp_type = S_IFSOCK;
5618                                 break;
5619                         default:
5620                                 fprintf(stderr, "%s: bad type '%s'\n",
5621                                         progname, optarg);
5622                                 ret = CMD_HELP;
5623                                 goto err;
5624                         }
5625                         break;
5626                 case LFS_FIND_PERM:
5627                         param.fp_exclude_perm = !!neg_opt;
5628                         param.fp_perm_sign = LFS_FIND_PERM_EXACT;
5629                         if (*optarg == '/') {
5630                                 param.fp_perm_sign = LFS_FIND_PERM_ANY;
5631                                 optarg++;
5632                         } else if (*optarg == '-') {
5633                                 param.fp_perm_sign = LFS_FIND_PERM_ALL;
5634                                 optarg++;
5635                         }
5636
5637                         if (str2mode_t(optarg, &param.fp_perm)) {
5638                                 fprintf(stderr, "error: invalid mode '%s'\n",
5639                                         optarg);
5640                                 ret = -1;
5641                                 goto err;
5642                         }
5643                         break;
5644                 case 'T':
5645                         if (optarg[0] == '+') {
5646                                 param.fp_mdt_count_sign = -1;
5647                                 optarg++;
5648                         } else if (optarg[0] == '-') {
5649                                 param.fp_mdt_count_sign =  1;
5650                                 optarg++;
5651                         }
5652
5653                         errno = 0;
5654                         param.fp_mdt_count = strtoul(optarg, &endptr, 0);
5655                         if (errno != 0 || *endptr != '\0' ||
5656                             param.fp_mdt_count >= UINT32_MAX) {
5657                                 fprintf(stderr, "error: bad mdt_count '%s'\n",
5658                                         optarg);
5659                                 ret = -1;
5660                                 goto err;
5661                         }
5662                         param.fp_check_mdt_count = 1;
5663                         param.fp_exclude_mdt_count = !!neg_opt;
5664                         break;
5665                 case 'z':
5666                         if (optarg[0] == '+') {
5667                                 param.fp_ext_size_sign = -1;
5668                                 optarg++;
5669                         } else if (optarg[0] == '-') {
5670                                 param.fp_ext_size_sign =  1;
5671                                 optarg++;
5672                         }
5673
5674                         ret = llapi_parse_size(optarg, &param.fp_ext_size,
5675                                                &param.fp_ext_size_units, 0);
5676                         if (ret) {
5677                                 fprintf(stderr, "error: bad ext-size '%s'\n",
5678                                         optarg);
5679                                 goto err;
5680                         }
5681                         param.fp_ext_size /= SEL_UNIT_SIZE;
5682                         param.fp_ext_size_units /= SEL_UNIT_SIZE;
5683                         param.fp_check_ext_size = 1;
5684                         param.fp_exclude_ext_size = !!neg_opt;
5685                         break;
5686                 default:
5687                         fprintf(stderr, "%s: unrecognized option '%s'\n",
5688                                 progname, argv[optind - 1]);
5689                 case 'h':
5690                         ret = CMD_HELP;
5691                         goto err;
5692                 }
5693         }
5694
5695         if (pathstart == -1) {
5696                 fprintf(stderr, "error: %s: no filename|pathname\n",
5697                         argv[0]);
5698                 ret = CMD_HELP;
5699                 goto err;
5700         } else if (pathend == -1) {
5701                 /* no options */
5702                 pathend = argc;
5703         }
5704
5705         do {
5706                 rc = llapi_find(argv[pathstart], &param);
5707                 if (rc && !ret) {
5708                         ret = rc;
5709                         pathbad = pathstart;
5710                 }
5711         } while (++pathstart < pathend);
5712
5713         if (ret)
5714                 fprintf(stderr, "%s: failed for '%s': %s\n",
5715                         progname, argv[pathbad], strerror(-rc));
5716
5717 err:
5718         if (param.fp_obd_uuid && param.fp_num_alloc_obds)
5719                 free(param.fp_obd_uuid);
5720
5721         if (param.fp_mdt_uuid && param.fp_num_alloc_mdts)
5722                 free(param.fp_mdt_uuid);
5723
5724         return ret;
5725 }
5726
5727 static int lfs_getstripe_internal(int argc, char **argv,
5728                                   struct find_param *param)
5729 {
5730         struct option long_opts[] = {
5731 /* find { .val = 'A',   .name = "atime",        .has_arg = required_argument }*/
5732 /* find { .val = 'b',   .name = "blocks",       .has_arg = required_argument }*/
5733 /* find { .val = 'B',   .name = "btime",        .has_arg = required_argument }*/
5734 /* find { .val = 'B',   .name = "Btime",        .has_arg = required_argument }*/
5735         { .val = LFS_COMP_COUNT_OPT,
5736                         .name = "comp-count",   .has_arg = no_argument },
5737         { .val = LFS_COMP_COUNT_OPT,
5738                 .name = "component-count",      .has_arg = no_argument },
5739         { .val = LFS_COMP_FLAGS_OPT,
5740                         .name = "comp-flags",   .has_arg = optional_argument },
5741         { .val = LFS_COMP_FLAGS_OPT,
5742                 .name = "component-flags",      .has_arg = optional_argument },
5743         { .val = LFS_COMP_START_OPT,
5744                         .name = "comp-start",   .has_arg = optional_argument },
5745         { .val = LFS_COMP_START_OPT,
5746                 .name = "component-start",      .has_arg = optional_argument },
5747         { .val = LFS_MIRROR_INDEX_OPT,
5748                 .name = "mirror-index",         .has_arg = required_argument },
5749         { .val = LFS_MIRROR_ID_OPT,
5750                 .name = "mirror-id",            .has_arg = required_argument },
5751         { .val = 'c',   .name = "stripe-count", .has_arg = no_argument },
5752         { .val = 'c',   .name = "stripe_count", .has_arg = no_argument },
5753 /* find { .val = 'C',   .name = "ctime",        .has_arg = required_argument }*/
5754         { .val = 'd',   .name = "directory",    .has_arg = no_argument },
5755         { .val = 'D',   .name = "default",      .has_arg = no_argument },
5756         { .val = 'E',   .name = "comp-end",     .has_arg = optional_argument },
5757         { .val = 'E',   .name = "component-end", .has_arg = optional_argument },
5758         { .val = 'F',   .name = "fid",          .has_arg = no_argument },
5759         { .val = 'g',   .name = "generation",   .has_arg = no_argument },
5760 /* find { .val = 'G',   .name = "group",        .has_arg = required_argument }*/
5761         { .val = 'h',   .name = "help",         .has_arg = no_argument },
5762 /* dirstripe { .val = 'H', .name = "mdt-hash",  .has_arg = required_argument }*/
5763         { .val = 'i',   .name = "stripe-index", .has_arg = no_argument },
5764         { .val = 'i',   .name = "stripe_index", .has_arg = no_argument },
5765         { .val = 'I',   .name = "comp-id",      .has_arg = optional_argument },
5766         { .val = 'I',   .name = "component-id", .has_arg = optional_argument },
5767 /* find { .val = 'l',   .name = "lazy",         .has_arg = no_argument }, */
5768         { .val = 'L',   .name = "layout",       .has_arg = no_argument },
5769         { .val = 'm',   .name = "mdt",          .has_arg = no_argument },
5770         { .val = 'm',   .name = "mdt-index",    .has_arg = no_argument },
5771         { .val = 'm',   .name = "mdt_index",    .has_arg = no_argument },
5772 /* find { .val = 'M',   .name = "mtime",        .has_arg = required_argument }*/
5773 /* find { .val = 'n',   .name = "name",         .has_arg = required_argument }*/
5774         { .val = 'N',   .name = "mirror-count", .has_arg = no_argument },
5775         { .val = 'O',   .name = "obd",          .has_arg = required_argument },
5776         { .val = 'O',   .name = "ost",          .has_arg = required_argument },
5777         { .val = 'p',   .name = "pool",         .has_arg = no_argument },
5778 /* find { .val = 'P',   .name = "print",        .has_arg = no_argument }, */
5779         { .val = 'q',   .name = "quiet",        .has_arg = no_argument },
5780         { .val = 'r',   .name = "recursive",    .has_arg = no_argument },
5781         { .val = 'R',   .name = "raw",          .has_arg = no_argument },
5782         { .val = 'S',   .name = "stripe-size",  .has_arg = no_argument },
5783         { .val = 'S',   .name = "stripe_size",  .has_arg = no_argument },
5784 /* find { .val = 't',   .name = "type",         .has_arg = required_argument }*/
5785 /* dirstripe { .val = 'T', .name = "mdt-count", .has_arg = required_argument }*/
5786 /* find { .val = 'u',   .name = "uid",          .has_arg = required_argument }*/
5787 /* find { .val = 'U',   .name = "user",         .has_arg = required_argument }*/
5788         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
5789 /* dirstripe { .val = 'X',.name = "max-inherit",.has_arg = required_argument }*/
5790         { .val = 'y',   .name = "yaml",         .has_arg = no_argument },
5791         { .val = 'z',   .name = "extension-size", .has_arg = no_argument },
5792         { .val = 'z',   .name = "ext-size",     .has_arg = no_argument },
5793         { .name = NULL } };
5794         int c, rc;
5795         int neg_opt = 0;
5796         int pathstart = -1, pathend = -1;
5797         int isoption;
5798         char *end, *tmp;
5799
5800         while ((c = getopt_long(argc, argv,
5801                         "-cdDE::FghiI::LmMNoO:pqrRsSvyz",
5802                         long_opts, NULL)) != -1) {
5803                 if (neg_opt)
5804                         --neg_opt;
5805
5806                 /* '!' is part of option */
5807                 isoption = (c != 1) || (strcmp(optarg, "!") == 0);
5808                 if (!isoption && pathend != -1) {
5809                         fprintf(stderr,
5810                                 "error: %s: filename|dirname must either precede options or follow options\n",
5811                                 argv[0]);
5812                         return CMD_HELP;
5813                 }
5814                 if (!isoption && pathstart == -1)
5815                         pathstart = optind - 1;
5816                 if (isoption && pathstart != -1 && pathend == -1)
5817                         pathend = optind - 2;
5818
5819                 switch (c) {
5820                 case 1:
5821                         /* unknown: opt is "!" */
5822                         if (strcmp(optarg, "!") == 0)
5823                                 neg_opt = 2;
5824                         break;
5825                 case 'c':
5826                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
5827                                 param->fp_verbose |= VERBOSE_COUNT;
5828                                 param->fp_max_depth = 0;
5829                         }
5830                         break;
5831                 case LFS_COMP_COUNT_OPT:
5832                         param->fp_verbose |= VERBOSE_COMP_COUNT;
5833                         param->fp_max_depth = 0;
5834                         break;
5835                 case LFS_COMP_FLAGS_OPT:
5836                         if (optarg) {
5837                                 rc = comp_str2flags(optarg,
5838                                                     &param->fp_comp_flags,
5839                                                     &param->fp_comp_neg_flags);
5840                                 if (rc != 0) {
5841                                         fprintf(stderr,
5842                                                 "error: %s bad component flags '%s'.\n",
5843                                                 argv[0], optarg);
5844                                         return CMD_HELP;
5845                                 }
5846                                 param->fp_check_comp_flags = 1;
5847                         } else {
5848                                 param->fp_verbose |= VERBOSE_COMP_FLAGS;
5849                                 param->fp_max_depth = 0;
5850                         }
5851                         break;
5852                 case LFS_COMP_START_OPT:
5853                         if (optarg) {
5854                                 tmp = optarg;
5855                                 if (tmp[0] == '+') {
5856                                         param->fp_comp_start_sign = -1;
5857                                         tmp++;
5858                                 } else if (tmp[0] == '-') {
5859                                         param->fp_comp_start_sign = 1;
5860                                         tmp++;
5861                                 }
5862                                 rc = llapi_parse_size(tmp,
5863                                                 &param->fp_comp_start,
5864                                                 &param->fp_comp_start_units, 0);
5865                                 if (rc != 0) {
5866                                         fprintf(stderr,
5867                                                 "error: %s bad component start '%s'.\n",
5868                                                 argv[0], tmp);
5869                                         return CMD_HELP;
5870                                 }
5871                                 param->fp_check_comp_start = 1;
5872                         } else {
5873                                 param->fp_verbose |= VERBOSE_COMP_START;
5874                                 param->fp_max_depth = 0;
5875                         }
5876                         break;
5877                 case LFS_MIRROR_INDEX_OPT: {
5878                         unsigned long int mirror_index;
5879
5880                         if (optarg[0] == '+') {
5881                                 param->fp_mirror_index_sign = -1;
5882                                 optarg++;
5883                         } else if (optarg[0] == '-') {
5884                                 param->fp_mirror_index_sign = 1;
5885                                 optarg++;
5886                         }
5887
5888                         errno = 0;
5889                         mirror_index = strtoul(optarg, &end, 0);
5890                         if (errno != 0 || *end != '\0' ||
5891                             mirror_index > UINT16_MAX || (mirror_index == 0 &&
5892                             param->fp_mirror_index_sign == 0 && neg_opt == 0)) {
5893                                 fprintf(stderr,
5894                                         "%s %s: invalid mirror index '%s'\n",
5895                                         progname, argv[0], optarg);
5896                                 return CMD_HELP;
5897                         }
5898
5899                         param->fp_mirror_index = (__u16)mirror_index;
5900
5901                         if (param->fp_mirror_id != 0) {
5902                                 fprintf(stderr,
5903                                         "%s %s: can't specify both mirror index and mirror ID\n",
5904                                         progname, argv[0]);
5905                                 return CMD_HELP;
5906                         }
5907                         param->fp_check_mirror_index = 1;
5908                         param->fp_exclude_mirror_index = !!neg_opt;
5909                         break;
5910                 }
5911                 case LFS_MIRROR_ID_OPT: {
5912                         unsigned long int mirror_id;
5913
5914                         if (optarg[0] == '+') {
5915                                 param->fp_mirror_id_sign = -1;
5916                                 optarg++;
5917                         } else if (optarg[0] == '-') {
5918                                 param->fp_mirror_id_sign = 1;
5919                                 optarg++;
5920                         }
5921
5922                         errno = 0;
5923                         mirror_id = strtoul(optarg, &end, 0);
5924                         if (errno != 0 || *end != '\0' ||
5925                             mirror_id > UINT16_MAX || (mirror_id == 0 &&
5926                             param->fp_mirror_id_sign == 0 && neg_opt == 0)) {
5927                                 fprintf(stderr,
5928                                         "%s %s: invalid mirror ID '%s'\n",
5929                                         progname, argv[0], optarg);
5930                                 return CMD_HELP;
5931                         }
5932
5933                         param->fp_mirror_id = (__u16)mirror_id;
5934
5935                         if (param->fp_mirror_index != 0) {
5936                                 fprintf(stderr,
5937                                         "%s %s: can't specify both mirror index and mirror ID\n",
5938                                         progname, argv[0]);
5939                                 return CMD_HELP;
5940                         }
5941                         param->fp_check_mirror_id = 1;
5942                         param->fp_exclude_mirror_id = !!neg_opt;
5943                         break;
5944                 }
5945                 case 'd':
5946                         param->fp_max_depth = 0;
5947                         break;
5948                 case 'D':
5949                         param->fp_get_default_lmv = 1;
5950                         break;
5951                 case 'E':
5952                         if (optarg) {
5953                                 tmp = optarg;
5954                                 if (tmp[0] == '+') {
5955                                         param->fp_comp_end_sign = -1;
5956                                         tmp++;
5957                                 } else if (tmp[0] == '-') {
5958                                         param->fp_comp_end_sign = 1;
5959                                         tmp++;
5960                                 }
5961
5962                                 if (arg_is_eof(tmp)) {
5963                                         param->fp_comp_end = LUSTRE_EOF;
5964                                         param->fp_comp_end_units = 1;
5965                                         rc = 0;
5966                                 } else {
5967                                         rc = llapi_parse_size(tmp,
5968                                                 &param->fp_comp_end,
5969                                                 &param->fp_comp_end_units, 0);
5970                                         /* assume units of KB if too small */
5971                                         if (param->fp_comp_end < 4096)
5972                                                 param->fp_comp_end *= 1024;
5973                                 }
5974                                 if (rc != 0) {
5975                                         fprintf(stderr,
5976                                                 "error: %s bad component end '%s'.\n",
5977                                                 argv[0], tmp);
5978                                         return CMD_HELP;
5979                                 }
5980                                 param->fp_check_comp_end = 1;
5981                         } else {
5982                                 param->fp_verbose |= VERBOSE_COMP_END;
5983                                 param->fp_max_depth = 0;
5984                         }
5985                         break;
5986                 case 'F':
5987                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
5988                                 param->fp_verbose |= VERBOSE_DFID;
5989                                 param->fp_max_depth = 0;
5990                         }
5991                         break;
5992                 case 'g':
5993                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
5994                                 param->fp_verbose |= VERBOSE_GENERATION;
5995                                 param->fp_max_depth = 0;
5996                         }
5997                         break;
5998                 case 'i':
5999                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6000                                 param->fp_verbose |= VERBOSE_STRIPE_OFFSET;
6001                                 param->fp_max_depth = 0;
6002                         }
6003                         break;
6004                 case 'I':
6005                         if (optarg) {
6006                                 param->fp_comp_id = strtoul(optarg, &end, 0);
6007                                 if (*end != '\0' || param->fp_comp_id == 0 ||
6008                                     param->fp_comp_id > LCME_ID_MAX) {
6009                                         fprintf(stderr,
6010                                                 "error: %s bad component id '%s'\n",
6011                                                 argv[0], optarg);
6012                                         return CMD_HELP;
6013                                 }
6014                                 param->fp_check_comp_id = 1;
6015                         } else {
6016                                 param->fp_max_depth = 0;
6017                                 param->fp_verbose |= VERBOSE_COMP_ID;
6018                         }
6019                         break;
6020                 case 'L':
6021                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6022                                 param->fp_verbose |= VERBOSE_PATTERN;
6023                                 param->fp_max_depth = 0;
6024                         }
6025                         break;
6026 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
6027                 case 'M':
6028                         fprintf(stderr,
6029                                 "warning: '-M' deprecated, use '--mdt-index' or '-m' instead\n");
6030 #endif
6031                 case 'm':
6032                         if (!(param->fp_verbose & VERBOSE_DETAIL))
6033                                 param->fp_max_depth = 0;
6034                         param->fp_verbose |= VERBOSE_MDTINDEX;
6035                         break;
6036                 case 'N':
6037                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6038                                 param->fp_verbose |= VERBOSE_MIRROR_COUNT;
6039                                 param->fp_max_depth = 0;
6040                         }
6041                         break;
6042                 case 'O':
6043                         if (param->fp_obd_uuid) {
6044                                 fprintf(stderr,
6045                                         "error: %s: only one obduuid allowed",
6046                                         argv[0]);
6047                                 return CMD_HELP;
6048                         }
6049                         param->fp_obd_uuid = (struct obd_uuid *)optarg;
6050                         break;
6051                 case 'p':
6052                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6053                                 param->fp_verbose |= VERBOSE_POOL;
6054                                 param->fp_max_depth = 0;
6055                         }
6056                         break;
6057                 case 'q':
6058                         param->fp_quiet++;
6059                         break;
6060                 case 'r':
6061                         param->fp_recursive = 1;
6062                         break;
6063                 case 'R':
6064                         param->fp_raw = 1;
6065                         break;
6066                 case 'S':
6067                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6068                                 param->fp_verbose |= VERBOSE_STRIPE_SIZE;
6069                                 param->fp_max_depth = 0;
6070                         }
6071                         break;
6072                 case 'v':
6073                         param->fp_verbose = VERBOSE_DEFAULT | VERBOSE_DETAIL;
6074                         break;
6075                 case 'y':
6076                         param->fp_yaml = 1;
6077                         break;
6078                 case 'z':
6079                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6080                                 param->fp_verbose |= VERBOSE_EXT_SIZE;
6081                                 param->fp_max_depth = 0;
6082                         }
6083                         break;
6084                 default:
6085                         fprintf(stderr, "%s: unrecognized option '%s'\n",
6086                                 progname, argv[optind - 1]);
6087                 case 'h':
6088                         return CMD_HELP;
6089                 }
6090         }
6091
6092         if (pathstart == -1) {
6093                 fprintf(stderr, "error: %s: no filename|pathname\n",
6094                                 argv[0]);
6095                 return CMD_HELP;
6096         } else if (pathend == -1) {
6097                 /* no options */
6098                 pathend = argc;
6099         }
6100
6101         if (pathend > argc)
6102                 return CMD_HELP;
6103
6104         if (param->fp_recursive)
6105                 param->fp_max_depth = -1;
6106         else if (param->fp_verbose & VERBOSE_DETAIL)
6107                 param->fp_max_depth = 1;
6108
6109         if (!param->fp_verbose)
6110                 param->fp_verbose = VERBOSE_DEFAULT;
6111         if (param->fp_quiet)
6112                 param->fp_verbose = VERBOSE_OBJID;
6113
6114         do {
6115                 rc = llapi_getstripe(argv[pathstart], param);
6116         } while (++pathstart < pathend && !rc);
6117
6118         if (rc)
6119                 fprintf(stderr, "error: %s failed for %s.\n",
6120                         argv[0], argv[optind - 1]);
6121         return rc;
6122 }
6123
6124 static int lfs_tgts(int argc, char **argv)
6125 {
6126         char mntdir[PATH_MAX] = {'\0'}, path[PATH_MAX] = {'\0'};
6127         struct find_param param;
6128         int index = 0, rc = 0;
6129
6130         if (argc > 2)
6131                 return CMD_HELP;
6132
6133         if (argc == 2 && !realpath(argv[1], path)) {
6134                 rc = -errno;
6135                 fprintf(stderr, "error: invalid path '%s': %s\n",
6136                         argv[1], strerror(-rc));
6137                 return rc;
6138         }
6139
6140         while (!llapi_search_mounts(path, index++, mntdir, NULL)) {
6141                 /* Check if we have a mount point */
6142                 if (mntdir[0] == '\0')
6143                         continue;
6144
6145                 memset(&param, 0, sizeof(param));
6146                 if (!strcmp(argv[0], "mdts"))
6147                         param.fp_get_lmv = 1;
6148
6149                 rc = llapi_ostlist(mntdir, &param);
6150                 if (rc) {
6151                         fprintf(stderr, "error: %s: failed on %s\n",
6152                                 argv[0], mntdir);
6153                 }
6154                 if (path[0] != '\0')
6155                         break;
6156                 memset(mntdir, 0, PATH_MAX);
6157         }
6158
6159         return rc;
6160 }
6161
6162 static int lfs_getstripe(int argc, char **argv)
6163 {
6164         struct find_param param = { 0 };
6165
6166         param.fp_max_depth = 1;
6167         return lfs_getstripe_internal(argc, argv, &param);
6168 }
6169
6170 /* functions */
6171 static int lfs_getdirstripe(int argc, char **argv)
6172 {
6173         struct find_param param = { 0 };
6174         struct option long_opts[] = {
6175         { .val = 'c',   .name = "mdt-count",     .has_arg = no_argument },
6176         { .val = 'D',   .name = "default",       .has_arg = no_argument },
6177         { .val = 'h',   .name = "help",         .has_arg = no_argument },
6178         { .val = 'H',   .name = "mdt-hash",      .has_arg = no_argument },
6179         { .val = 'i',   .name = "mdt-index",     .has_arg = no_argument },
6180         { .val = 'm',   .name = "mdt-index",     .has_arg = no_argument },
6181         { .val = 'O',   .name = "obd",           .has_arg = required_argument },
6182         { .val = 'r',   .name = "recursive",     .has_arg = no_argument },
6183         { .val = 'T',   .name = "mdt-count",     .has_arg = no_argument },
6184         { .val = 'v',   .name = "verbose",       .has_arg = no_argument },
6185         { .val = 'X',   .name = "max-inherit",   .has_arg = no_argument },
6186         { .val = 'y',   .name = "yaml",          .has_arg = no_argument },
6187         { .val = LFS_INHERIT_RR_OPT,
6188                         .name = "max-inherit-rr", .has_arg = no_argument },
6189         { .name = NULL } };
6190         int c, rc;
6191
6192         param.fp_get_lmv = 1;
6193
6194         while ((c = getopt_long(argc, argv,
6195                                 "cDhHimO:rtTvXy", long_opts, NULL)) != -1) {
6196                 switch (c) {
6197                 case 'c':
6198                 case 'T':
6199                         param.fp_verbose |= VERBOSE_COUNT;
6200                         break;
6201                 case 'D':
6202                         param.fp_get_default_lmv = 1;
6203                         break;
6204 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
6205                 case 't':
6206                         fprintf(stderr,
6207                                 "warning: '-t' deprecated, use '--mdt-hash' or '-H' instead\n");
6208                         /* fallthrough */
6209 #endif
6210                 case 'H':
6211                         param.fp_verbose |= VERBOSE_HASH_TYPE;
6212                         break;
6213                 case 'i': /* fallthrough */
6214                 case 'm':
6215                         param.fp_verbose |= VERBOSE_STRIPE_OFFSET;
6216                         break;
6217                 case 'O':
6218                         if (param.fp_obd_uuid) {
6219                                 fprintf(stderr,
6220                                         "%s: only one obduuid allowed",
6221                                         progname);
6222                                 return CMD_HELP;
6223                         }
6224                         param.fp_obd_uuid = (struct obd_uuid *)optarg;
6225                         break;
6226                 case 'r':
6227                         param.fp_recursive = 1;
6228                         break;
6229                 case 'v':
6230                         param.fp_verbose |= VERBOSE_DETAIL;
6231                         break;
6232                 case 'X':
6233                         param.fp_verbose |= VERBOSE_INHERIT;
6234                         break;
6235                 case LFS_INHERIT_RR_OPT:
6236                         param.fp_verbose |= VERBOSE_INHERIT_RR;
6237                         break;
6238                 case 'y':
6239                         param.fp_yaml = 1;
6240                         break;
6241                 default:
6242                         fprintf(stderr, "%s: unrecognized option '%s'\n",
6243                                 progname, argv[optind - 1]);
6244                         /* fallthrough */
6245                 case 'h':
6246                         return CMD_HELP;
6247                 }
6248         }
6249
6250         if (optind >= argc)
6251                 return CMD_HELP;
6252
6253         if (param.fp_recursive)
6254                 param.fp_max_depth = -1;
6255
6256         if (!param.fp_verbose)
6257                 param.fp_verbose = VERBOSE_DEFAULT;
6258
6259         do {
6260                 rc = llapi_getstripe(argv[optind], &param);
6261         } while (++optind < argc && !rc);
6262
6263         if (rc)
6264                 fprintf(stderr, "error: %s failed for %s.\n",
6265                         argv[0], argv[optind - 1]);
6266         return rc;
6267 }
6268
6269 enum mntdf_flags {
6270         MNTDF_INODES    = 0x0001,
6271         MNTDF_COOKED    = 0x0002,
6272         MNTDF_LAZY      = 0x0004,
6273         MNTDF_VERBOSE   = 0x0008,
6274         MNTDF_SHOW      = 0x0010,
6275         MNTDF_DECIMAL   = 0x0020,
6276 };
6277
6278 #define COOK(value, base)                                       \
6279 ({                                                              \
6280         int radix = 0;                                          \
6281         while (value > base) {                                  \
6282                 value /= base;                                  \
6283                 radix++;                                        \
6284         }                                                       \
6285         radix;                                                  \
6286 })
6287 #define UUF     "%-20s"
6288 #define CSF     "%11s"
6289 #define CDF     "%11llu"
6290 #define HDF     "%8.1f%c"
6291 #define RSF     "%4s"
6292 #define RDF     "%3d%%"
6293
6294 static inline int obd_statfs_ratio(const struct obd_statfs *st, bool inodes)
6295 {
6296         double avail, used, ratio = 0;
6297
6298         if (inodes) {
6299                 avail = st->os_ffree;
6300                 used = st->os_files - st->os_ffree;
6301         } else {
6302                 avail = st->os_bavail;
6303                 used = st->os_blocks - st->os_bfree;
6304         }
6305         if (avail + used > 0)
6306                 ratio = used / (used + avail) * 100;
6307
6308         /* Round up to match df(1) usage percentage */
6309         return (ratio - (int)ratio) > 0 ? (int)(ratio + 1) : (int)ratio;
6310 }
6311
6312 /*
6313  * This is to identify various problem states for "lfs df" if .osn_err = true,
6314  * so only show flags reflecting those states by default. Informational states
6315  * are only shown with "-v" and use lower-case names to distinguish them.
6316  * UNUSED[12] were for "EROFS = 30" until 1.6 but are now available for use.
6317  */
6318 static struct obd_statfs_state_names {
6319         enum obd_statfs_state   osn_state;
6320         const char              osn_name;
6321         bool                    osn_err;
6322 } oss_names[] = {
6323         { .osn_state = OS_STATFS_DEGRADED,   .osn_name = 'D', .osn_err = true },
6324         { .osn_state = OS_STATFS_READONLY,   .osn_name = 'R', .osn_err = true },
6325         { .osn_state = OS_STATFS_NOPRECREATE,.osn_name = 'N', .osn_err = true },
6326         { .osn_state = OS_STATFS_UNUSED1,    .osn_name = '?', .osn_err = true },
6327         { .osn_state = OS_STATFS_UNUSED2,    .osn_name = '?', .osn_err = true },
6328         { .osn_state = OS_STATFS_ENOSPC,     .osn_name = 'S', .osn_err = true },
6329         { .osn_state = OS_STATFS_ENOINO,     .osn_name = 'I', .osn_err = true },
6330         { .osn_state = OS_STATFS_SUM,        .osn_name = 'a', /* aggregate */ },
6331         { .osn_state = OS_STATFS_NONROT,     .osn_name = 'f', /* flash */     },
6332 };
6333
6334 static int showdf(char *mntdir, struct obd_statfs *stat,
6335                   char *uuid, enum mntdf_flags flags,
6336                   char *type, int index, int rc)
6337 {
6338         long long avail, used, total;
6339         int ratio = 0;
6340         char *suffix = flags & MNTDF_DECIMAL ? "kMGTPEZY" : "KMGTPEZY";
6341         /* Note if we have >2^64 bytes/fs these buffers will need to be grown */
6342         char tbuf[3 * sizeof(__u64)];
6343         char ubuf[3 * sizeof(__u64)];
6344         char abuf[3 * sizeof(__u64)];
6345         char rbuf[3 * sizeof(__u64)];
6346
6347         if (!uuid || !stat)
6348                 return -EINVAL;
6349
6350         switch (rc) {
6351         case 0:
6352                 if (flags & MNTDF_INODES) {
6353                         avail = stat->os_ffree;
6354                         used = stat->os_files - stat->os_ffree;
6355                         total = stat->os_files;
6356                 } else {
6357                         int shift = flags & MNTDF_COOKED ? 0 : 10;
6358
6359                         avail = (stat->os_bavail * stat->os_bsize) >> shift;
6360                         used  = ((stat->os_blocks - stat->os_bfree) *
6361                                  stat->os_bsize) >> shift;
6362                         total = (stat->os_blocks * stat->os_bsize) >> shift;
6363                 }
6364
6365                 ratio = obd_statfs_ratio(stat, flags & MNTDF_INODES);
6366
6367                 if (flags & MNTDF_COOKED) {
6368                         int base = flags & MNTDF_DECIMAL ? 1000 : 1024;
6369                         double cook_val;
6370                         int i;
6371
6372                         cook_val = (double)total;
6373                         i = COOK(cook_val, base);
6374                         if (i > 0)
6375                                 snprintf(tbuf, sizeof(tbuf), HDF, cook_val,
6376                                          suffix[i - 1]);
6377                         else
6378                                 snprintf(tbuf, sizeof(tbuf), CDF, total);
6379
6380                         cook_val = (double)used;
6381                         i = COOK(cook_val, base);
6382                         if (i > 0)
6383                                 snprintf(ubuf, sizeof(ubuf), HDF, cook_val,
6384                                          suffix[i - 1]);
6385                         else
6386                                 snprintf(ubuf, sizeof(ubuf), CDF, used);
6387
6388                         cook_val = (double)avail;
6389                         i = COOK(cook_val, base);
6390                         if (i > 0)
6391                                 snprintf(abuf, sizeof(abuf), HDF, cook_val,
6392                                          suffix[i - 1]);
6393                         else
6394                                 snprintf(abuf, sizeof(abuf), CDF, avail);
6395                 } else {
6396                         snprintf(tbuf, sizeof(tbuf), CDF, total);
6397                         snprintf(ubuf, sizeof(tbuf), CDF, used);
6398                         snprintf(abuf, sizeof(tbuf), CDF, avail);
6399                 }
6400
6401                 sprintf(rbuf, RDF, ratio);
6402                 printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s",
6403                        uuid, tbuf, ubuf, abuf, rbuf, mntdir);
6404                 if (type)
6405                         printf("[%s:%d]", type, index);
6406
6407                 if (stat->os_state) {
6408                         uint32_t i;
6409
6410                         printf(" ");
6411                         for (i = 0; i < ARRAY_SIZE(oss_names); i++) {
6412                                 if (oss_names[i].osn_state & stat->os_state &&
6413                                     (oss_names[i].osn_err ||
6414                                      flags & MNTDF_VERBOSE))
6415                                         printf("%c", oss_names[i].osn_name);
6416                         }
6417                 }
6418
6419                 printf("\n");
6420                 break;
6421         case -ENODATA:
6422                 printf(UUF": inactive device\n", uuid);
6423                 break;
6424         default:
6425                 printf(UUF": %s\n", uuid, strerror(-rc));
6426                 break;
6427         }
6428
6429         return 0;
6430 }
6431
6432 struct ll_stat_type {
6433         int   st_op;
6434         char *st_name;
6435 };
6436
6437 #define LL_STATFS_MAX   LOV_MAX_STRIPE_COUNT
6438
6439 struct ll_statfs_data {
6440         int                     sd_index;
6441         struct obd_statfs       sd_st;
6442 };
6443
6444 struct ll_statfs_buf {
6445         int                     sb_count;
6446         struct ll_statfs_data   sb_buf[LL_STATFS_MAX];
6447 };
6448
6449 static int mntdf(char *mntdir, char *fsname, char *pool, enum mntdf_flags flags,
6450                  int ops, struct ll_statfs_buf *lsb)
6451 {
6452         struct obd_statfs stat_buf, sum = { .os_bsize = 1 };
6453         struct obd_uuid uuid_buf;
6454         char *poolname = NULL;
6455         struct ll_stat_type types[] = {
6456                 { .st_op = LL_STATFS_LMV,       .st_name = "MDT" },
6457                 { .st_op = LL_STATFS_LOV,       .st_name = "OST" },
6458                 { .st_name = NULL } };
6459         struct ll_stat_type *tp;
6460         __u64 ost_files = 0;
6461         __u64 ost_ffree = 0;
6462         __u32 index;
6463         __u32 type;
6464         int fd;
6465         int rc = 0;
6466         int rc2;
6467
6468         if (pool) {
6469                 poolname = strchr(pool, '.');
6470                 if (poolname) {
6471                         if (strncmp(fsname, pool, strlen(fsname))) {
6472                                 fprintf(stderr, "filesystem name incorrect\n");
6473                                 return -ENODEV;
6474                         }
6475                         poolname++;
6476                 } else
6477                         poolname = pool;
6478         }
6479
6480         fd = open(mntdir, O_RDONLY);
6481         if (fd < 0) {
6482                 rc = -errno;
6483                 fprintf(stderr, "%s: cannot open '%s': %s\n", progname, mntdir,
6484                         strerror(errno));
6485                 return rc;
6486         }
6487
6488         if (flags & MNTDF_SHOW) {
6489                 if (flags & MNTDF_INODES)
6490                         printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s\n",
6491                                "UUID", "Inodes", "IUsed", "IFree",
6492                                "IUse%", "Mounted on");
6493                 else
6494                         printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s\n",
6495                                "UUID",
6496                                flags & MNTDF_COOKED ? "bytes" : "1K-blocks",
6497                                "Used", "Available", "Use%", "Mounted on");
6498         }
6499
6500         for (tp = types; tp->st_name != NULL; tp++) {
6501                 bool have_ost = false;
6502
6503                 if (!(tp->st_op & ops))
6504                         continue;
6505
6506                 for (index = 0; ; index++) {
6507                         memset(&stat_buf, 0, sizeof(struct obd_statfs));
6508                         memset(&uuid_buf, 0, sizeof(struct obd_uuid));
6509                         type = flags & MNTDF_LAZY ?
6510                                 tp->st_op | LL_STATFS_NODELAY : tp->st_op;
6511                         rc2 = llapi_obd_fstatfs(fd, type, index,
6512                                                &stat_buf, &uuid_buf);
6513                         if (rc2 == -ENODEV)
6514                                 break;
6515                         if (rc2 == -EAGAIN)
6516                                 continue;
6517                         if (rc2 == -ENODATA) { /* Inactive device, OK. */
6518                                 if (!(flags & MNTDF_VERBOSE))
6519                                         continue;
6520                         } else if (rc2 < 0 && rc == 0) {
6521                                 rc = rc2;
6522                         }
6523
6524                         /*
6525                          * If we have OSTs then don't report MDT block counts.
6526                          * For MDT-only filesystems the expectation is that all
6527                          * layouts have a DoM component.  For filesystems with
6528                          * OSTs, files are not necessarily going to store data
6529                          * on MDTs, and MDT space is limited to a fraction of
6530                          * OST space, so don't include it in the summary.
6531                          */
6532                         if (tp->st_op == LL_STATFS_LOV && !have_ost) {
6533                                 have_ost = true;
6534                                 sum.os_blocks = 0;
6535                                 sum.os_bfree = 0;
6536                                 sum.os_bavail = 0;
6537                         }
6538
6539                         if (poolname && tp->st_op == LL_STATFS_LOV &&
6540                             llapi_search_ost(fsname, poolname,
6541                                              obd_uuid2str(&uuid_buf)) != 1)
6542                                 continue;
6543
6544                         /*
6545                          * the llapi_obd_fstatfs() call may have returned with
6546                          * an error, but if it filled in uuid_buf we will at
6547                          * lease use that to print out a message for that OBD.
6548                          * If we didn't get anything in the uuid_buf, then fill
6549                          * it in so that we can print an error message.
6550                          */
6551                         if (uuid_buf.uuid[0] == '\0')
6552                                 snprintf(uuid_buf.uuid, sizeof(uuid_buf.uuid),
6553                                          "%s%04x", tp->st_name, index);
6554                         if (!rc && lsb) {
6555                                 lsb->sb_buf[lsb->sb_count].sd_index = index;
6556                                 lsb->sb_buf[lsb->sb_count].sd_st = stat_buf;
6557                                 lsb->sb_count++;
6558                         }
6559                         if (flags & MNTDF_SHOW)
6560                                 showdf(mntdir, &stat_buf,
6561                                        obd_uuid2str(&uuid_buf), flags,
6562                                        tp->st_name, index, rc2);
6563
6564                         if (rc2)
6565                                 continue;
6566
6567                         if (tp->st_op == LL_STATFS_LMV) {
6568                                 sum.os_ffree += stat_buf.os_ffree;
6569                                 sum.os_files += stat_buf.os_files;
6570                         } else /* if (tp->st_op == LL_STATFS_LOV) */ {
6571                                 ost_files += stat_buf.os_files;
6572                                 ost_ffree += stat_buf.os_ffree;
6573                         }
6574                         sum.os_blocks += stat_buf.os_blocks *
6575                                          stat_buf.os_bsize;
6576                         sum.os_bfree  += stat_buf.os_bfree *
6577                                          stat_buf.os_bsize;
6578                         sum.os_bavail += stat_buf.os_bavail *
6579                                          stat_buf.os_bsize;
6580                 }
6581         }
6582
6583         close(fd);
6584
6585         /*
6586          * If we have _some_ OSTs, but don't have as many free objects on the
6587          * OST as inodes on the MDTs, reduce the reported number of inodes
6588          * to compensate, so that the "inodes in use" number is correct.
6589          * This should be kept in sync with ll_statfs_internal().
6590          */
6591         if (ost_files && ost_ffree < sum.os_ffree) {
6592                 sum.os_files = (sum.os_files - sum.os_ffree) + ost_ffree;
6593                 sum.os_ffree = ost_ffree;
6594         }
6595         if (flags & MNTDF_SHOW) {
6596                 printf("\n");
6597                 showdf(mntdir, &sum, "filesystem_summary:", flags, NULL, 0, 0);
6598                 printf("\n");
6599         }
6600
6601         return rc;
6602 }
6603
6604 enum {
6605         LAYOUT_INHERIT_UNSET    = -2,
6606 };
6607
6608 /* functions */
6609 static int lfs_setdirstripe(int argc, char **argv)
6610 {
6611         char *dname;
6612         struct lfs_setstripe_args lsa = { 0 };
6613         struct llapi_stripe_param *param = NULL;
6614         __u32 mdts[LMV_MAX_STRIPE_COUNT] = { 0 };
6615         char *end;
6616         int c;
6617         char *mode_opt = NULL;
6618         bool default_stripe = false;
6619         bool delete = false;
6620         bool foreign_mode = false;
6621         mode_t mode = S_IRWXU | S_IRWXG | S_IRWXO;
6622         mode_t previous_mode = 0;
6623         char *xattr = NULL;
6624         __u32 type = LU_FOREIGN_TYPE_SYMLINK, flags = 0;
6625         int max_inherit = LAYOUT_INHERIT_UNSET;
6626         int max_inherit_rr = LAYOUT_INHERIT_UNSET;
6627         struct option long_opts[] = {
6628         { .val = 'c',   .name = "count",        .has_arg = required_argument },
6629         { .val = 'c',   .name = "mdt-count",    .has_arg = required_argument },
6630         { .val = 'd',   .name = "delete",       .has_arg = no_argument },
6631         { .val = 'D',   .name = "default",      .has_arg = no_argument },
6632         { .val = 'D',   .name = "default_stripe", .has_arg = no_argument },
6633         { .val = LFS_LAYOUT_FLAGS_OPT,
6634                         .name = "flags",        .has_arg = required_argument },
6635         { .val = LFS_LAYOUT_FOREIGN_OPT,
6636                         .name = "foreign",      .has_arg = optional_argument},
6637         { .val = 'h',   .name = "help",         .has_arg = no_argument },
6638         { .val = 'H',   .name = "mdt-hash",     .has_arg = required_argument },
6639 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 17, 53, 0)
6640         { .val = 'i',   .name = "mdt-index",    .has_arg = required_argument },
6641         { .val = 'i',   .name = "mdt",          .has_arg = required_argument },
6642 #else
6643 /* find { .val = 'l',   .name = "lazy",         .has_arg = no_argument }, */
6644         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument },
6645         { .val = 'm',   .name = "mdt",          .has_arg = required_argument },
6646 #endif
6647 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
6648         { .val = 'i',   .name = "index",        .has_arg = required_argument },
6649 #endif
6650         { .val = 'o',   .name = "mode",         .has_arg = required_argument },
6651 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
6652         { .val = 't',   .name = "hash-type",    .has_arg = required_argument },
6653 #endif
6654         { .val = 'T',   .name = "mdt-count",    .has_arg = required_argument },
6655         { .val = 'x',   .name = "xattr",        .has_arg = required_argument },
6656         { .val = 'X',   .name = "max-inherit",  .has_arg = required_argument },
6657         { .val = LFS_INHERIT_RR_OPT,
6658                         .name = "max-inherit-rr", .has_arg = required_argument},
6659 /* setstripe { .val = 'y', .name = "yaml",      .has_arg = no_argument }, */
6660         { .name = NULL } };
6661         int result = 0;
6662
6663         setstripe_args_init(&lsa);
6664
6665         while ((c = getopt_long(argc, argv, "c:dDi:hH:m:o:t:T:x:X:",
6666                                 long_opts, NULL)) >= 0) {
6667                 switch (c) {
6668                 case 0:
6669                         /* Long options. */
6670                         break;
6671                 case 'c':
6672                 case 'T':
6673                         errno = 0;
6674                         lsa.lsa_stripe_count = strtoul(optarg, &end, 0);
6675                         if (errno != 0 || *end != '\0' ||
6676                             lsa.lsa_stripe_count < -1 ||
6677                             lsa.lsa_stripe_count > LOV_MAX_STRIPE_COUNT) {
6678                                 fprintf(stderr,
6679                                         "%s: invalid stripe count '%s'\n",
6680                                         progname, optarg);
6681                                 return CMD_HELP;
6682                         }
6683                         break;
6684                 case 'd':
6685                         delete = true;
6686                         default_stripe = true;
6687                         break;
6688                 case 'D':
6689                         default_stripe = true;
6690                         break;
6691                 case LFS_LAYOUT_FOREIGN_OPT:
6692                         if (optarg) {
6693                                 /* check pure numeric */
6694                                 type = strtoul(optarg, &end, 0);
6695                                 if (*end) {
6696                                         /* check name */
6697                                         type = check_foreign_type_name(optarg);
6698                                         if (type == LU_FOREIGN_TYPE_UNKNOWN) {
6699                                                 fprintf(stderr,
6700                                                         "%s %s: unknown foreign type '%s'\n",
6701                                                         progname, argv[0],
6702                                                         optarg);
6703                                                 return CMD_HELP;
6704                                         }
6705                                 } else if (type >= UINT32_MAX) {
6706                                         fprintf(stderr,
6707                                                 "%s %s: invalid foreign type '%s'\n",
6708                                                 progname, argv[0], optarg);
6709                                         return CMD_HELP;
6710                                 }
6711                         }
6712                         foreign_mode = true;
6713                         break;
6714                 case LFS_LAYOUT_FLAGS_OPT:
6715                         errno = 0;
6716                         flags = strtoul(optarg, &end, 16);
6717                         if (errno != 0 || *end != '\0' ||
6718                             flags >= UINT32_MAX) {
6719                                 fprintf(stderr,
6720                                         "%s %s: invalid hex flags '%s'\n",
6721                                         progname, argv[0], optarg);
6722                                 return CMD_HELP;
6723                         }
6724                         if (!foreign_mode) {
6725                                 fprintf(stderr,
6726                                         "%s %s: hex flags must be specified with --foreign option\n",
6727                                         progname, argv[0]);
6728                                 return CMD_HELP;
6729                         }
6730                         break;
6731 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
6732                 case 't':
6733                         fprintf(stderr,
6734                                 "warning: '--hash-type' and '-t' deprecated, use '--mdt-hash' or '-H' instead\n");
6735                         /* fallthrough */
6736 #endif
6737                 case 'H':
6738                         lsa.lsa_pattern = check_hashtype(optarg);
6739                         if (lsa.lsa_pattern == 0) {
6740                                 fprintf(stderr,
6741                                         "%s %s: bad stripe hash type '%s'\n",
6742                                         progname, argv[0], optarg);
6743                                 return CMD_HELP;
6744                         }
6745                         break;
6746                 case 'i':
6747 #if LUSTRE_VERSION_CODE >= OBD_OCD_VERSION(2, 17, 53, 0)
6748                 case 'm':
6749 #endif
6750 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
6751                         if (strcmp(argv[optind - 1], "--index") == 0)
6752                                 fprintf(stderr,
6753                                         "%s %s: warning: '--index' deprecated, use '--mdt-index' instead\n",
6754                                         progname, argv[0]);
6755 #endif
6756                         lsa.lsa_nr_tgts = parse_targets(mdts,
6757                                                 sizeof(mdts) / sizeof(__u32),
6758                                                 lsa.lsa_nr_tgts, optarg, NULL);
6759                         if (lsa.lsa_nr_tgts < 0) {
6760                                 fprintf(stderr,
6761                                         "%s %s: invalid MDT target(s) '%s'\n",
6762                                         progname, argv[0], optarg);
6763                                 return CMD_HELP;
6764                         }
6765
6766                         lsa.lsa_tgts = mdts;
6767                         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
6768                                 lsa.lsa_stripe_off = mdts[0];
6769                         break;
6770 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 15, 53, 0)
6771                 case 'm':
6772                         fprintf(stderr,
6773                                 "warning: '-m' is deprecated, use '--mode' or '-o' instead\n");
6774 #endif
6775                 case 'o':
6776                         mode_opt = optarg;
6777                         break;
6778                 case 'x':
6779                         xattr = optarg;
6780                         break;
6781                 case 'X':
6782                         errno = 0;
6783                         max_inherit = strtol(optarg, &end, 10);
6784                         if (errno != 0 || *end != '\0' || max_inherit < -2) {
6785                                 fprintf(stderr,
6786                                         "%s %s: invalid max-inherit '%s'\n",
6787                                         progname, argv[0], optarg);
6788                                 return CMD_HELP;
6789                         }
6790                         if (max_inherit == 0) {
6791                                 max_inherit = LMV_INHERIT_NONE;
6792                         } else if (max_inherit == -1) {
6793                                 max_inherit = LMV_INHERIT_UNLIMITED;
6794                         } else if (max_inherit > LMV_INHERIT_MAX) {
6795                                 fprintf(stderr,
6796                                         "%s %s: max-inherit %d exceeds maximum %u\n",
6797                                         progname, argv[0], max_inherit,
6798                                         LMV_INHERIT_MAX);
6799                                 return CMD_HELP;
6800                         }
6801                         break;
6802                 case LFS_INHERIT_RR_OPT:
6803                         if (!default_stripe) {
6804                                 fprintf(stderr,
6805                                         "%s %s: '--max-inherit-rr' must be specified with '-D'\n",
6806                                         progname, argv[0]);
6807                                 return CMD_HELP;
6808                         }
6809                         errno = 0;
6810                         max_inherit_rr = strtol(optarg, &end, 10);
6811                         if (errno != 0 || *end != '\0' || max_inherit_rr < -2) {
6812                                 fprintf(stderr,
6813                                         "%s %s: invalid max-inherit-rr '%s'\n",
6814                                         progname, argv[0], optarg);
6815                                 return CMD_HELP;
6816                         }
6817                         if (max_inherit_rr == 0) {
6818                                 max_inherit_rr = LMV_INHERIT_RR_NONE;
6819                         } else if (max_inherit_rr == -1) {
6820                                 max_inherit_rr = LMV_INHERIT_RR_UNLIMITED;
6821                         } else if (max_inherit_rr > LMV_INHERIT_RR_MAX) {
6822                                 fprintf(stderr,
6823                                         "%s %s: max-inherit-rr %d exceeds maximum %u\n",
6824                                         progname, argv[0], max_inherit_rr,
6825                                         LMV_INHERIT_RR_MAX);
6826                                 return CMD_HELP;
6827                         }
6828                         break;
6829                 default:
6830                         fprintf(stderr, "%s: unrecognized option '%s'\n",
6831                                 progname, argv[optind - 1]);
6832                         /* fallthrough */
6833                 case 'h':
6834                         return CMD_HELP;
6835                 }
6836         }
6837
6838         if (optind == argc) {
6839                 fprintf(stderr, "%s %s: DIR must be specified\n",
6840                         progname, argv[0]);
6841                 return CMD_HELP;
6842         }
6843
6844         if (xattr && !foreign_mode) {
6845                 /*
6846                  * only print a warning as this is armless and will be
6847                  * ignored
6848                  */
6849                 fprintf(stderr,
6850                         "%s %s: xattr has been specified for non-foreign layout\n",
6851                         progname, argv[0]);
6852         } else if (foreign_mode && !xattr) {
6853                 fprintf(stderr,
6854                         "%s %s: xattr must be provided in foreign mode\n",
6855                         progname, argv[0]);
6856                 return CMD_HELP;
6857         }
6858
6859         if (foreign_mode && (delete || default_stripe || lsa.lsa_nr_tgts ||
6860             lsa.lsa_tgts || setstripe_args_specified(&lsa))) {
6861                 fprintf(stderr,
6862                         "%s %s: only --xattr/--flags/--mode options are valid with --foreign\n",
6863                         progname, argv[0]);
6864                 return CMD_HELP;
6865         }
6866
6867         if (!delete && lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT &&
6868             lsa.lsa_stripe_count == LLAPI_LAYOUT_DEFAULT && !foreign_mode) {
6869                 /* if no parameters set, create directory on least-used MDTs */
6870                 lsa.lsa_stripe_off = LMV_OFFSET_DEFAULT;
6871                 lsa.lsa_stripe_count = 1;
6872         }
6873
6874         if (delete &&
6875             (lsa.lsa_stripe_off != LLAPI_LAYOUT_DEFAULT ||
6876              lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT)) {
6877                 fprintf(stderr,
6878                         "%s %s: cannot specify -d with -c or -i options\n",
6879                         progname, argv[0]);
6880                 return CMD_HELP;
6881         }
6882
6883         if (mode_opt) {
6884                 mode = strtoul(mode_opt, &end, 8);
6885                 if (*end != '\0') {
6886                         fprintf(stderr,
6887                                 "%s %s: bad MODE '%s'\n",
6888                                 progname, argv[0], mode_opt);
6889                         return CMD_HELP;
6890                 }
6891                 previous_mode = umask(0);
6892         }
6893
6894         if (max_inherit_rr != LAYOUT_INHERIT_UNSET &&
6895             lsa.lsa_stripe_off != LLAPI_LAYOUT_DEFAULT &&
6896             lsa.lsa_stripe_off != LMV_OFFSET_DEFAULT) {
6897                 fprintf(stderr,
6898                         "%s %s: max-inherit-rr needs mdt-index=-1, not %lld\n",
6899                         progname, argv[0], lsa.lsa_stripe_off);
6900                 return CMD_HELP;
6901         }
6902
6903         /* foreign LMV/dir case */
6904         if (foreign_mode) {
6905                 if (argc > optind + 1) {
6906                         fprintf(stderr,
6907                                 "%s %s: cannot specify multiple foreign dirs\n",
6908                                 progname, argv[0]);
6909                         return CMD_HELP;
6910                 }
6911
6912                 dname = argv[optind];
6913                 result = llapi_dir_create_foreign(dname, mode, type, flags,
6914                                                   xattr);
6915                 if (result != 0)
6916                         fprintf(stderr,
6917                                 "%s mkdir: can't create foreign dir '%s': %s\n",
6918                                 progname, dname, strerror(-result));
6919                 return result;
6920         }
6921
6922         /*
6923          * initialize stripe parameters, in case param is converted to specific,
6924          * i.e, 'lfs mkdir -i -1 -c N', always allocate space for lsp_tgts.
6925          */
6926         param = calloc(1, offsetof(typeof(*param),
6927                        lsp_tgts[lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT ?
6928                                 lsa.lsa_stripe_count : lsa.lsa_nr_tgts]));
6929         if (!param) {
6930                 fprintf(stderr,
6931                         "%s %s: cannot allocate memory for parameters: %s\n",
6932                         progname, argv[0], strerror(ENOMEM));
6933                 return CMD_HELP;
6934         }
6935
6936         /* if "lfs setdirstripe -D -i -1" is used, assume 1-stripe directory */
6937         if (default_stripe && lsa.lsa_stripe_off == LMV_OFFSET_DEFAULT &&
6938             (lsa.lsa_stripe_count == LLAPI_LAYOUT_DEFAULT ||
6939              lsa.lsa_stripe_count == 0))
6940                 lsa.lsa_stripe_count = 1;
6941         if (lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT)
6942                 param->lsp_stripe_count = lsa.lsa_stripe_count;
6943         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
6944                 param->lsp_stripe_offset = LMV_OFFSET_DEFAULT;
6945         else
6946                 param->lsp_stripe_offset = lsa.lsa_stripe_off;
6947         if (lsa.lsa_pattern != LLAPI_LAYOUT_RAID0)
6948                 param->lsp_stripe_pattern = lsa.lsa_pattern;
6949         else
6950                 param->lsp_stripe_pattern = LMV_HASH_TYPE_UNKNOWN;
6951         param->lsp_pool = lsa.lsa_pool_name;
6952         param->lsp_is_specific = false;
6953         if (max_inherit == LAYOUT_INHERIT_UNSET)
6954                 max_inherit = LMV_INHERIT_DEFAULT;
6955         param->lsp_max_inherit = max_inherit;
6956         if (default_stripe) {
6957                 if (max_inherit_rr == LAYOUT_INHERIT_UNSET)
6958                         max_inherit_rr = LMV_INHERIT_RR_DEFAULT;
6959                 param->lsp_max_inherit_rr = max_inherit_rr;
6960         }
6961         if (strcmp(argv[0], "mkdir") == 0)
6962                 param->lsp_is_create = true;
6963         if (lsa.lsa_nr_tgts > 1) {
6964                 if (lsa.lsa_stripe_count > 0 &&
6965                     lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT &&
6966                     lsa.lsa_stripe_count != lsa.lsa_nr_tgts) {
6967                         fprintf(stderr,
6968                                 "error: %s: stripe count %lld doesn't match the number of MDTs: %d\n",
6969                                 argv[0], lsa.lsa_stripe_count,
6970                                 lsa.lsa_nr_tgts);
6971                         free(param);
6972                         return CMD_HELP;
6973                 }
6974
6975                 param->lsp_is_specific = true;
6976                 param->lsp_stripe_count = lsa.lsa_nr_tgts;
6977                 memcpy(param->lsp_tgts, mdts, sizeof(*mdts) * lsa.lsa_nr_tgts);
6978         }
6979
6980         dname = argv[optind];
6981         do {
6982                 if (default_stripe) {
6983                         result = llapi_dir_set_default_lmv(dname, param);
6984                         if (result)
6985                                 fprintf(stderr,
6986                                         "%s setdirstripe: cannot set default stripe on dir '%s': %s\n",
6987                                         progname, dname, strerror(-result));
6988                         continue;
6989                 }
6990
6991                 result = llapi_dir_create(dname, mode, param);
6992                 if (result)
6993                         fprintf(stderr,
6994                                 "%s setdirstripe: cannot create dir '%s': %s\n",
6995                                 progname, dname, strerror(-result));
6996         } while (!result && (dname = argv[++optind]));
6997
6998         if (mode_opt)
6999                 umask(previous_mode);
7000
7001         free(param);
7002         return result;
7003 }
7004
7005 /* functions */
7006 static int lfs_rmentry(int argc, char **argv)
7007 {
7008         char *dname;
7009         int   index;
7010         int   result = 0;
7011
7012         if (argc <= 1) {
7013                 fprintf(stderr, "error: %s: missing dirname\n",
7014                         argv[0]);
7015                 return CMD_HELP;
7016         }
7017
7018         index = 1;
7019         dname = argv[index];
7020         while (dname) {
7021                 result = llapi_direntry_remove(dname);
7022                 if (result) {
7023                         fprintf(stderr,
7024                                 "error: %s: remove dir entry '%s' failed\n",
7025                                 argv[0], dname);
7026                         break;
7027                 }
7028                 dname = argv[++index];
7029         }
7030         return result;
7031 }
7032
7033 static int lfs_unlink_foreign(int argc, char **argv)
7034 {
7035         char *name;
7036         int   index;
7037         int   result = 0;
7038
7039         if (argc <= 1) {
7040                 fprintf(stderr, "error: %s: missing pathname\n",
7041                         argv[0]);
7042                 return CMD_HELP;
7043         }
7044
7045         index = 1;
7046         name = argv[index];
7047         while (name != NULL) {
7048                 result = llapi_unlink_foreign(name);
7049                 if (result) {
7050                         fprintf(stderr,
7051                                 "error: %s: unlink foreign entry '%s' failed\n",
7052                                 argv[0], name);
7053                         break;
7054                 }
7055                 name = argv[++index];
7056         }
7057         return result;
7058 }
7059
7060 static int lfs_mv(int argc, char **argv)
7061 {
7062         struct lmv_user_md lmu = { LMV_USER_MAGIC };
7063         struct find_param param = {
7064                 .fp_max_depth = -1,
7065                 .fp_mdt_index = -1,
7066         };
7067         char *end;
7068         int c;
7069         int rc = 0;
7070         struct option long_opts[] = {
7071         { .val = 'm',   .name = "mdt",          .has_arg = required_argument },
7072         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument },
7073         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
7074         { .name = NULL } };
7075
7076         while ((c = getopt_long(argc, argv, "m:M:v", long_opts, NULL)) != -1) {
7077                 switch (c) {
7078 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
7079                 case 'M':
7080                         fprintf(stderr,
7081                                 "warning: '-M' deprecated, use '--mdt-index' or '-m' instead\n");
7082 #endif
7083                 case 'm':
7084                         errno = 0;
7085                         lmu.lum_stripe_offset = strtoul(optarg, &end, 0);
7086                         if (errno != 0 || *end != '\0' ||
7087                             lmu.lum_stripe_offset >= UINT32_MAX) {
7088                                 fprintf(stderr, "%s mv: bad MDT index '%s'\n",
7089                                         progname, optarg);
7090                                 return CMD_HELP;
7091                         }
7092                         break;
7093                 case 'v':
7094                         param.fp_verbose = VERBOSE_DETAIL;
7095                         break;
7096                 default:
7097                         fprintf(stderr, "%s mv: unrecognized option '%s'\n",
7098                                 progname, argv[optind - 1]);
7099                         return CMD_HELP;
7100                 }
7101         }
7102
7103         if (lmu.lum_stripe_offset == LMV_OFFSET_DEFAULT) {
7104                 fprintf(stderr, "%s mv: MDT index must be specified\n",
7105                         progname);
7106                 return CMD_HELP;
7107         }
7108
7109         if (optind >= argc) {
7110                 fprintf(stderr, "%s mv: DIR must be specified\n", progname);
7111                 return CMD_HELP;
7112         }
7113
7114         lmu.lum_hash_type = LMV_HASH_TYPE_UNKNOWN;
7115
7116         /* initialize migrate mdt parameters */
7117         param.fp_lmv_md = &lmu;
7118         param.fp_migrate = 1;
7119         rc = llapi_migrate_mdt(argv[optind], &param);
7120         if (rc != 0)
7121                 fprintf(stderr, "%s mv: cannot migrate '%s' to MDT%04x: %s\n",
7122                         progname, argv[optind], lmu.lum_stripe_offset,
7123                         strerror(-rc));
7124         return rc;
7125 }
7126
7127 static int lfs_osts(int argc, char **argv)
7128 {
7129         return lfs_tgts(argc, argv);
7130 }
7131
7132 static int lfs_mdts(int argc, char **argv)
7133 {
7134         return lfs_tgts(argc, argv);
7135 }
7136
7137 static int lfs_df(int argc, char **argv)
7138 {
7139         char mntdir[PATH_MAX] = {'\0'}, path[PATH_MAX] = {'\0'};
7140         enum mntdf_flags flags = MNTDF_SHOW;
7141         int ops = LL_STATFS_LMV | LL_STATFS_LOV;
7142         int c, rc = 0, rc1 = 0, index = 0, arg_idx = 0;
7143         char fsname[PATH_MAX] = "", *pool_name = NULL;
7144         struct option long_opts[] = {
7145         { .val = 'h',   .name = "human-readable", .has_arg = no_argument },
7146         { .val = 'H',   .name = "si",           .has_arg = no_argument },
7147         { .val = 'i',   .name = "inodes",       .has_arg = no_argument },
7148         { .val = 'l',   .name = "lazy",         .has_arg = no_argument },
7149         { .val = 'p',   .name = "pool",         .has_arg = required_argument },
7150         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
7151         { .name = NULL} };
7152
7153         while ((c = getopt_long(argc, argv, "hHilp:v", long_opts, NULL)) != -1) {
7154                 switch (c) {
7155                 case 'h':
7156                         flags = (flags & ~MNTDF_DECIMAL) | MNTDF_COOKED;
7157                         break;
7158                 case 'H':
7159                         flags |= MNTDF_COOKED | MNTDF_DECIMAL;
7160                         break;
7161                 case 'i':
7162                         flags |= MNTDF_INODES;
7163                         break;
7164                 case 'l':
7165                         flags |= MNTDF_LAZY;
7166                         break;
7167                 case 'p':
7168                         pool_name = optarg;
7169                         break;
7170                 case 'v':
7171                         flags |= MNTDF_VERBOSE;
7172                         break;
7173                 default:
7174                         fprintf(stderr, "%s: unrecognized option '%s'\n",
7175                                 progname, argv[optind - 1]);
7176                         return CMD_HELP;
7177                 }
7178         }
7179
7180         /* Handle case where path is not specified */
7181         if (optind == argc) {
7182                 while (!llapi_search_mounts(path, index++, mntdir, fsname)) {
7183                         /* Check if we have a mount point */
7184                         if (mntdir[0] == '\0')
7185                                 continue;
7186
7187                         rc = mntdf(mntdir, fsname, pool_name, flags, ops, NULL);
7188                         if (rc || path[0] != '\0')
7189                                 break;
7190
7191                         fsname[0] = '\0'; /* avoid matching in next loop */
7192                         mntdir[0] = '\0'; /* avoid matching in next loop */
7193                         path[0] = '\0'; /* clean for next loop */
7194                 }
7195                 return rc;
7196         }
7197
7198         /* Loop through all the remaining arguments. These are Lustre FS
7199          * paths.
7200          */
7201         for (arg_idx = optind; arg_idx <= argc - 1; arg_idx++) {
7202                 bool valid = false;
7203
7204                 fsname[0] = '\0'; /* start clean */
7205                 mntdir[0] = '\0'; /* start clean */
7206                 path[0] = '\0';   /* start clean */
7207
7208                 /* path does not exists at all */
7209                 if (!realpath(argv[arg_idx], path)) {
7210                         rc = -errno;
7211                         fprintf(stderr, "error: invalid path '%s': %s\n",
7212                                 argv[arg_idx], strerror(-rc));
7213                         /* save first seen error */
7214                         if (!rc1)
7215                                 rc1 = rc;
7216
7217                         continue;
7218                 }
7219
7220                 /* path exists but may not be a Lustre filesystem */
7221                 while (!llapi_search_mounts(path, index++, mntdir, fsname)) {
7222                         /* Check if we have a mount point */
7223                         if (mntdir[0] == '\0')
7224                                 continue;
7225
7226                         rc = mntdf(mntdir, fsname, pool_name, flags, ops, NULL);
7227                         if (rc || path[0] != '\0') {
7228                                 valid = true;
7229
7230                                 /* save first seen error */
7231                                 if (!rc1)
7232                                         rc1 = rc;
7233                                 break;
7234                         }
7235                 }
7236
7237                 if (!valid) {
7238                         llapi_printf(LLAPI_MSG_ERROR,
7239                                      "%s:%s Not a Lustre filesystem\n",
7240                                      argv[0], argv[arg_idx]);
7241                         /* save first seen error */
7242                         if (!rc1)
7243                                 rc1 = -EOPNOTSUPP;
7244                 }
7245         }
7246
7247         return rc1;
7248 }
7249
7250 static int print_instance(const char *mntdir, char *buf, size_t buflen,
7251                           bool opt_instance, bool opt_fsname, bool opt_mntdir)
7252 {
7253         int rc = 0;
7254
7255         if (opt_fsname == opt_instance) { /* both true or both false */
7256                 rc = llapi_getname(mntdir, buf, buflen);
7257         } else if (opt_fsname) {
7258                 /*
7259                  * llapi_search_mounts() fills @buf with fsname, but that is not
7260                  * called if explicit paths are specified on the command-line
7261                  */
7262                 if (buf[0] == '\0')
7263                         rc = llapi_get_fsname(mntdir, buf, buflen);
7264         } else /* if (opt_instance) */ {
7265                 rc = llapi_get_instance(mntdir, buf, buflen);
7266         }
7267
7268         if (rc < 0) {
7269                 fprintf(stderr, "cannot get instance for '%s': %s\n",
7270                         mntdir, strerror(-rc));
7271                 return rc;
7272         }
7273
7274         if (opt_mntdir)
7275                 printf("%s %s\n", buf, mntdir);
7276         else
7277                 printf("%s\n", buf);
7278
7279         return 0;
7280 }
7281
7282 static int lfs_getname(int argc, char **argv)
7283 {
7284         struct option long_opts[] = {
7285         { .val = 'h',   .name = "help",         .has_arg = no_argument },
7286         { .val = 'i',   .name = "instance",     .has_arg = no_argument },
7287         { .val = 'n',   .name = "fsname",       .has_arg = no_argument },
7288         { .name = NULL} };
7289         bool opt_instance = false, opt_fsname = false;
7290         char fsname[PATH_MAX] = "";
7291         int rc = 0, rc2, c;
7292
7293         while ((c = getopt_long(argc, argv, "hin", long_opts, NULL)) != -1) {
7294                 switch (c) {
7295                 case 'i':
7296                         opt_instance = true;
7297                         break;
7298                 case 'n':
7299                         opt_fsname = true;
7300                         break;
7301                 default:
7302                         fprintf(stderr, "%s: unrecognized option '%s'\n",
7303                                 progname, argv[optind - 1]);
7304                         /* fallthrough */
7305                 case 'h':
7306                         return CMD_HELP;
7307                 }
7308         }
7309
7310         if (optind == argc) { /* no paths specified, get all paths. */
7311                 char mntdir[PATH_MAX] = "", path[PATH_MAX] = "";
7312                 int index = 0;
7313
7314                 while (!llapi_search_mounts(path, index++, mntdir, fsname)) {
7315                         rc2 = print_instance(mntdir, fsname, sizeof(fsname),
7316                                              opt_instance, opt_fsname, true);
7317                         if (!rc)
7318                                 rc = rc2;
7319                         path[0] = fsname[0] = mntdir[0] = '\0';
7320                 }
7321         } else { /* paths specified, only attempt to search these. */
7322                 bool opt_mntdir;
7323
7324                 /* if only one path is given, print only requested info */
7325                 opt_mntdir = argc - optind > 1 || (opt_instance == opt_fsname);
7326
7327                 for (; optind < argc; optind++) {
7328                         rc2 = print_instance(argv[optind], fsname,
7329                                              sizeof(fsname), opt_instance,
7330                                              opt_fsname, opt_mntdir);
7331                         if (!rc)
7332                                 rc = rc2;
7333                         fsname[0] = '\0';
7334                 }
7335         }
7336
7337         return rc;
7338 }
7339
7340 static int lfs_check(int argc, char **argv)
7341 {
7342         char mntdir[PATH_MAX] = {'\0'};
7343         int num_types = 1;
7344         char *obd_types[3];
7345         char obd_type1[4];
7346         char obd_type2[4];
7347         char obd_type3[4];
7348         int rc;
7349
7350         if (argc != 2) {
7351                 fprintf(stderr, "%s check: server type must be specified\n",
7352                         progname);
7353                 return CMD_HELP;
7354         }
7355
7356         obd_types[0] = obd_type1;
7357         obd_types[1] = obd_type2;
7358         obd_types[2] = obd_type3;
7359
7360         if (strcmp(argv[1], "osts") == 0) {
7361                 strcpy(obd_types[0], "osc");
7362         } else if (strcmp(argv[1], "mdts") == 0 ||
7363                    strcmp(argv[1], "mds") == 0) {
7364                 strcpy(obd_types[0], "mdc");
7365         } else if (strcmp(argv[1], "mgts") == 0) {
7366                 strcpy(obd_types[0], "mgc");
7367         } else if (strcmp(argv[1], "all") == 0 ||
7368                    strcmp(argv[1], "servers") == 0) {
7369                 num_types = 3;
7370                 strcpy(obd_types[0], "osc");
7371                 strcpy(obd_types[1], "mdc");
7372                 strcpy(obd_types[2], "mgc");
7373         } else {
7374                 fprintf(stderr, "%s check: unrecognized option '%s'\n",
7375                         progname, argv[1]);
7376                 return CMD_HELP;
7377         }
7378
7379         rc = llapi_search_mounts(NULL, 0, mntdir, NULL);
7380         if (rc < 0 || mntdir[0] == '\0') {
7381                 fprintf(stderr,
7382                         "%s check: cannot find mounted Lustre filesystem: %s\n",
7383                         progname, (rc < 0) ? strerror(-rc) : strerror(ENODEV));
7384                 return rc;
7385         }
7386
7387         rc = llapi_target_check(num_types, obd_types, mntdir);
7388         if (rc)
7389                 fprintf(stderr, "%s check: cannot check target '%s': %s\n",
7390                         progname, argv[1], strerror(-rc));
7391
7392         return rc;
7393 }
7394
7395 #ifdef HAVE_SYS_QUOTA_H
7396 #define ADD_OVERFLOW(a, b) \
7397                      ((((a) + (b)) < (a)) ? \
7398                       ((a) = ULONG_MAX) : ((a) = (a) + (b)))
7399
7400 /* Convert format time string "XXwXXdXXhXXmXXs" into seconds value
7401  * returns the value or ULONG_MAX on integer overflow or incorrect format
7402  * Notes:
7403  *        1. the order of specifiers is arbitrary (may be: 5w3s or 3s5w)
7404  *        2. specifiers may be encountered multiple times (2s3s is 5 seconds)
7405  *        3. empty integer value is interpreted as 0
7406  */
7407 static unsigned long str2sec(const char *timestr)
7408 {
7409         const char spec[] = "smhdw";
7410         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
7411         unsigned long val = 0;
7412         char *tail;
7413
7414         if (strpbrk(timestr, spec) == NULL) {
7415                 /*
7416                  * no specifiers inside the time string,
7417                  * should treat it as an integer value
7418                  */
7419                 val = strtoul(timestr, &tail, 10);
7420                 return *tail ? ULONG_MAX : val;
7421         }
7422
7423         /* format string is XXwXXdXXhXXmXXs */
7424         while (*timestr) {
7425                 unsigned long v;
7426                 int ind;
7427                 char *ptr;
7428
7429                 v = strtoul(timestr, &tail, 10);
7430                 if (v == ULONG_MAX || *tail == '\0')
7431                         /*
7432                          * value too large (ULONG_MAX or more)
7433                          * or missing specifier
7434                          */
7435                         goto error;
7436
7437                 ptr = strchr(spec, *tail);
7438                 if (!ptr)
7439                         /* unknown specifier */
7440                         goto error;
7441
7442                 ind = ptr - spec;
7443
7444                 /* check if product will overflow the type */
7445                 if (!(v < ULONG_MAX / mult[ind]))
7446                         goto error;
7447
7448                 ADD_OVERFLOW(val, mult[ind] * v);
7449                 if (val == ULONG_MAX)
7450                         goto error;
7451
7452                 timestr = tail + 1;
7453         }
7454
7455         return val;
7456
7457 error:
7458         return ULONG_MAX;
7459 }
7460
7461 #define ARG2ULL(nr, str, def_units)                                     \
7462 do {                                                                    \
7463         unsigned long long limit, units = def_units;                    \
7464         int rc;                                                         \
7465                                                                         \
7466         rc = llapi_parse_size(str, &limit, &units, 1);                  \
7467         if (rc < 0) {                                                   \
7468                 fprintf(stderr, "%s: invalid limit '%s'\n",             \
7469                         progname, str);                                 \
7470                 return CMD_HELP;                                        \
7471         }                                                               \
7472         nr = limit;                                                     \
7473 } while (0)
7474
7475 static inline int has_times_option(int argc, char **argv)
7476 {
7477         int i;
7478
7479         for (i = 1; i < argc; i++)
7480                 if (!strcmp(argv[i], "-t"))
7481                         return 1;
7482
7483         return 0;
7484 }
7485
7486 static inline int lfs_verify_poolarg(char *pool)
7487 {
7488         if (strnlen(optarg, LOV_MAXPOOLNAME + 1) > LOV_MAXPOOLNAME) {
7489                 fprintf(stderr,
7490                         "Pool name '%.*s' is longer than %d\n",
7491                         LOV_MAXPOOLNAME, pool, LOV_MAXPOOLNAME);
7492                 return 1;
7493         }
7494         return 0;
7495 }
7496
7497 /* special grace time, only notify the user when its quota is over soft limit
7498  * but doesn't block new writes until the hard limit is reached.
7499  */
7500 #define NOTIFY_GRACE            "notify"
7501 #define NOTIFY_GRACE_TIME       LQUOTA_GRACE_MASK
7502
7503 #ifndef toqb
7504 static inline __u64 lustre_stoqb(size_t space)
7505 {
7506         return (space + QIF_DQBLKSIZE - 1) >> QIF_DQBLKSIZE_BITS;
7507 }
7508 #else
7509 #define lustre_stoqb   toqb
7510 #endif
7511
7512 int lfs_setquota_times(int argc, char **argv, struct if_quotactl *qctl)
7513 {
7514         int c, rc;
7515         char *mnt, *obd_type = (char *)qctl->obd_type;
7516         struct obd_dqblk *dqb = &qctl->qc_dqblk;
7517         struct obd_dqinfo *dqi = &qctl->qc_dqinfo;
7518         struct option long_opts[] = {
7519         { .val = 'b',   .name = "block-grace",  .has_arg = required_argument },
7520         { .val = 'g',   .name = "group",        .has_arg = no_argument },
7521         { .val = 'h',   .name = "help",         .has_arg = no_argument },
7522         { .val = 'i',   .name = "inode-grace",  .has_arg = required_argument },
7523         { .val = 'p',   .name = "projid",       .has_arg = no_argument },
7524         { .val = 't',   .name = "times",        .has_arg = no_argument },
7525         { .val = 'u',   .name = "user",         .has_arg = no_argument },
7526         { .val = LFS_POOL_OPT,
7527                         .name = "pool",         .has_arg = required_argument },
7528         { .name = NULL } };
7529         int qtype;
7530
7531         qctl->qc_cmd  = LUSTRE_Q_SETINFO;
7532         qctl->qc_type = ALLQUOTA;
7533
7534         while ((c = getopt_long(argc, argv, "b:ghi:ptu",
7535                                 long_opts, NULL)) != -1) {
7536                 switch (c) {
7537                 case 'u':
7538                         qtype = USRQUOTA;
7539                         goto quota_type;
7540                 case 'g':
7541                         qtype = GRPQUOTA;
7542                         goto quota_type;
7543                 case 'p':
7544                         qtype = PRJQUOTA;
7545 quota_type:
7546                         if (qctl->qc_type != ALLQUOTA) {
7547                                 fprintf(stderr,
7548                                         "%s: -u/g/p cannot be used more than once\n",
7549                                         progname);
7550                                 return CMD_HELP;
7551                         }
7552                         qctl->qc_type = qtype;
7553                         break;
7554                 case 'b':
7555                         if (strncmp(optarg, NOTIFY_GRACE,
7556                                     strlen(NOTIFY_GRACE)) == 0) {
7557                                 dqi->dqi_bgrace = NOTIFY_GRACE_TIME;
7558                         } else {
7559                                 dqi->dqi_bgrace = str2sec(optarg);
7560                                 if (dqi->dqi_bgrace >= NOTIFY_GRACE_TIME) {
7561                                         fprintf(stderr,
7562                                                 "%s: bad block-grace: %s\n",
7563                                                 progname, optarg);
7564                                         return CMD_HELP;
7565                                 }
7566                         }
7567                         dqb->dqb_valid |= QIF_BTIME;
7568                         break;
7569                 case 'i':
7570                         if (strncmp(optarg, NOTIFY_GRACE,
7571                                     strlen(NOTIFY_GRACE)) == 0) {
7572                                 dqi->dqi_igrace = NOTIFY_GRACE_TIME;
7573                         } else {
7574                                 dqi->dqi_igrace = str2sec(optarg);
7575                                 if (dqi->dqi_igrace >= NOTIFY_GRACE_TIME) {
7576                                         fprintf(stderr,
7577                                                 "%s: bad inode-grace: %s\n",
7578                                                 progname, optarg);
7579                                         return CMD_HELP;
7580                                 }
7581                         }
7582                         dqb->dqb_valid |= QIF_ITIME;
7583                         break;
7584                 case 't': /* Yes, of course! */
7585                         break;
7586                 case LFS_POOL_OPT:
7587                         if (lfs_verify_poolarg(optarg))
7588                                 return -1;
7589                         strncpy(qctl->qc_poolname, optarg, LOV_MAXPOOLNAME);
7590                         qctl->qc_cmd  = LUSTRE_Q_SETINFOPOOL;
7591                         break;
7592                 /* getopt prints error message for us when opterr != 0 */
7593                 default:
7594                         fprintf(stderr, "%s: unrecognized option '%s'\n",
7595                                 progname, argv[optind - 1]);
7596                         /* fallthrough */
7597                 case 'h':
7598                         return CMD_HELP;
7599                 }
7600         }
7601
7602         if (qctl->qc_type == ALLQUOTA) {
7603                 fprintf(stderr, "%s: neither -u, -g nor -p specified\n",
7604                         progname);
7605                 return CMD_HELP;
7606         }
7607
7608         if (optind != argc - 1) {
7609                 fprintf(stderr, "%s: unexpected parameter '%s'\n",
7610                         progname, argv[optind + 1]);
7611                 return CMD_HELP;
7612         }
7613
7614         mnt = argv[optind];
7615         rc = llapi_quotactl(mnt, qctl);
7616         if (rc) {
7617                 if (*obd_type)
7618                         fprintf(stderr, "%s %s ", obd_type,
7619                                 obd_uuid2str(&qctl->obd_uuid));
7620                 fprintf(stderr, "setquota failed: %s\n", strerror(-rc));
7621                 return rc;
7622         }
7623
7624         return 0;
7625 }
7626
7627 #define BSLIMIT (1 << 0)
7628 #define BHLIMIT (1 << 1)
7629 #define ISLIMIT (1 << 2)
7630 #define IHLIMIT (1 << 3)
7631
7632 int lfs_setquota(int argc, char **argv)
7633 {
7634         int c, rc = 0;
7635         struct if_quotactl *qctl;
7636         char *mnt, *obd_type;
7637         struct obd_dqblk *dqb;
7638         struct option long_opts[] = {
7639         { .val = 'b',   .name = "block-softlimit",
7640                                                 .has_arg = required_argument },
7641         { .val = 'B',   .name = "block-hardlimit",
7642                                                 .has_arg = required_argument },
7643         { .val = 'd',   .name = "default",      .has_arg = no_argument },
7644         { .val = 'g',   .name = "group",        .has_arg = required_argument },
7645         { .val = 'G',   .name = "default-grp",  .has_arg = no_argument },
7646         { .val = 'h',   .name = "help",         .has_arg = no_argument },
7647         { .val = 'i',   .name = "inode-softlimit",
7648                                                 .has_arg = required_argument },
7649         { .val = 'I',   .name = "inode-hardlimit",
7650                                                 .has_arg = required_argument },
7651         { .val = 'p',   .name = "projid",       .has_arg = required_argument },
7652         { .val = 'P',   .name = "default-prj",  .has_arg = no_argument },
7653         { .val = 'u',   .name = "user",         .has_arg = required_argument },
7654         { .val = 'U',   .name = "default-usr",  .has_arg = no_argument },
7655         { .val = LFS_POOL_OPT,
7656                         .name = "pool",         .has_arg = required_argument },
7657         { .name = NULL } };
7658         unsigned int limit_mask = 0;
7659         bool use_default = false;
7660         int qtype, qctl_len;
7661
7662         qctl_len = sizeof(*qctl) + LOV_MAXPOOLNAME + 1;
7663         qctl = malloc(qctl_len);
7664         if (!qctl)
7665                 return -ENOMEM;
7666
7667         memset(qctl, 0, qctl_len);
7668         obd_type = (char *)qctl->obd_type;
7669         dqb = &qctl->qc_dqblk;
7670
7671         if (has_times_option(argc, argv)) {
7672                 rc = lfs_setquota_times(argc, argv, qctl);
7673                 goto out;
7674         }
7675
7676         qctl->qc_cmd  = LUSTRE_Q_SETQUOTA;
7677         qctl->qc_type = ALLQUOTA; /* ALLQUOTA makes no sense for setquota,
7678                                    * so it can be used as a marker that qc_type
7679                                    * isn't reinitialized from command line
7680                                    */
7681
7682         while ((c = getopt_long(argc, argv, "b:B:dg:Ghi:I:p:Pu:U",
7683                 long_opts, NULL)) != -1) {
7684                 switch (c) {
7685                 case 'U':
7686                         qctl->qc_cmd = LUSTRE_Q_SETDEFAULT;
7687                         qtype = USRQUOTA;
7688                         qctl->qc_id = 0;
7689                         goto quota_type_def;
7690                 case 'u':
7691                         qtype = USRQUOTA;
7692                         rc = name2uid(&qctl->qc_id, optarg);
7693                         goto quota_type;
7694                 case 'G':
7695                         qctl->qc_cmd = LUSTRE_Q_SETDEFAULT;
7696                         qtype = GRPQUOTA;
7697                         qctl->qc_id = 0;
7698                         goto quota_type_def;
7699                 case 'g':
7700                         qtype = GRPQUOTA;
7701                         rc = name2gid(&qctl->qc_id, optarg);
7702                         goto quota_type;
7703                 case 'P':
7704                         qctl->qc_cmd = LUSTRE_Q_SETDEFAULT;
7705                         qtype = PRJQUOTA;
7706                         qctl->qc_id = 0;
7707                         goto quota_type_def;
7708                 case 'p':
7709                         qtype = PRJQUOTA;
7710                         rc = name2projid(&qctl->qc_id, optarg);
7711 quota_type:
7712                         if (rc) {
7713                                 if (str2quotaid(&qctl->qc_id, optarg)) {
7714                                         fprintf(stderr,
7715                                                 "%s setquota: invalid id '%s'\n",
7716                                                 progname, optarg);
7717                                         rc = -1;
7718                                         goto out;
7719                                 }
7720                         }
7721
7722                         if (qctl->qc_id == 0) {
7723                                 fprintf(stderr,
7724                                         "%s setquota: can't set quota for root usr/group/project.\n",
7725                                         progname);
7726                                 rc = -1;
7727                                 goto out;
7728                         }
7729
7730 quota_type_def:
7731                         if (qctl->qc_type != ALLQUOTA) {
7732                                 fprintf(stderr,
7733                                         "%s setquota: only one of -u, -U, -g, -G, -p or -P may be specified\n",
7734                                         progname);
7735                                 rc = CMD_HELP;
7736                                 goto out;
7737                         }
7738                         qctl->qc_type = qtype;
7739                         break;
7740                 case 'd':
7741                         qctl->qc_cmd = LUSTRE_Q_SETDEFAULT;
7742                         use_default = true;
7743                         break;
7744                 case 'b':
7745                         ARG2ULL(dqb->dqb_bsoftlimit, optarg, 1024);
7746                         dqb->dqb_bsoftlimit >>= 10;
7747                         limit_mask |= BSLIMIT;
7748                         if (dqb->dqb_bsoftlimit &&
7749                             dqb->dqb_bsoftlimit <= 1024) /* <= 1M? */
7750                                 fprintf(stderr,
7751                                         "%s setquota: warning: block softlimit '%llu' smaller than minimum qunit size\nSee '%s help setquota' or Lustre manual for details\n",
7752                                         progname,
7753                                         (unsigned long long)dqb->dqb_bsoftlimit,
7754                                         progname);
7755                         break;
7756                 case 'B':
7757                         ARG2ULL(dqb->dqb_bhardlimit, optarg, 1024);
7758                         dqb->dqb_bhardlimit >>= 10;
7759                         limit_mask |= BHLIMIT;
7760                         if (dqb->dqb_bhardlimit &&
7761                             dqb->dqb_bhardlimit <= 1024) /* <= 1M? */
7762                                 fprintf(stderr,
7763                                         "%s setquota: warning: block hardlimit '%llu' smaller than minimum qunit size\n"
7764                                         "See '%s help setquota' or Lustre manual for details\n",
7765                                         progname,
7766                                         (unsigned long long)dqb->dqb_bhardlimit,
7767                                         progname);
7768                         break;
7769                 case 'i':
7770                         ARG2ULL(dqb->dqb_isoftlimit, optarg, 1);
7771                         limit_mask |= ISLIMIT;
7772                         if (dqb->dqb_isoftlimit &&
7773                             dqb->dqb_isoftlimit <= 1024) /* <= 1K inodes? */
7774                                 fprintf(stderr,
7775                                         "%s setquota: warning: inode softlimit '%llu' smaller than minimum qunit size\nSee '%s help setquota' or Lustre manual for details\n",
7776                                         progname,
7777                                         (unsigned long long)dqb->dqb_isoftlimit,
7778                                         progname);
7779                         break;
7780                 case 'I':
7781                         ARG2ULL(dqb->dqb_ihardlimit, optarg, 1);
7782                         limit_mask |= IHLIMIT;
7783                         if (dqb->dqb_ihardlimit &&
7784                             dqb->dqb_ihardlimit <= 1024) /* <= 1K inodes? */
7785                                 fprintf(stderr,
7786                                         "%s setquota: warning: inode hardlimit '%llu' smaller than minimum qunit size\nSee '%s help setquota' or Lustre manual for details\n",
7787                                         progname,
7788                                         (unsigned long long)dqb->dqb_ihardlimit,
7789                                         progname);
7790                         break;
7791                 case LFS_POOL_OPT:
7792                         if (lfs_verify_poolarg(optarg)) {
7793                                 rc = -1;
7794                                 goto out;
7795                         }
7796                         strncpy(qctl->qc_poolname, optarg, LOV_MAXPOOLNAME);
7797                         qctl->qc_cmd = qctl->qc_cmd == LUSTRE_Q_SETDEFAULT ?
7798                                                 LUSTRE_Q_SETDEFAULT_POOL :
7799                                                 LUSTRE_Q_SETQUOTAPOOL;
7800                         break;
7801                 default:
7802                         fprintf(stderr,
7803                                 "%s setquota: unrecognized option '%s'\n",
7804                                 progname, argv[optind - 1]);
7805                         /* fallthrough */
7806                 case 'h':
7807                         rc = CMD_HELP;
7808                         goto out;
7809                 }
7810         }
7811
7812         if (qctl->qc_type == ALLQUOTA) {
7813                 fprintf(stderr,
7814                         "%s setquota: either -u or -g must be specified\n",
7815                         progname);
7816                 rc = CMD_HELP;
7817                 goto out;
7818         }
7819
7820         if (!use_default && limit_mask == 0) {
7821                 fprintf(stderr,
7822                         "%s setquota: at least one limit must be specified\n",
7823                         progname);
7824                 rc = CMD_HELP;
7825                 goto out;
7826         }
7827
7828         if (use_default && limit_mask != 0) {
7829                 fprintf(stderr,
7830                         "%s setquota: limits should not be specified when using default quota\n",
7831                         progname);
7832                 rc = CMD_HELP;
7833                 goto out;
7834         }
7835
7836         if (use_default && qctl->qc_id == 0) {
7837                 fprintf(stderr,
7838                         "%s setquota: can not set default quota for root user/group/project\n",
7839                         progname);
7840                 rc = CMD_HELP;
7841                 goto out;
7842         }
7843
7844         if (optind != argc - 1) {
7845                 fprintf(stderr,
7846                         "%s setquota: filesystem not specified or unexpected argument '%s'\n",
7847                         progname, argv[optind]);
7848                 rc = CMD_HELP;
7849                 goto out;
7850         }
7851
7852         mnt = argv[optind];
7853
7854         if (use_default) {
7855                 dqb->dqb_bhardlimit = 0;
7856                 dqb->dqb_bsoftlimit = 0;
7857                 dqb->dqb_ihardlimit = 0;
7858                 dqb->dqb_isoftlimit = 0;
7859                 dqb->dqb_itime = 0;
7860                 dqb->dqb_btime = 0;
7861                 dqb->dqb_valid |= QIF_LIMITS | QIF_TIMES;
7862                 /* do not set inode limits for Pool Quotas */
7863                 if (qctl->qc_cmd  == LUSTRE_Q_SETDEFAULT_POOL)
7864                         dqb->dqb_valid ^= QIF_ILIMITS | QIF_ITIME;
7865         } else if ((!(limit_mask & BHLIMIT) ^ !(limit_mask & BSLIMIT)) ||
7866                    (!(limit_mask & IHLIMIT) ^ !(limit_mask & ISLIMIT))) {
7867                 /* sigh, we can't just set blimits/ilimits */
7868                 struct if_quotactl tmp_qctl = {.qc_cmd  = LUSTRE_Q_GETQUOTA,
7869                                                .qc_type = qctl->qc_type,
7870                                                .qc_id   = qctl->qc_id};
7871
7872                 rc = llapi_quotactl(mnt, &tmp_qctl);
7873                 if (rc < 0)
7874                         goto out;
7875
7876                 if (!(limit_mask & BHLIMIT))
7877                         dqb->dqb_bhardlimit = tmp_qctl.qc_dqblk.dqb_bhardlimit;
7878                 if (!(limit_mask & BSLIMIT))
7879                         dqb->dqb_bsoftlimit = tmp_qctl.qc_dqblk.dqb_bsoftlimit;
7880                 if (!(limit_mask & IHLIMIT))
7881                         dqb->dqb_ihardlimit = tmp_qctl.qc_dqblk.dqb_ihardlimit;
7882                 if (!(limit_mask & ISLIMIT))
7883                         dqb->dqb_isoftlimit = tmp_qctl.qc_dqblk.dqb_isoftlimit;
7884
7885                 /* Keep grace times if we have got no softlimit arguments */
7886                 if ((limit_mask & BHLIMIT) && !(limit_mask & BSLIMIT)) {
7887                         dqb->dqb_valid |= QIF_BTIME;
7888                         dqb->dqb_btime = tmp_qctl.qc_dqblk.dqb_btime;
7889                 }
7890
7891                 if ((limit_mask & IHLIMIT) && !(limit_mask & ISLIMIT)) {
7892                         dqb->dqb_valid |= QIF_ITIME;
7893                         dqb->dqb_itime = tmp_qctl.qc_dqblk.dqb_itime;
7894                 }
7895         }
7896
7897         dqb->dqb_valid |= (limit_mask & (BHLIMIT | BSLIMIT)) ? QIF_BLIMITS : 0;
7898         dqb->dqb_valid |= (limit_mask & (IHLIMIT | ISLIMIT)) ? QIF_ILIMITS : 0;
7899
7900         rc = llapi_quotactl(mnt, qctl);
7901         if (rc) {
7902                 if (*obd_type)
7903                         fprintf(stderr,
7904                                 "%s setquota: cannot quotactl '%s' '%s': %s\n",
7905                                 progname, obd_type,
7906                                 obd_uuid2str(&qctl->obd_uuid), strerror(-rc));
7907                 else
7908                         fprintf(stderr,
7909                                 "%s setquota: quotactl failed: %s\n",
7910                                 progname, strerror(-rc));
7911         }
7912 out:
7913         if (rc)
7914                 fprintf(stderr, "setquota failed: %s\n", strerror(-rc));
7915
7916         free(qctl);
7917         return rc;
7918 }
7919
7920 /* Converts seconds value into format string
7921  * result is returned in buf
7922  * Notes:
7923  *        1. result is in descenting order: 1w2d3h4m5s
7924  *        2. zero fields are not filled (except for p. 3): 5d1s
7925  *        3. zero seconds value is presented as "0s"
7926  */
7927 static char *__sec2str(time_t seconds, char *buf)
7928 {
7929         const char spec[] = "smhdw";
7930         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
7931         unsigned long c;
7932         char *tail = buf;
7933         int i;
7934
7935         for (i = ARRAY_SIZE(mult) - 1 ; i >= 0; i--) {
7936                 c = seconds / mult[i];
7937
7938                 if (c > 0 || (i == 0 && buf == tail))
7939                         tail += scnprintf(tail, 40-(tail-buf), "%lu%c", c,
7940                                           spec[i]);
7941
7942                 seconds %= mult[i];
7943         }
7944
7945         return tail;
7946 }
7947
7948 static void sec2str(time_t seconds, char *buf, int rc)
7949 {
7950         char *tail = buf;
7951
7952         if (rc)
7953                 *tail++ = '[';
7954
7955         tail = __sec2str(seconds, tail);
7956
7957         if (rc && tail - buf < 39) {
7958                 *tail++ = ']';
7959                 *tail++ = 0;
7960         }
7961 }
7962
7963 static void diff2str(time_t seconds, char *buf, time_t now)
7964 {
7965         buf[0] = 0;
7966         if (!seconds)
7967                 return;
7968         if (seconds <= now) {
7969                 strcpy(buf, "none");
7970                 return;
7971         }
7972         __sec2str(seconds - now, buf);
7973 }
7974
7975 static void print_quota_title(char *name, struct if_quotactl *qctl,
7976                               bool human_readable, bool show_default)
7977 {
7978         if (show_default) {
7979                 printf("Disk default %s quota:\n", qtype_name(qctl->qc_type));
7980                 printf("%15s %8s%8s%8s %8s%8s%8s\n",
7981                        "Filesystem", "bquota", "blimit", "bgrace",
7982                        "iquota", "ilimit", "igrace");
7983         } else {
7984                 printf("Disk quotas for %s %s (%cid %u):\n",
7985                        qtype_name(qctl->qc_type), name,
7986                        *qtype_name(qctl->qc_type), qctl->qc_id);
7987                 printf("%15s%8s %7s%8s%8s%8s %7s%8s%8s\n",
7988                        "Filesystem", human_readable ? "used" : "kbytes",
7989                        "quota", "limit", "grace",
7990                        "files", "quota", "limit", "grace");
7991         }
7992 }
7993
7994 static void kbytes2str(__u64 num, char *buf, int buflen, bool h)
7995 {
7996         if (!h) {
7997                 snprintf(buf, buflen, "%ju", (uintmax_t)num);
7998         } else {
7999                 if (num >> 40)
8000                         snprintf(buf, buflen, "%5.4gP",
8001                                  (double)num / ((__u64)1 << 40));
8002                 else if (num >> 30)
8003                         snprintf(buf, buflen, "%5.4gT",
8004                                  (double)num / (1 << 30));
8005                 else if (num >> 20)
8006                         snprintf(buf, buflen, "%5.4gG",
8007                                  (double)num / (1 << 20));
8008                 else if (num >> 10)
8009                         snprintf(buf, buflen, "%5.4gM",
8010                                  (double)num / (1 << 10));
8011                 else
8012                         snprintf(buf, buflen, "%ju%s", (uintmax_t)num, "k");
8013         }
8014 }
8015
8016 #ifdef HAVE_NATIVE_CLIENT
8017 /* In the current Lustre implementation, the grace time is either the time
8018  * or the timestamp to be used after some quota ID exceeds the soft limt,
8019  * 48 bits should be enough, its high 16 bits can be used as quota flags.
8020  */
8021 #define LQUOTA_GRACE_BITS       48
8022 #define LQUOTA_GRACE_MASK       ((1ULL << LQUOTA_GRACE_BITS) - 1)
8023 #define LQUOTA_GRACE_MAX        LQUOTA_GRACE_MASK
8024 #define LQUOTA_GRACE(t)         (t & LQUOTA_GRACE_MASK)
8025 #define LQUOTA_FLAG(t)          (t >> LQUOTA_GRACE_BITS)
8026 #define LQUOTA_GRACE_FLAG(t, f) ((__u64)t | (__u64)f << LQUOTA_GRACE_BITS)
8027 #endif
8028
8029 #define STRBUF_LEN      24
8030 static void print_quota(char *mnt, struct if_quotactl *qctl, int type,
8031                         int rc, bool h, bool show_default)
8032 {
8033         time_t now;
8034
8035         time(&now);
8036
8037         if (qctl->qc_cmd == LUSTRE_Q_GETQUOTA || qctl->qc_cmd == Q_GETOQUOTA ||
8038             qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL ||
8039             qctl->qc_cmd == LUSTRE_Q_GETDEFAULT ||
8040             qctl->qc_cmd == LUSTRE_Q_GETDEFAULT_POOL) {
8041                 int bover = 0, iover = 0;
8042                 struct obd_dqblk *dqb = &qctl->qc_dqblk;
8043                 char numbuf[3][STRBUF_LEN + 2]; /* 2 for brackets or wildcard */
8044                 char timebuf[40];
8045                 char strbuf[STRBUF_LEN];
8046
8047                 if (dqb->dqb_bhardlimit &&
8048                     lustre_stoqb(dqb->dqb_curspace) >= dqb->dqb_bhardlimit) {
8049                         bover = 1;
8050                 } else if (dqb->dqb_bsoftlimit && dqb->dqb_btime) {
8051                         if (dqb->dqb_btime > now)
8052                                 bover = 2;
8053                         else
8054                                 bover = 3;
8055                 }
8056
8057                 if (dqb->dqb_ihardlimit &&
8058                     dqb->dqb_curinodes >= dqb->dqb_ihardlimit) {
8059                         iover = 1;
8060                 } else if (dqb->dqb_isoftlimit && dqb->dqb_itime) {
8061                         if (dqb->dqb_itime > now)
8062                                 iover = 2;
8063                         else
8064                                 iover = 3;
8065                 }
8066
8067                 if (strlen(mnt) > 15)
8068                         printf("%s\n%15s", mnt, "");
8069                 else
8070                         printf("%15s", mnt);
8071
8072                 if (bover)
8073                         diff2str(dqb->dqb_btime, timebuf, now);
8074                 else if (show_default)
8075                         snprintf(timebuf, sizeof(timebuf), "%llu",
8076                                  (unsigned long long)dqb->dqb_btime);
8077
8078                 kbytes2str(lustre_stoqb(dqb->dqb_curspace),
8079                            strbuf, sizeof(strbuf), h);
8080                 if (rc == -EREMOTEIO)
8081                         sprintf(numbuf[0], "%s*", strbuf);
8082                 else
8083                         sprintf(numbuf[0], (dqb->dqb_valid & QIF_SPACE) ?
8084                                 "%s" : "[%s]", strbuf);
8085
8086                 kbytes2str(dqb->dqb_bsoftlimit, strbuf, sizeof(strbuf), h);
8087                 if (type == QC_GENERAL)
8088                         sprintf(numbuf[1], (dqb->dqb_valid & QIF_BLIMITS) ?
8089                                 "%s" : "[%s]", strbuf);
8090                 else
8091                         sprintf(numbuf[1], "%s", "-");
8092
8093                 kbytes2str(dqb->dqb_bhardlimit, strbuf, sizeof(strbuf), h);
8094                 sprintf(numbuf[2], (dqb->dqb_valid & QIF_BLIMITS) ?
8095                         "%s" : "[%s]", strbuf);
8096
8097                 if (show_default)
8098                         printf(" %6s %7s %7s", numbuf[1], numbuf[2], timebuf);
8099                 else
8100                         printf(" %7s%c %6s %7s %7s",
8101                                numbuf[0], bover ? '*' : ' ', numbuf[1],
8102                                numbuf[2], bover > 1 ? timebuf : "-");
8103
8104                 if (iover)
8105                         diff2str(dqb->dqb_itime, timebuf, now);
8106                 else if (show_default)
8107                         snprintf(timebuf, sizeof(timebuf), "%llu",
8108                                  (unsigned long long)dqb->dqb_itime);
8109
8110                 snprintf(numbuf[0], sizeof(numbuf),
8111                          (dqb->dqb_valid & QIF_INODES) ? "%ju" : "[%ju]",
8112                          (uintmax_t)dqb->dqb_curinodes);
8113
8114                 if (type == QC_GENERAL)
8115                         sprintf(numbuf[1], (dqb->dqb_valid & QIF_ILIMITS) ?
8116                                 "%ju" : "[%ju]",
8117                                 (uintmax_t)dqb->dqb_isoftlimit);
8118                 else
8119                         sprintf(numbuf[1], "%s", "-");
8120
8121                 sprintf(numbuf[2], (dqb->dqb_valid & QIF_ILIMITS) ?
8122                         "%ju" : "[%ju]", (uintmax_t)dqb->dqb_ihardlimit);
8123
8124                 if (show_default)
8125                         printf(" %6s %7s %7s", numbuf[1], numbuf[2], timebuf);
8126                 else if (type != QC_OSTIDX)
8127                         printf(" %7s%c %6s %7s %7s",
8128                                numbuf[0], iover ? '*' : ' ', numbuf[1],
8129                                numbuf[2], iover > 1 ? timebuf : "-");
8130                 else
8131                         printf(" %7s %7s %7s %7s", "-", "-", "-", "-");
8132                 printf("\n");
8133         } else if (qctl->qc_cmd == LUSTRE_Q_GETINFO || LUSTRE_Q_GETINFOPOOL ||
8134                    qctl->qc_cmd == Q_GETOINFO) {
8135                 char bgtimebuf[40];
8136                 char igtimebuf[40];
8137
8138                 if (qctl->qc_dqinfo.dqi_bgrace == NOTIFY_GRACE_TIME)
8139                         strncpy(bgtimebuf, NOTIFY_GRACE, 40);
8140                 else
8141                         sec2str(qctl->qc_dqinfo.dqi_bgrace, bgtimebuf, rc);
8142                 if (qctl->qc_dqinfo.dqi_igrace == NOTIFY_GRACE_TIME)
8143                         strncpy(igtimebuf, NOTIFY_GRACE, 40);
8144                 else
8145                         sec2str(qctl->qc_dqinfo.dqi_igrace, igtimebuf, rc);
8146
8147                 printf("Block grace time: %s; Inode grace time: %s\n",
8148                        bgtimebuf, igtimebuf);
8149         }
8150 }
8151
8152 static int tgt_name2index(const char *tgtname, unsigned int *idx)
8153 {
8154         char *dash, *endp;
8155
8156         /* format is "lustre-OST0001" */
8157         dash = memchr(tgtname, '-', LUSTRE_MAXFSNAME + 1);
8158         if (!dash) {
8159                 fprintf(stderr, "wrong tgtname format '%s'\n", tgtname);
8160                 return -EINVAL;
8161         }
8162         dash += 4;
8163
8164         *idx = strtoul(dash, &endp, 16);
8165         if (*idx > 0xffff) {
8166                 fprintf(stderr, "wrong index %s\n", tgtname);
8167                 return -ERANGE;
8168         }
8169
8170         return 0;
8171 }
8172
8173 static int print_obd_quota(char *mnt, struct if_quotactl *qctl, int is_mdt,
8174                            bool h, __u64 *total)
8175 {
8176         int rc = 0, rc1 = 0, count = 0, i = 0;
8177         char **list = NULL, *buffer = NULL;
8178         __u32 valid = qctl->qc_valid;
8179
8180         if (qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL && is_mdt)
8181                 return 0;
8182
8183         /* Is it correct for the case OST0000, OST0002, OST0003 -
8184          * we will ask OST0001 that is absent and won't ask OST0003? */
8185         rc = llapi_get_obd_count(mnt, &count, is_mdt);
8186         if (rc) {
8187                 fprintf(stderr, "can not get %s count: %s\n",
8188                         is_mdt ? "mdt" : "ost", strerror(-rc));
8189                 return rc;
8190         }
8191
8192         if (qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL) {
8193                 char fname[PATH_MAX];
8194                 char fsname[LUSTRE_MAXFSNAME + 1];
8195                 int bufsize = sizeof(struct obd_uuid) * count;
8196
8197                 rc = llapi_search_fsname(mnt, fsname);
8198                 if (rc) {
8199                         fprintf(stderr, "cannot get fsname for mountpoint %s\n",
8200                                 mnt);
8201                         goto out;
8202                 }
8203                 buffer = malloc(bufsize + sizeof(*list) * count);
8204                 if (!buffer)
8205                         return -ENOMEM;
8206                 list = (char **)(buffer + bufsize);
8207                 snprintf(fname, PATH_MAX, "%s.%s", fsname, qctl->qc_poolname);
8208                 count = llapi_get_poolmembers(fname, list, count,
8209                                               buffer, bufsize);
8210                 if (count <= 0)
8211                         goto out;
8212         }
8213
8214         for (i = 0; i < count; i++) {
8215                 if (qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL) {
8216                         unsigned int index;
8217
8218                         if (tgt_name2index(list[i], &index))
8219                                 continue;
8220                         qctl->qc_idx = index;
8221                 } else {
8222                         qctl->qc_idx = i;
8223                 }
8224
8225                 qctl->qc_valid = is_mdt ? QC_MDTIDX : QC_OSTIDX;
8226                 rc = llapi_quotactl(mnt, qctl);
8227                 if (rc) {
8228                         /* It is remote client case. */
8229                         if (rc == -EOPNOTSUPP) {
8230                                 rc = 0;
8231                                 goto out;
8232                         }
8233
8234                         if (!rc1)
8235                                 rc1 = rc;
8236                         fprintf(stderr, "quotactl %s%d failed.\n",
8237                                 is_mdt ? "mdt" : "ost", qctl->qc_idx);
8238                         continue;
8239                 }
8240
8241                 print_quota(obd_uuid2str(&qctl->obd_uuid), qctl,
8242                             qctl->qc_valid, 0, h, false);
8243                 *total += is_mdt ? qctl->qc_dqblk.dqb_ihardlimit :
8244                                    qctl->qc_dqblk.dqb_bhardlimit;
8245         }
8246 out:
8247         if (buffer)
8248                 free(buffer);
8249         qctl->qc_valid = valid;
8250         return rc ? : rc1;
8251 }
8252
8253 static int get_print_quota(char *mnt, char *name, struct if_quotactl *qctl,
8254                            int verbose, int quiet, bool human_readable,
8255                            bool show_default)
8256 {
8257         int rc1 = 0, rc2 = 0, rc3 = 0;
8258         char *obd_type = (char *)qctl->obd_type;
8259         char *obd_uuid = (char *)qctl->obd_uuid.uuid;
8260         __u64 total_ialloc = 0, total_balloc = 0;
8261         bool use_default_for_blk = false;
8262         bool use_default_for_file = false;
8263         int inacc;
8264
8265         rc1 = llapi_quotactl(mnt, qctl);
8266         if (rc1 < 0) {
8267                 switch (rc1) {
8268                 case -ESRCH:
8269                         fprintf(stderr, "%s quotas are not enabled.\n",
8270                                 qtype_name(qctl->qc_type));
8271                         goto out;
8272                 case -EPERM:
8273                         fprintf(stderr, "Permission denied.\n");
8274                 case -ENODEV:
8275                 case -ENOENT:
8276                         /* We already got error message. */
8277                         goto out;
8278                 default:
8279                         fprintf(stderr, "Unexpected quotactl error: %s\n",
8280                                 strerror(-rc1));
8281                 }
8282         }
8283
8284         if (!show_default && qctl->qc_id == 0) {
8285                 qctl->qc_dqblk.dqb_bhardlimit = 0;
8286                 qctl->qc_dqblk.dqb_bsoftlimit = 0;
8287                 qctl->qc_dqblk.dqb_ihardlimit = 0;
8288                 qctl->qc_dqblk.dqb_isoftlimit = 0;
8289                 qctl->qc_dqblk.dqb_btime = 0;
8290                 qctl->qc_dqblk.dqb_itime = 0;
8291                 qctl->qc_dqblk.dqb_valid |= QIF_LIMITS | QIF_TIMES;
8292         }
8293
8294         if (qctl->qc_dqblk.dqb_valid & QIF_BTIME &&
8295             LQUOTA_FLAG(qctl->qc_dqblk.dqb_btime) & LQUOTA_FLAG_DEFAULT) {
8296                 use_default_for_blk = true;
8297                 qctl->qc_dqblk.dqb_btime &= LQUOTA_GRACE_MASK;
8298         }
8299
8300         if (qctl->qc_dqblk.dqb_valid & QIF_ITIME &&
8301             LQUOTA_FLAG(qctl->qc_dqblk.dqb_itime) & LQUOTA_FLAG_DEFAULT) {
8302                 use_default_for_file = true;
8303                 qctl->qc_dqblk.dqb_itime &= LQUOTA_GRACE_MASK;
8304         }
8305
8306         if ((qctl->qc_cmd == LUSTRE_Q_GETQUOTA ||
8307              qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL ||
8308              qctl->qc_cmd == LUSTRE_Q_GETDEFAULT_POOL ||
8309              qctl->qc_cmd == LUSTRE_Q_GETDEFAULT) && !quiet)
8310                 print_quota_title(name, qctl, human_readable, show_default);
8311
8312         if (rc1 && *obd_type)
8313                 fprintf(stderr, "%s %s ", obd_type, obd_uuid);
8314
8315         if (qctl->qc_valid != QC_GENERAL)
8316                 mnt = "";
8317
8318         inacc = (qctl->qc_cmd == LUSTRE_Q_GETQUOTA ||
8319                  qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL) &&
8320                 ((qctl->qc_dqblk.dqb_valid & (QIF_LIMITS|QIF_USAGE)) !=
8321                  (QIF_LIMITS|QIF_USAGE));
8322
8323         print_quota(mnt, qctl, QC_GENERAL, rc1, human_readable, show_default);
8324
8325         if (!show_default && verbose &&
8326             qctl->qc_valid == QC_GENERAL && qctl->qc_cmd != LUSTRE_Q_GETINFO &&
8327             qctl->qc_cmd != LUSTRE_Q_GETINFOPOOL) {
8328                 char strbuf[STRBUF_LEN];
8329
8330                 rc2 = print_obd_quota(mnt, qctl, 1, human_readable,
8331                                       &total_ialloc);
8332                 rc3 = print_obd_quota(mnt, qctl, 0, human_readable,
8333                                       &total_balloc);
8334                 kbytes2str(total_balloc, strbuf, sizeof(strbuf),
8335                            human_readable);
8336                 printf("Total allocated inode limit: %ju, total allocated block limit: %s\n",
8337                        (uintmax_t)total_ialloc, strbuf);
8338         }
8339
8340         if (use_default_for_blk)
8341                 printf("%cid %u is using default block quota setting\n",
8342                        *qtype_name(qctl->qc_type), qctl->qc_id);
8343
8344         if (use_default_for_file)
8345                 printf("%cid %u is using default file quota setting\n",
8346                        *qtype_name(qctl->qc_type), qctl->qc_id);
8347
8348         if (rc1 || rc2 || rc3 || inacc)
8349                 printf("Some errors happened when getting quota info. Some devices may be not working or deactivated. The data in \"[]\" is inaccurate.\n");
8350 out:
8351         if (rc1)
8352                 return rc1;
8353         if (rc2)
8354                 return rc2;
8355         if (rc3)
8356                 return rc3;
8357         if (inacc)
8358                 return -EIO;
8359
8360         return 0;
8361 }
8362
8363 static int lfs_project(int argc, char **argv)
8364 {
8365         int ret = 0, err = 0, c, i;
8366         struct project_handle_control phc = { 0 };
8367         enum lfs_project_ops_t op;
8368
8369         phc.newline = true;
8370         phc.assign_projid = false;
8371         /* default action */
8372         op = LFS_PROJECT_LIST;
8373
8374         while ((c = getopt(argc, argv, "p:cCsdkr0")) != -1) {
8375                 switch (c) {
8376                 case 'c':
8377                         if (op != LFS_PROJECT_LIST) {
8378                                 fprintf(stderr,
8379                                         "%s: cannot specify '-c' '-C' '-s' together\n",
8380                                         progname);
8381                                 return CMD_HELP;
8382                         }
8383
8384                         op = LFS_PROJECT_CHECK;
8385                         break;
8386                 case 'C':
8387                         if (op != LFS_PROJECT_LIST) {
8388                                 fprintf(stderr,
8389                                         "%s: cannot specify '-c' '-C' '-s' together\n",
8390                                         progname);
8391                                 return CMD_HELP;
8392                         }
8393
8394                         op = LFS_PROJECT_CLEAR;
8395                         break;
8396                 case 's':
8397                         if (op != LFS_PROJECT_LIST) {
8398                                 fprintf(stderr,
8399                                         "%s: cannot specify '-c' '-C' '-s' together\n",
8400                                         progname);
8401                                 return CMD_HELP;
8402                         }
8403
8404                         phc.set_inherit = true;
8405                         op = LFS_PROJECT_SET;
8406                         break;
8407                 case 'd':
8408                         phc.dironly = true;
8409                         break;
8410                 case 'k':
8411                         phc.keep_projid = true;
8412                         break;
8413                 case 'r':
8414                         phc.recursive = true;
8415                         break;
8416                 case 'p':
8417                         if (str2quotaid(&phc.projid, optarg)) {
8418                                 fprintf(stderr,
8419                                         "Invalid project ID: %s\n",
8420                                         optarg);
8421                                 return CMD_HELP;
8422                         }
8423
8424                         phc.assign_projid = true;
8425
8426                         break;
8427                 case '0':
8428                         phc.newline = false;
8429                         break;
8430                 default:
8431                         fprintf(stderr, "%s: invalid option '%c'\n",
8432                                 progname, optopt);
8433                         return CMD_HELP;
8434                 }
8435         }
8436
8437         if (phc.assign_projid && op == LFS_PROJECT_LIST) {
8438                 op = LFS_PROJECT_SET;
8439                 phc.set_projid = true;
8440         } else if (phc.assign_projid && op == LFS_PROJECT_SET) {
8441                 phc.set_projid = true;
8442         }
8443
8444         switch (op) {
8445         case LFS_PROJECT_CHECK:
8446                 if (phc.keep_projid) {
8447                         fprintf(stderr,
8448                                 "%s: '-k' is useless together with '-c'\n",
8449                                 progname);
8450                         return CMD_HELP;
8451                 }
8452                 break;
8453         case LFS_PROJECT_CLEAR:
8454                 if (!phc.newline) {
8455                         fprintf(stderr,
8456                                 "%s: '-0' is useless together with '-C'\n",
8457                                 progname);
8458                         return CMD_HELP;
8459                 }
8460                 if (phc.assign_projid) {
8461                         fprintf(stderr,
8462                                 "%s: '-p' is useless together with '-C'\n",
8463                                 progname);
8464                         return CMD_HELP;
8465                 }
8466                 break;
8467         case LFS_PROJECT_SET:
8468                 if (!phc.newline) {
8469                         fprintf(stderr,
8470                                 "%s: '-0' is useless together with '-s'\n",
8471                                 progname);
8472                         return CMD_HELP;
8473                 }
8474                 if (phc.keep_projid) {
8475                         fprintf(stderr,
8476                                 "%s: '-k' is useless together with '-s'\n",
8477                                 progname);
8478                         return CMD_HELP;
8479                 }
8480                 break;
8481         default:
8482                 if (!phc.newline) {
8483                         fprintf(stderr,
8484                                 "%s: '-0' is useless for list operations\n",
8485                                 progname);
8486                         return CMD_HELP;
8487                 }
8488                 break;
8489         }
8490
8491         argv += optind;
8492         argc -= optind;
8493         if (argc == 0) {
8494                 fprintf(stderr, "%s: missing file or directory target(s)\n",
8495                         progname);
8496                 return CMD_HELP;
8497         }
8498
8499         for (i = 0; i < argc; i++) {
8500                 switch (op) {
8501                 case LFS_PROJECT_CHECK:
8502                         err = lfs_project_check(argv[i], &phc);
8503                         break;
8504                 case LFS_PROJECT_LIST:
8505                         err = lfs_project_list(argv[i], &phc);
8506                         break;
8507                 case LFS_PROJECT_CLEAR:
8508                         err = lfs_project_clear(argv[i], &phc);
8509                         break;
8510                 case LFS_PROJECT_SET:
8511                         err = lfs_project_set(argv[i], &phc);
8512                         break;
8513                 default:
8514                         break;
8515                 }
8516                 if (err && !ret)
8517                         ret = err;
8518         }
8519
8520         return ret;
8521 }
8522
8523 static int lfs_quota(int argc, char **argv)
8524 {
8525         int c;
8526         char *mnt, *name = NULL;
8527         struct if_quotactl *qctl;
8528         char *obd_uuid;
8529         int rc = 0, rc1 = 0, verbose = 0, quiet = 0;
8530         __u32 valid = QC_GENERAL, idx = 0;
8531         bool human_readable = false;
8532         bool show_default = false;
8533         int qtype;
8534         bool show_pools = false;
8535         struct option long_opts[] = {
8536         { .val = LFS_POOL_OPT, .name = "pool", .has_arg = optional_argument },
8537         { .name = NULL } };
8538         char **poollist = NULL;
8539         char *buf = NULL;
8540         int poolcount, i;
8541
8542         qctl = calloc(1, sizeof(*qctl) + LOV_MAXPOOLNAME + 1);
8543         if (!qctl)
8544                 return -ENOMEM;
8545
8546         qctl->qc_cmd = LUSTRE_Q_GETQUOTA;
8547         qctl->qc_type = ALLQUOTA;
8548         obd_uuid = (char *)qctl->obd_uuid.uuid;
8549
8550         while ((c = getopt_long(argc, argv, "gGi:I:o:pPqtuUvh",
8551                 long_opts, NULL)) != -1) {
8552                 switch (c) {
8553                 case 'U':
8554                         show_default = true;
8555                 case 'u':
8556                         qtype = USRQUOTA;
8557                         goto quota_type;
8558                 case 'G':
8559                         show_default = true;
8560                 case 'g':
8561                         qtype = GRPQUOTA;
8562                         goto quota_type;
8563                 case 'P':
8564                         show_default = true;
8565                 case 'p':
8566                         qtype = PRJQUOTA;
8567 quota_type:
8568                         if (qctl->qc_type != ALLQUOTA) {
8569                                 fprintf(stderr,
8570                                         "%s quota: only one of -u, -g, or -p may be specified\n",
8571                                         progname);
8572                                 rc = CMD_HELP;
8573                                 goto out;
8574                         }
8575                         qctl->qc_type = qtype;
8576                         break;
8577                 case 't':
8578                         qctl->qc_cmd = LUSTRE_Q_GETINFO;
8579                         break;
8580                 case 'o':
8581                         valid = qctl->qc_valid = QC_UUID;
8582                         snprintf(obd_uuid, sizeof(*obd_uuid), "%s", optarg);
8583                         break;
8584                 case 'i':
8585                         valid = qctl->qc_valid = QC_MDTIDX;
8586                         idx = qctl->qc_idx = atoi(optarg);
8587                         if (idx == 0 && *optarg != '0') {
8588                                 fprintf(stderr,
8589                                         "%s quota: invalid MDT index '%s'\n",
8590                                         progname, optarg);
8591                                 rc = CMD_HELP;
8592                                 goto out;
8593                         }
8594                         break;
8595                 case 'I':
8596                         valid = qctl->qc_valid = QC_OSTIDX;
8597                         idx = qctl->qc_idx = atoi(optarg);
8598                         if (idx == 0 && *optarg != '0') {
8599                                 fprintf(stderr,
8600                                         "%s quota: invalid OST index '%s'\n",
8601                                         progname, optarg);
8602                                 rc = CMD_HELP;
8603                                 goto out;
8604                         }
8605                         break;
8606                 case 'v':
8607                         verbose = 1;
8608                         break;
8609                 case 'q':
8610                         quiet = 1;
8611                         break;
8612                 case 'h':
8613                         human_readable = true;
8614                         break;
8615                 case LFS_POOL_OPT:
8616                         if ((!optarg) && (argv[optind] != NULL) &&
8617                                 (argv[optind][0] != '-') &&
8618                                 (argv[optind][0] != '/')) {
8619                                 optarg = argv[optind++];
8620                                 if (lfs_verify_poolarg(optarg)) {
8621                                         rc = -EINVAL;
8622                                         goto out;
8623                                 }
8624                                 strncpy(qctl->qc_poolname, optarg,
8625                                         LOV_MAXPOOLNAME);
8626                                 if (qctl->qc_cmd == LUSTRE_Q_GETINFO)
8627                                         qctl->qc_cmd = LUSTRE_Q_GETINFOPOOL;
8628                                 else
8629                                         qctl->qc_cmd = LUSTRE_Q_GETQUOTAPOOL;
8630                                 break;
8631                         }
8632
8633                         /* optarg is NULL */
8634                         show_pools = true;
8635                         qctl->qc_cmd = LUSTRE_Q_GETQUOTAPOOL;
8636                         break;
8637                 default:
8638                         fprintf(stderr, "%s quota: unrecognized option '%s'\n",
8639                                 progname, argv[optind - 1]);
8640                         rc = CMD_HELP;
8641                         goto out;
8642                 }
8643         }
8644
8645         /* current uid/gid info for "lfs quota /path/to/lustre/mount" */
8646         if ((qctl->qc_cmd == LUSTRE_Q_GETQUOTA ||
8647              qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL) &&
8648              qctl->qc_type == ALLQUOTA &&
8649              optind == argc - 1 && !show_default) {
8650                 qctl->qc_idx = idx;
8651
8652                 for (qtype = USRQUOTA; qtype <= GRPQUOTA; qtype++) {
8653                         qctl->qc_type = qtype;
8654                         qctl->qc_valid = valid;
8655                         if (qtype == USRQUOTA) {
8656                                 qctl->qc_id = geteuid();
8657                                 rc = uid2name(&name, qctl->qc_id);
8658                         } else {
8659                                 qctl->qc_id = getegid();
8660                                 rc = gid2name(&name, qctl->qc_id);
8661                                 memset(&qctl->qc_dqblk, 0,
8662                                        sizeof(qctl->qc_dqblk));
8663                         }
8664                         if (rc)
8665                                 name = "<unknown>";
8666                         mnt = argv[optind];
8667                         rc1 = get_print_quota(mnt, name, qctl, verbose, quiet,
8668                                               human_readable, show_default);
8669                         if (rc1 && !rc)
8670                                 rc = rc1;
8671                 }
8672                 goto out;
8673         /* lfs quota -u username /path/to/lustre/mount */
8674         } else if (qctl->qc_cmd == LUSTRE_Q_GETQUOTA ||
8675                    qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL) {
8676                 /* options should be followed by u/g-name and mntpoint */
8677                 if ((!show_default && optind + 2 != argc) ||
8678                     (show_default && optind + 1 != argc) ||
8679                     qctl->qc_type == ALLQUOTA) {
8680                         fprintf(stderr,
8681                                 "%s quota: name and mount point must be specified\n",
8682                                 progname);
8683                         rc = CMD_HELP;
8684                         goto out;
8685                 }
8686
8687                 if (!show_default) {
8688                         name = argv[optind++];
8689                         switch (qctl->qc_type) {
8690                         case USRQUOTA:
8691                                 rc = name2uid(&qctl->qc_id, name);
8692                                 break;
8693                         case GRPQUOTA:
8694                                 rc = name2gid(&qctl->qc_id, name);
8695                                 break;
8696                         case PRJQUOTA:
8697                                 rc = name2projid(&qctl->qc_id, name);
8698                                 break;
8699                         default:
8700                                 rc = -ENOTSUP;
8701                                 break;
8702                         }
8703                 } else {
8704                         qctl->qc_valid = QC_GENERAL;
8705                         qctl->qc_cmd = qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL ?
8706                                         LUSTRE_Q_GETDEFAULT_POOL :
8707                                         LUSTRE_Q_GETDEFAULT;
8708                         qctl->qc_id = 0;
8709                 }
8710
8711                 if (rc) {
8712                         if (str2quotaid(&qctl->qc_id, name)) {
8713                                 fprintf(stderr, "%s quota: invalid id '%s'\n",
8714                                         progname, name);
8715                                 rc = CMD_HELP;
8716                                 goto out;
8717                         }
8718                 }
8719         } else if (optind + 1 != argc || qctl->qc_type == ALLQUOTA) {
8720                 fprintf(stderr, "%s quota: missing quota info argument(s)\n",
8721                         progname);
8722                 rc = CMD_HELP;
8723                 goto out;
8724         }
8725
8726         mnt = argv[optind];
8727         if (show_pools) {
8728                 char *p;
8729
8730                 i = 0;
8731                 rc = llapi_get_poolbuf(mnt, &buf, &poollist, &poolcount);
8732                 if (rc)
8733                         goto out;
8734
8735                 for (i = 0; i < poolcount; i++) {
8736                         p = memchr(poollist[i], '.', MAXNAMLEN);
8737                         if (!p) {
8738                                 fprintf(stderr, "bad string format %.*s\n",
8739                                         MAXNAMLEN, poollist[i]);
8740                                 rc = -EINVAL;
8741                                 goto out;
8742                         }
8743                         p++;
8744                         printf("Quotas for pool: %s\n", p);
8745                         strncpy(qctl->qc_poolname, p, LOV_MAXPOOLNAME);
8746                         rc = get_print_quota(mnt, name, qctl, verbose, quiet,
8747                                              human_readable, show_default);
8748                         if (rc)
8749                                 break;
8750                 }
8751                 goto out;
8752         }
8753
8754         rc = get_print_quota(mnt, name, qctl, verbose, quiet,
8755                              human_readable, show_default);
8756 out:
8757         free(buf);
8758         free(qctl);
8759         return rc;
8760 }
8761 #endif /* HAVE_SYS_QUOTA_H! */
8762
8763 static int flushctx_ioctl(char *mp)
8764 {
8765         int fd, rc;
8766
8767         fd = open(mp, O_RDONLY);
8768         if (fd == -1) {
8769                 fprintf(stderr, "flushctx: error open %s: %s\n",
8770                         mp, strerror(errno));
8771                 return -1;
8772         }
8773
8774         rc = ioctl(fd, LL_IOC_FLUSHCTX);
8775         if (rc == -1)
8776                 fprintf(stderr, "flushctx: error ioctl %s: %s\n",
8777                         mp, strerror(errno));
8778
8779         close(fd);
8780         return rc;
8781 }
8782
8783 static int lfs_flushctx(int argc, char **argv)
8784 {
8785         int     kdestroy = 0, reap = 0, c;
8786         char    mntdir[PATH_MAX] = {'\0'};
8787         int     index = 0;
8788         int     rc = 0;
8789
8790         while ((c = getopt(argc, argv, "kr")) != -1) {
8791                 switch (c) {
8792                 case 'k':
8793                         kdestroy = 1;
8794                         break;
8795                 case 'r':
8796                         reap = 1;
8797                         break;
8798                 default:
8799                         fprintf(stderr,
8800                                 "error: %s: option '-%c' unrecognized\n",
8801                                 argv[0], c);
8802                         return CMD_HELP;
8803                 }
8804         }
8805
8806         if (kdestroy) {
8807                 rc = system("kdestroy > /dev/null");
8808                 if (rc) {
8809                         rc = WEXITSTATUS(rc);
8810                         fprintf(stderr,
8811                                 "error destroying tickets: %d, continuing\n",
8812                                 rc);
8813                 }
8814         }
8815
8816         if (optind >= argc) {
8817                 /* flush for all mounted lustre fs. */
8818                 while (!llapi_search_mounts(NULL, index++, mntdir, NULL)) {
8819                         /* Check if we have a mount point */
8820                         if (mntdir[0] == '\0')
8821                                 continue;
8822
8823                         if (flushctx_ioctl(mntdir))
8824                                 rc = -1;
8825
8826                         mntdir[0] = '\0'; /* avoid matching in next loop */
8827                 }
8828         } else {
8829                 /* flush fs as specified */
8830                 while (optind < argc) {
8831                         if (flushctx_ioctl(argv[optind++]))
8832                                 rc = -1;
8833                 }
8834         }
8835
8836         if (reap) {
8837                 rc = system("keyctl reap > /dev/null");
8838                 if (rc != 0) {
8839                         rc = WEXITSTATUS(rc);
8840                         fprintf(stderr, "error reaping keyring: %d\n", rc);
8841                 }
8842         }
8843
8844         return rc;
8845 }
8846
8847 static int lfs_changelog(int argc, char **argv)
8848 {
8849         void *changelog_priv;
8850         struct changelog_rec *rec;
8851         long long startrec = 0, endrec = 0;
8852         char *mdd;
8853         struct option long_opts[] = {
8854                 { .val = 'f', .name = "follow", .has_arg = no_argument },
8855                 { .name = NULL } };
8856         char short_opts[] = "f";
8857         int rc, follow = 0;
8858
8859         while ((rc = getopt_long(argc, argv, short_opts,
8860                 long_opts, NULL)) != -1) {
8861                 switch (rc) {
8862                 case 'f':
8863                         follow++;
8864                         break;
8865                 default:
8866                         fprintf(stderr,
8867                                 "%s changelog: unrecognized option '%s'\n",
8868                                 progname, argv[optind - 1]);
8869                         return CMD_HELP;
8870                 }
8871         }
8872         if (optind >= argc) {
8873                 fprintf(stderr, "%s changelog: mdtname must be specified\n",
8874                         progname);
8875                 return CMD_HELP;
8876         }
8877
8878         mdd = argv[optind++];
8879         if (argc > optind) {
8880                 errno = 0;
8881                 startrec = strtoll(argv[optind++], NULL, 10);
8882                 if (errno != 0 || startrec < 0) {
8883                         fprintf(stderr,
8884                                 "%s changelog: bad startrec\n",
8885                                 progname);
8886                         return CMD_HELP;
8887                 }
8888         }
8889
8890         if (argc > optind) {
8891                 errno = 0;
8892                 endrec = strtoll(argv[optind++], NULL, 10);
8893                 if (errno != 0 || endrec < 0) {
8894                         fprintf(stderr,
8895                                 "%s changelog: bad endrec\n",
8896                                 progname);
8897                         return CMD_HELP;
8898                 }
8899         }
8900
8901         rc = llapi_changelog_start(&changelog_priv,
8902                                    CHANGELOG_FLAG_BLOCK |
8903                                    CHANGELOG_FLAG_JOBID |
8904                                    CHANGELOG_FLAG_EXTRA_FLAGS |
8905                                    (follow ? CHANGELOG_FLAG_FOLLOW : 0),
8906                                    mdd, startrec);
8907         if (rc < 0) {
8908                 fprintf(stderr, "%s changelog: cannot start changelog: %s\n",
8909                         progname, strerror(errno = -rc));
8910                 return rc;
8911         }
8912
8913         rc = llapi_changelog_set_xflags(changelog_priv,
8914                                         CHANGELOG_EXTRA_FLAG_UIDGID |
8915                                         CHANGELOG_EXTRA_FLAG_NID |
8916                                         CHANGELOG_EXTRA_FLAG_OMODE |
8917                                         CHANGELOG_EXTRA_FLAG_XATTR);
8918         if (rc < 0) {
8919                 fprintf(stderr,
8920                         "%s changelog: cannot set xflags for changelog: %s\n",
8921                         progname, strerror(errno = -rc));
8922                 return rc;
8923         }
8924
8925         while ((rc = llapi_changelog_recv(changelog_priv, &rec)) == 0) {
8926                 time_t secs;
8927                 struct tm ts;
8928
8929                 if (endrec && rec->cr_index > endrec) {
8930                         llapi_changelog_free(&rec);
8931                         break;
8932                 }
8933                 if (rec->cr_index < startrec) {
8934                         llapi_changelog_free(&rec);
8935                         continue;
8936                 }
8937
8938                 secs = rec->cr_time >> 30;
8939                 gmtime_r(&secs, &ts);
8940                 printf("%ju %02d%-5s %02d:%02d:%02d.%09d %04d.%02d.%02d "
8941                        "0x%x t="DFID, (uintmax_t)rec->cr_index, rec->cr_type,
8942                        changelog_type2str(rec->cr_type),
8943                        ts.tm_hour, ts.tm_min, ts.tm_sec,
8944                        (int)(rec->cr_time & ((1 << 30) - 1)),
8945                        ts.tm_year + 1900, ts.tm_mon + 1, ts.tm_mday,
8946                        rec->cr_flags & CLF_FLAGMASK, PFID(&rec->cr_tfid));
8947
8948                 if (rec->cr_flags & CLF_JOBID) {
8949                         struct changelog_ext_jobid *jid =
8950                                 changelog_rec_jobid(rec);
8951
8952                         if (jid->cr_jobid[0] != '\0')
8953                                 printf(" j=%s", jid->cr_jobid);
8954                 }
8955
8956                 if (rec->cr_flags & CLF_EXTRA_FLAGS) {
8957                         struct changelog_ext_extra_flags *ef =
8958                                 changelog_rec_extra_flags(rec);
8959
8960                         printf(" ef=0x%llx",
8961                                (unsigned long long)ef->cr_extra_flags);
8962
8963                         if (ef->cr_extra_flags & CLFE_UIDGID) {
8964                                 struct changelog_ext_uidgid *uidgid =
8965                                         changelog_rec_uidgid(rec);
8966
8967                                 printf(" u=%llu:%llu",
8968                                        (unsigned long long)uidgid->cr_uid,
8969                                        (unsigned long long)uidgid->cr_gid);
8970                         }
8971                         if (ef->cr_extra_flags & CLFE_NID) {
8972                                 struct changelog_ext_nid *nid =
8973                                         changelog_rec_nid(rec);
8974
8975                                 printf(" nid=%s",
8976                                        libcfs_nid2str(nid->cr_nid));
8977                         }
8978
8979                         if (ef->cr_extra_flags & CLFE_OPEN) {
8980                                 struct changelog_ext_openmode *omd =
8981                                         changelog_rec_openmode(rec);
8982                                 char mode[] = "---";
8983
8984                                 /* exec mode must be exclusive */
8985                                 if (omd->cr_openflags & MDS_FMODE_EXEC) {
8986                                         mode[2] = 'x';
8987                                 } else {
8988                                         if (omd->cr_openflags & MDS_FMODE_READ)
8989                                                 mode[0] = 'r';
8990                                         if (omd->cr_openflags &
8991                                             (MDS_FMODE_WRITE |
8992                                              MDS_OPEN_TRUNC |
8993                                              MDS_OPEN_APPEND))
8994                                                 mode[1] = 'w';
8995                                 }
8996
8997                                 if (strcmp(mode, "---") != 0)
8998                                         printf(" m=%s", mode);
8999                         }
9000
9001                         if (ef->cr_extra_flags & CLFE_XATTR) {
9002                                 struct changelog_ext_xattr *xattr =
9003                                         changelog_rec_xattr(rec);
9004
9005                                 if (xattr->cr_xattr[0] != '\0')
9006                                         printf(" x=%s", xattr->cr_xattr);
9007                         }
9008                 }
9009
9010                 if (!fid_is_zero(&rec->cr_pfid))
9011                         printf(" p="DFID, PFID(&rec->cr_pfid));
9012                 if (rec->cr_namelen)
9013                         printf(" %.*s", rec->cr_namelen,
9014                                changelog_rec_name(rec));
9015
9016                 if (rec->cr_flags & CLF_RENAME) {
9017                         struct changelog_ext_rename *rnm =
9018                                 changelog_rec_rename(rec);
9019
9020                         if (!fid_is_zero(&rnm->cr_sfid))
9021                                 printf(" s="DFID" sp="DFID" %.*s",
9022                                        PFID(&rnm->cr_sfid),
9023                                        PFID(&rnm->cr_spfid),
9024                                        (int)changelog_rec_snamelen(rec),
9025                                        changelog_rec_sname(rec));
9026                 }
9027                 printf("\n");
9028
9029                 llapi_changelog_free(&rec);
9030         }
9031
9032         llapi_changelog_fini(&changelog_priv);
9033
9034         if (rc < 0)
9035                 fprintf(stderr, "%s changelog: cannot access changelog: %s\n",
9036                         progname, strerror(errno = -rc));
9037
9038         return (rc == 1 ? 0 : rc);
9039 }
9040
9041 static int lfs_changelog_clear(int argc, char **argv)
9042 {
9043         long long endrec;
9044         int rc;
9045
9046         if (argc != 4)
9047                 return CMD_HELP;
9048
9049         errno = 0;
9050         endrec = strtoll(argv[3], NULL, 10);
9051         if (errno != 0 || endrec < 0) {
9052                 fprintf(stderr,
9053                         "%s: bad endrec '%s'\n",
9054                         argv[0], argv[3]);
9055                 return CMD_HELP;
9056         }
9057
9058         rc = llapi_changelog_clear(argv[1], argv[2], endrec);
9059
9060         if (rc == -EINVAL)
9061                 fprintf(stderr, "%s: record out of range: %llu\n",
9062                         argv[0], endrec);
9063         else if (rc == -ENOENT)
9064                 fprintf(stderr, "%s: no changelog user: %s\n",
9065                         argv[0], argv[2]);
9066         else if (rc)
9067                 fprintf(stderr, "%s error: %s\n", argv[0],
9068                         strerror(-rc));
9069
9070         if (rc)
9071                 errno = -rc;
9072
9073         return rc;
9074 }
9075
9076 static void rstripc(char *str, int c)
9077 {
9078         char *end = str + strlen(str);
9079
9080         for (; str < end && end[-1] == c; --end)
9081                 end[-1] = '\0';
9082 }
9083
9084 static int lfs_fid2path(int argc, char **argv)
9085 {
9086         struct option long_opts[] = {
9087                 { .val = 'c',   .name = "cur",  .has_arg = no_argument },
9088                 { .val = 'c',   .name = "current",      .has_arg = no_argument },
9089                 { .val = 'c',   .name = "print-link",   .has_arg = no_argument },
9090                 { .val = 'f',   .name = "print-fid",    .has_arg = no_argument },
9091                 { .val = 'l',   .name = "link", .has_arg = required_argument },
9092                 { .name = NULL } };
9093         char short_opts[] = "cfl:pr:";
9094         bool print_link = false;
9095         bool print_fid = false;
9096         bool print_mnt_dir;
9097         char mnt_dir[PATH_MAX] = "";
9098         int mnt_fd = -1;
9099         char *path_or_fsname;
9100         long long recno = -1;
9101         int linkno = -1;
9102         char *endptr = NULL;
9103         int rc = 0;
9104         int c;
9105         int i;
9106
9107         while ((c = getopt_long(argc, argv, short_opts, long_opts, NULL)) != -1) {
9108                 switch (c) {
9109                 case 'c':
9110                         print_link = true;
9111                         break;
9112                 case 'f':
9113                         print_fid = true;
9114                         break;
9115                 case 'l':
9116                         errno = 0;
9117                         linkno = strtol(optarg, &endptr, 10);
9118                         if (errno != 0 || *endptr != '\0' || linkno < 0) {
9119                                 fprintf(stderr,
9120                                         "%s fid2path: invalid linkno '%s'\n",
9121                                         progname, optarg);
9122                                 return CMD_HELP;
9123                         }
9124                         break;
9125                 case 'r':
9126                         /* recno is something to do with changelogs
9127                          * that was never implemented. We just pass it
9128                          * through for the MDT to ignore.
9129                          */
9130                         errno = 0;
9131                         recno = strtoll(optarg, &endptr, 10);
9132                         if (errno != 0 || *endptr != '\0' || recno < 0) {
9133                                 fprintf(stderr,
9134                                         "%s fid2path: invalid recno '%s'\n",
9135                                         progname, optarg);
9136                                 return CMD_HELP;
9137                         }
9138                         break;
9139                 default:
9140                         fprintf(stderr,
9141                                 "%s fid2path: unrecognized option '%s'\n",
9142                                 progname, argv[optind - 1]);
9143                         return CMD_HELP;
9144                 }
9145         }
9146
9147         if (argc - optind < 2) {
9148                 fprintf(stderr,
9149                         "Usage: %s fid2path FSNAME|ROOT FID...\n",
9150                         progname);
9151                 return CMD_HELP;
9152         }
9153
9154         path_or_fsname = argv[optind];
9155
9156         if (*path_or_fsname == '/') {
9157                 print_mnt_dir = true;
9158                 rc = llapi_search_mounts(path_or_fsname, 0, mnt_dir, NULL);
9159         } else {
9160                 print_mnt_dir = false;
9161                 rc = llapi_search_rootpath(mnt_dir, path_or_fsname);
9162         }
9163
9164         if (rc < 0) {
9165                 fprintf(stderr,
9166                         "%s fid2path: cannot resolve mount point for '%s': %s\n",
9167                         progname, path_or_fsname, strerror(-rc));
9168                 goto out;
9169         }
9170
9171         mnt_fd = open(mnt_dir, O_RDONLY | O_DIRECTORY);
9172         if (mnt_fd < 0) {
9173                 fprintf(stderr,
9174                         "%s fid2path: cannot open mount point for '%s': %s\n",
9175                         progname, path_or_fsname, strerror(-rc));
9176                 goto out;
9177         }
9178
9179         /* Strip trailing slashes from mnt_dir. */
9180         rstripc(mnt_dir + 1, '/');
9181
9182         for (i = optind + 1; i < argc; i++) {
9183                 const char *fid_str = argv[i];
9184                 struct lu_fid fid;
9185                 int rc2;
9186
9187                 rc2 = llapi_fid_parse(fid_str, &fid, NULL);
9188                 if (rc2 < 0) {
9189                         fprintf(stderr,
9190                                 "%s fid2path: invalid FID '%s'\n",
9191                                 progname, fid_str);
9192                         if (rc == 0)
9193                                 rc = rc2;
9194
9195                         continue;
9196                 }
9197
9198                 int linktmp = (linkno >= 0) ? linkno : 0;
9199                 while (1) {
9200                         int oldtmp = linktmp;
9201                         long long rectmp = recno;
9202                         char path_buf[PATH_MAX];
9203
9204                         rc2 = llapi_fid2path_at(mnt_fd, &fid,
9205                                 path_buf, sizeof(path_buf), &rectmp, &linktmp);
9206                         if (rc2 < 0) {
9207                                 fprintf(stderr,
9208                                         "%s fid2path: cannot find %s %s: %s\n",
9209                                         progname, path_or_fsname, fid_str,
9210                                         strerror(-rc2));
9211                                 if (rc == 0)
9212                                         rc = rc2;
9213                                 break;
9214                         }
9215
9216                         if (print_fid)
9217                                 printf("%s ", fid_str);
9218
9219                         if (print_link)
9220                                 printf("%d ", linktmp);
9221
9222                         /* You may think this looks wrong or weird (and it is!)
9223                          * but we are actually trying to preserve the old quirky
9224                          * behaviors (enforced by our old quirky tests!) that
9225                          * make lfs so much fun to work on:
9226                          *
9227                          *   lustre 0x200000007:0x1:0x0 => "/"
9228                          *   /mnt/lustre 0x200000007:0x1:0x0 => "/mnt/lustre//"
9229                          *
9230                          * Note that llapi_fid2path() returns "" for the root
9231                          * FID. */
9232
9233                         printf("%s%s%s\n",
9234                                print_mnt_dir ? mnt_dir : "",
9235                                (print_mnt_dir || *path_buf == '\0') ? "/" : "",
9236                                path_buf);
9237
9238                         if (linkno >= 0)
9239                                 /* specified linkno */
9240                                 break;
9241
9242                         if (oldtmp == linktmp)
9243                                 /* no more links */
9244                                 break;
9245                 }
9246         }
9247 out:
9248         if (!(mnt_fd < 0))
9249                 close(mnt_fd);
9250
9251         return rc;
9252 }
9253
9254 static int lfs_path2fid(int argc, char **argv)
9255 {
9256         struct option long_opts[] = {
9257                 { .val = 'p', .name = "parents", .has_arg = no_argument },
9258                 { .name = NULL } };
9259         char            **path;
9260         const char        short_opts[] = "p";
9261         const char       *sep = "";
9262         struct lu_fid     fid;
9263         int               rc = 0;
9264         bool              show_parents = false;
9265
9266         while ((rc = getopt_long(argc, argv, short_opts,
9267                                  long_opts, NULL)) != -1) {
9268                 switch (rc) {
9269                 case 'p':
9270                         show_parents = true;
9271                         break;
9272                 default:
9273                         fprintf(stderr,
9274                                 "%s path2fid: unrecognized option '%s'\n",
9275                                 progname, argv[optind - 1]);
9276                         return CMD_HELP;
9277                 }
9278         }
9279
9280         if (optind > argc - 1) {
9281                 fprintf(stderr, "%s path2fid: FILE... must be specified\n",
9282                         progname);
9283                 return CMD_HELP;
9284         } else if (optind < argc - 1) {
9285                 sep = ": ";
9286         }
9287
9288         rc = 0;
9289         for (path = argv + optind; *path != NULL; path++) {
9290                 int err = 0;
9291
9292                 if (!show_parents) {
9293                         err = llapi_path2fid(*path, &fid);
9294                         if (!err)
9295                                 printf("%s%s"DFID"\n",
9296                                        *sep != '\0' ? *path : "", sep,
9297                                        PFID(&fid));
9298                 } else {
9299                         char            name[NAME_MAX + 1];
9300                         unsigned int    linkno = 0;
9301
9302                         while ((err = llapi_path2parent(*path, linkno, &fid,
9303                                                 name, sizeof(name))) == 0) {
9304                                 if (*sep != '\0' && linkno == 0)
9305                                         printf("%s%s", *path, sep);
9306
9307                                 printf("%s"DFID"/%s", linkno != 0 ? "\t" : "",
9308                                        PFID(&fid), name);
9309                                 linkno++;
9310                         }
9311
9312                         /* err == -ENODATA is end-of-loop */
9313                         if (linkno > 0 && err == -ENODATA) {
9314                                 printf("\n");
9315                                 err = 0;
9316                         }
9317                 }
9318
9319                 if (err) {
9320                         fprintf(stderr,
9321                                 "%s path2fid: cannot get %sfid for '%s': %s\n",
9322                                 progname, show_parents ? "parent " : "", *path,
9323                                 strerror(-err));
9324                         if (rc == 0) {
9325                                 rc = err;
9326                                 errno = -err;
9327                         }
9328                 }
9329         }
9330
9331         return rc;
9332 }
9333
9334 #define MAX_ERRNO       4095
9335 #define IS_ERR_VALUE(x) ((unsigned long)(x) >= (unsigned long)-MAX_ERRNO)
9336
9337 static int lfs_rmfid_and_show_errors(const char *device, struct fid_array *fa)
9338 {
9339         int rc, rc2, k;
9340
9341         rc = llapi_rmfid(device, fa);
9342         if (rc < 0) {
9343                 fprintf(stderr, "%s rmfid: cannot remove FIDs: %s\n",
9344                         progname, strerror(-rc));
9345                 return rc;
9346         }
9347
9348         for (k = 0; k < fa->fa_nr; k++) {
9349                 rc2 = (__s32)fa->fa_fids[k].f_ver;
9350                 if (!IS_ERR_VALUE(rc2))
9351                         continue;
9352
9353                 if (rc == 0)
9354                         rc = rc2;
9355
9356                 fa->fa_fids[k].f_ver = 0;
9357                 fprintf(stderr, "%s rmfid: cannot remove "DFID": %s\n",
9358                         progname, PFID(&fa->fa_fids[k]), strerror(-rc2));
9359         }
9360
9361         return rc;
9362 }
9363
9364 static int lfs_rmfid(int argc, char **argv)
9365 {
9366         char *fidstr, *device;
9367         int rc = 0, rc2, nr;
9368         struct fid_array *fa;
9369
9370         if (optind > argc - 1) {
9371                 fprintf(stderr, "%s rmfid: missing dirname\n", progname);
9372                 return CMD_HELP;
9373         }
9374
9375         device = argv[optind++];
9376
9377         nr = argc - optind;
9378         fa = malloc(offsetof(struct fid_array, fa_fids[nr + 1]));
9379         if (!fa)
9380                 return -ENOMEM;
9381
9382         fa->fa_nr = 0;
9383         rc = 0;
9384         while (optind < argc) {
9385                 int found;
9386
9387                 fidstr = argv[optind++];
9388                 while (*fidstr == '[')
9389                         fidstr++;
9390                 found = sscanf(fidstr, SFID, RFID(&fa->fa_fids[fa->fa_nr]));
9391                 if (found != 3) {
9392                         fprintf(stderr, "unrecognized FID: %s\n",
9393                                 argv[optind - 1]);
9394                         exit(1);
9395                 }
9396                 fa->fa_nr++;
9397                 if (fa->fa_nr == OBD_MAX_FIDS_IN_ARRAY) {
9398                         /* start another batch */
9399                         rc2 = lfs_rmfid_and_show_errors(device, fa);
9400                         if (rc2 && !rc)
9401                                 rc = rc2;
9402                         fa->fa_nr = 0;
9403                 }
9404         }
9405         if (fa->fa_nr) {
9406                 rc2 = lfs_rmfid_and_show_errors(device, fa);
9407                 if (rc2 && !rc)
9408                         rc = rc2;
9409         }
9410
9411         return rc;
9412 }
9413
9414 static int lfs_data_version(int argc, char **argv)
9415 {
9416         int data_version_flags = LL_DV_RD_FLUSH; /* Read by default */
9417         __u64 data_version;
9418         char *path;
9419         int fd;
9420         int rc;
9421         int c;
9422
9423         if (argc < 2) {
9424                 fprintf(stderr, "%s: FILE must be specified\n",
9425                         progname);
9426                 return CMD_HELP;
9427         }
9428
9429         while ((c = getopt(argc, argv, "hnrw")) != -1) {
9430                 switch (c) {
9431                 case 'n':
9432                         data_version_flags = 0;
9433                         break;
9434                 case 'r':
9435                         data_version_flags |= LL_DV_RD_FLUSH;
9436                         break;
9437                 case 'w':
9438                         data_version_flags |= LL_DV_WR_FLUSH;
9439                         break;
9440                 default:
9441                         fprintf(stderr,
9442                                 "%s data_version: unrecognized option '%s'\n",
9443                                 progname, argv[optind - 1]);
9444                         /* fallthrough */
9445                 case 'h':
9446                         return CMD_HELP;
9447                 }
9448         }
9449         if (optind == argc) {
9450                 fprintf(stderr, "%s data_version: FILE must be specified\n",
9451                         progname);
9452                 return CMD_HELP;
9453         }
9454
9455         path = argv[optind];
9456         fd = open(path, O_RDONLY);
9457         if (fd < 0) {
9458                 rc = -errno;
9459                 fprintf(stderr, "%s data_version: cannot open file '%s': %s\n",
9460                         progname, path, strerror(-rc));
9461                 return rc;
9462         }
9463
9464         rc = llapi_get_data_version(fd, &data_version, data_version_flags);
9465         if (rc < 0)
9466                 fprintf(stderr,
9467                         "%s data_version: cannot get version for '%s': %s\n",
9468                         progname, path, strerror(-rc));
9469         else
9470                 printf("%ju" "\n", (uintmax_t)data_version);
9471
9472         close(fd);
9473         return rc;
9474 }
9475
9476 static int lfs_hsm_state(int argc, char **argv)
9477 {
9478         int rc;
9479         int i = 1;
9480         char *path;
9481         struct hsm_user_state hus;
9482
9483         if (argc < 2)
9484                 return CMD_HELP;
9485
9486         do {
9487                 path = argv[i];
9488
9489                 rc = llapi_hsm_state_get(path, &hus);
9490                 if (rc) {
9491                         fprintf(stderr, "can't get hsm state for %s: %s\n",
9492                                 path, strerror(errno = -rc));
9493                         return rc;
9494                 }
9495
9496                 /* Display path name and status flags */
9497                 printf("%s: (0x%08x)", path, hus.hus_states);
9498
9499                 if (hus.hus_states & HS_RELEASED)
9500                         printf(" released");
9501                 if (hus.hus_states & HS_EXISTS)
9502                         printf(" exists");
9503                 if (hus.hus_states & HS_DIRTY)
9504                         printf(" dirty");
9505                 if (hus.hus_states & HS_ARCHIVED)
9506                         printf(" archived");
9507                 /* Display user-settable flags */
9508                 if (hus.hus_states & HS_NORELEASE)
9509                         printf(" never_release");
9510                 if (hus.hus_states & HS_NOARCHIVE)
9511                         printf(" never_archive");
9512                 if (hus.hus_states & HS_LOST)
9513                         printf(" lost_from_hsm");
9514
9515                 if (hus.hus_archive_id != 0)
9516                         printf(", archive_id:%d", hus.hus_archive_id);
9517                 printf("\n");
9518
9519         } while (++i < argc);
9520
9521         return 0;
9522 }
9523
9524 #define LFS_HSM_SET   0
9525 #define LFS_HSM_CLEAR 1
9526
9527 /**
9528  * Generic function to set or clear HSM flags.
9529  * Used by hsm_set and hsm_clear.
9530  *
9531  * @mode  if LFS_HSM_SET, set the flags, if LFS_HSM_CLEAR, clear the flags.
9532  */
9533 static int lfs_hsm_change_flags(int argc, char **argv, int mode)
9534 {
9535         struct option long_opts[] = {
9536         { .val = 'A',   .name = "archived",     .has_arg = no_argument },
9537         { .val = 'a',   .name = "noarchive",    .has_arg = no_argument },
9538         { .val = 'd',   .name = "dirty",        .has_arg = no_argument },
9539         { .val = 'e',   .name = "exists",       .has_arg = no_argument },
9540         { .val = 'h',   .name = "help",         .has_arg = no_argument },
9541         { .val = 'i',   .name = "archive-id",   .has_arg = required_argument },
9542         { .val = 'l',   .name = "lost",         .has_arg = no_argument },
9543         { .val = 'r',   .name = "norelease",    .has_arg = no_argument },
9544         { .name = NULL } };
9545         __u64 mask = 0;
9546         int c, rc;
9547         char *path;
9548         __u32 archive_id = 0;
9549         char *end = NULL;
9550
9551         if (argc < 3)
9552                 return CMD_HELP;
9553
9554         while ((c = getopt_long(argc, argv, "aAdehi:lr",
9555                                 long_opts, NULL)) != -1) {
9556                 switch (c) {
9557                 case 'l':
9558                         mask |= HS_LOST;
9559                         break;
9560                 case 'a':
9561                         mask |= HS_NOARCHIVE;
9562                         break;
9563                 case 'A':
9564                         mask |= HS_ARCHIVED;
9565                         break;
9566                 case 'r':
9567                         mask |= HS_NORELEASE;
9568                         break;
9569                 case 'd':
9570                         mask |= HS_DIRTY;
9571                         break;
9572                 case 'e':
9573                         mask |= HS_EXISTS;
9574                         break;
9575                 case 'i':
9576                         errno = 0;
9577                         archive_id = strtol(optarg, &end, 10);
9578                         if (errno != 0 || *end != '\0' || archive_id < 0) {
9579                                 fprintf(stderr,
9580                                         "%s: invalid archive_id: '%s'\n",
9581                                         progname, end);
9582                                 return CMD_HELP;
9583                         }
9584                         break;
9585                 default:
9586                         fprintf(stderr, "%s: unrecognized option '%s'\n",
9587                                 progname, argv[optind - 1]);
9588                         /* fallthrough */
9589                 case 'h':
9590                         return CMD_HELP;
9591                 }
9592         }
9593
9594         /* User should have specified a flag */
9595         if (mask == 0)
9596                 return CMD_HELP;
9597
9598         while (optind < argc) {
9599                 path = argv[optind];
9600
9601                 /* If mode == 0, this means we apply the mask. */
9602                 if (mode == LFS_HSM_SET)
9603                         rc = llapi_hsm_state_set(path, mask, 0, archive_id);
9604                 else
9605                         rc = llapi_hsm_state_set(path, 0, mask, 0);
9606
9607                 if (rc != 0) {
9608                         fprintf(stderr, "Can't change hsm flags for %s: %s\n",
9609                                 path, strerror(errno = -rc));
9610                         return rc;
9611                 }
9612                 optind++;
9613         }
9614
9615         return 0;
9616 }
9617
9618 static int lfs_hsm_action(int argc, char **argv)
9619 {
9620         int                              rc;
9621         int                              i = 1;
9622         char                            *path;
9623         struct hsm_current_action        hca;
9624         struct hsm_extent                he;
9625         enum hsm_user_action             hua;
9626         enum hsm_progress_states         hps;
9627
9628         if (argc < 2)
9629                 return CMD_HELP;
9630
9631         do {
9632                 path = argv[i];
9633
9634                 rc = llapi_hsm_current_action(path, &hca);
9635                 if (rc) {
9636                         fprintf(stderr, "can't get hsm action for %s: %s\n",
9637                                 path, strerror(errno = -rc));
9638                         return rc;
9639                 }
9640                 he = hca.hca_location;
9641                 hua = hca.hca_action;
9642                 hps = hca.hca_state;
9643
9644                 printf("%s: %s", path, hsm_user_action2name(hua));
9645
9646                 /* Skip file without action */
9647                 if (hca.hca_action == HUA_NONE) {
9648                         printf("\n");
9649                         continue;
9650                 }
9651
9652                 printf(" %s ", hsm_progress_state2name(hps));
9653
9654                 if ((hps == HPS_RUNNING) &&
9655                     (hua == HUA_ARCHIVE || hua == HUA_RESTORE))
9656                         printf("(%llu bytes moved)\n",
9657                                (unsigned long long)he.length);
9658                 else if ((he.offset + he.length) == LUSTRE_EOF)
9659                         printf("(from %llu to EOF)\n",
9660                                (unsigned long long)he.offset);
9661                 else
9662                         printf("(from %llu to %llu)\n",
9663                                (unsigned long long)he.offset,
9664                                (unsigned long long)(he.offset + he.length));
9665
9666         } while (++i < argc);
9667
9668         return 0;
9669 }
9670
9671 static int lfs_hsm_set(int argc, char **argv)
9672 {
9673         return lfs_hsm_change_flags(argc, argv, LFS_HSM_SET);
9674 }
9675
9676 static int lfs_hsm_clear(int argc, char **argv)
9677 {
9678         return lfs_hsm_change_flags(argc, argv, LFS_HSM_CLEAR);
9679 }
9680
9681 /**
9682  * Check file state and return its fid, to be used by lfs_hsm_request().
9683  *
9684  * \param[in]     file      Path to file to check
9685  * \param[in,out] fid       Pointer to allocated lu_fid struct.
9686  * \param[in,out] last_dev  Pointer to last device id used.
9687  *
9688  * \return 0 on success.
9689  */
9690 static int lfs_hsm_prepare_file(const char *file, struct lu_fid *fid,
9691                                 dev_t *last_dev)
9692 {
9693         struct stat     st;
9694         int             rc;
9695
9696         rc = lstat(file, &st);
9697         if (rc) {
9698                 fprintf(stderr, "Cannot stat %s: %s\n", file, strerror(errno));
9699                 return -errno;
9700         }
9701         /*
9702          * Checking for regular file as archiving as posix copytool
9703          * rejects archiving files other than regular files
9704          */
9705         if (!S_ISREG(st.st_mode)) {
9706                 fprintf(stderr, "error: \"%s\" is not a regular file\n", file);
9707                 return CMD_HELP;
9708         }
9709         /* A request should be ... */
9710         if (*last_dev != st.st_dev && *last_dev != 0) {
9711                 fprintf(stderr,
9712                         "All files should be on the same filesystem: %s\n",
9713                         file);
9714                 return -EINVAL;
9715         }
9716         *last_dev = st.st_dev;
9717
9718         rc = llapi_path2fid(file, fid);
9719         if (rc) {
9720                 fprintf(stderr, "Cannot read FID of %s: %s\n",
9721                         file, strerror(-rc));
9722                 return rc;
9723         }
9724         return 0;
9725 }
9726
9727 /* Fill an HSM HUR item with a given file name.
9728  *
9729  * If mntpath is set, then the filename is actually a FID, and no
9730  * lookup on the filesystem will be performed.
9731  *
9732  * \param[in]  hur         the user request to fill
9733  * \param[in]  idx         index of the item inside the HUR to fill
9734  * \param[in]  mntpath     mountpoint of Lustre
9735  * \param[in]  fname       filename (if mtnpath is NULL)
9736  *                         or FID (if mntpath is set)
9737  * \param[in]  last_dev    pointer to last device id used
9738  *
9739  * \retval 0 on success
9740  * \retval CMD_HELP or a negative errno on error
9741  */
9742 static int fill_hur_item(struct hsm_user_request *hur, unsigned int idx,
9743                          const char *mntpath, const char *fname,
9744                          dev_t *last_dev)
9745 {
9746         struct hsm_user_item *hui = &hur->hur_user_item[idx];
9747         int rc;
9748
9749         hui->hui_extent.length = -1;
9750
9751         if (mntpath) {
9752                 rc = llapi_fid_parse(fname, &hui->hui_fid, NULL);
9753                 if (rc)
9754                         fprintf(stderr, "hsm: '%s' is not a valid FID\n",
9755                                 fname);
9756         } else {
9757                 rc = lfs_hsm_prepare_file(fname, &hui->hui_fid, last_dev);
9758         }
9759
9760         if (rc == 0)
9761                 hur->hur_request.hr_itemcount++;
9762
9763         return rc;
9764 }
9765
9766 static int lfs_hsm_request(int argc, char **argv, int action)
9767 {
9768         struct option long_opts[] = {
9769         { .val = 'a',   .name = "archive",      .has_arg = required_argument },
9770         { .val = 'D',   .name = "data",         .has_arg = required_argument },
9771         { .val = 'h',   .name = "help",         .has_arg = no_argument },
9772         { .val = 'l',   .name = "filelist",     .has_arg = required_argument },
9773         { .val = 'm',   .name = "mntpath",      .has_arg = required_argument },
9774         { .name = NULL } };
9775         dev_t last_dev = 0;
9776         struct hsm_user_request *hur, *oldhur;
9777         int c, i;
9778         size_t len;
9779         int nbfile;
9780         char *line = NULL;
9781         char *filelist = NULL;
9782         char fullpath[PATH_MAX];
9783         char *opaque = NULL;
9784         int opaque_len = 0;
9785         int archive_id = 0;
9786         FILE *fp;
9787         int nbfile_alloc = 0;
9788         char *some_file = NULL;
9789         char *mntpath = NULL;
9790         int rc;
9791
9792         if (argc < 2)
9793                 return CMD_HELP;
9794
9795         while ((c = getopt_long(argc, argv, "a:D:hl:m:",
9796                                 long_opts, NULL)) != -1) {
9797                 switch (c) {
9798                 case 'l':
9799                         filelist = optarg;
9800                         break;
9801                 case 'D':
9802                         opaque = optarg;
9803                         break;
9804                 case 'a':
9805                         if (action != HUA_ARCHIVE &&
9806                             action != HUA_REMOVE) {
9807                                 fprintf(stderr,
9808                                         "error: -a is supported only when archiving or removing\n");
9809                                 return CMD_HELP;
9810                         }
9811                         archive_id = atoi(optarg);
9812                         break;
9813                 case 'm':
9814                         if (!some_file) {
9815                                 mntpath = optarg;
9816                                 some_file = strdup(optarg);
9817                         }
9818                         break;
9819                 default:
9820                         fprintf(stderr, "%s: unrecognized option '%s'\n",
9821                                 progname, argv[optind - 1]);
9822                         /* fallthrough */
9823                 case 'h':
9824                         return CMD_HELP;
9825                 }
9826         }
9827
9828         /* All remaining args are files, so we have at least nbfile */
9829         nbfile = argc - optind;
9830
9831         if ((nbfile == 0) && (!filelist))
9832                 return CMD_HELP;
9833
9834         if (opaque)
9835                 opaque_len = strlen(opaque);
9836
9837         /*
9838          * Alloc the request structure with enough place to store all files
9839          * from command line.
9840          */
9841         hur = llapi_hsm_user_request_alloc(nbfile, opaque_len);
9842         if (!hur) {
9843                 fprintf(stderr, "Cannot create the request: %s\n",
9844                         strerror(errno));
9845                 return errno;
9846         }
9847         nbfile_alloc = nbfile;
9848
9849         hur->hur_request.hr_action = action;
9850         hur->hur_request.hr_archive_id = archive_id;
9851         hur->hur_request.hr_flags = 0;
9852
9853         /* All remaining args are files, add them */
9854         if (nbfile != 0 && some_file == NULL)
9855                 some_file = strdup(argv[optind]);
9856
9857         for (i = 0; i < nbfile; i++) {
9858                 rc = fill_hur_item(hur, i, mntpath, argv[optind + i],
9859                                    &last_dev);
9860                 if (rc)
9861                         goto out_free;
9862         }
9863
9864         /* from here stop using nb_file, use hur->hur_request.hr_itemcount */
9865
9866         /* If a filelist was specified, read the filelist from it. */
9867         if (filelist) {
9868                 fp = fopen(filelist, "r");
9869                 if (!fp) {
9870                         fprintf(stderr, "Cannot read the file list %s: %s\n",
9871                                 filelist, strerror(errno));
9872                         rc = -errno;
9873                         goto out_free;
9874                 }
9875
9876                 while ((rc = getline(&line, &len, fp)) != -1) {
9877                         /*
9878                          * If allocated buffer was too small, get something
9879                          * larger
9880                          */
9881                         if (nbfile_alloc <= hur->hur_request.hr_itemcount) {
9882                                 ssize_t size;
9883
9884                                 nbfile_alloc = nbfile_alloc * 2 + 1;
9885                                 oldhur = hur;
9886                                 hur = llapi_hsm_user_request_alloc(nbfile_alloc,
9887                                                                    opaque_len);
9888                                 if (!hur) {
9889                                         fprintf(stderr,
9890                                                 "hsm: cannot allocate the request: %s\n",
9891                                                 strerror(errno));
9892                                         hur = oldhur;
9893                                         rc = -errno;
9894                                         fclose(fp);
9895                                         goto out_free;
9896                                 }
9897                                 size = hur_len(oldhur);
9898                                 if (size < 0) {
9899                                         fprintf(stderr,
9900                                                 "hsm: cannot allocate %u files + %u bytes data\n",
9901                                                 oldhur->hur_request.hr_itemcount,
9902                                                 oldhur->hur_request.hr_data_len);
9903                                         free(hur);
9904                                         hur = oldhur;
9905                                         rc = -E2BIG;
9906                                         fclose(fp);
9907                                         goto out_free;
9908                                 }
9909                                 memcpy(hur, oldhur, size);
9910                                 free(oldhur);
9911                         }
9912
9913                         /* Chop CR */
9914                         if (line[strlen(line) - 1] == '\n')
9915                                 line[strlen(line) - 1] = '\0';
9916
9917                         rc = fill_hur_item(hur, hur->hur_request.hr_itemcount,
9918                                            mntpath, line, &last_dev);
9919                         if (rc) {
9920                                 fclose(fp);
9921                                 goto out_free;
9922                         }
9923
9924                         if (!some_file) {
9925                                 some_file = line;
9926                                 line = NULL;
9927                         }
9928                 }
9929
9930                 rc = fclose(fp);
9931                 free(line);
9932         }
9933
9934         /* If a --data was used, add it to the request */
9935         hur->hur_request.hr_data_len = opaque_len;
9936         if (opaque)
9937                 memcpy(hur_data(hur), opaque, opaque_len);
9938
9939         /* Send the HSM request */
9940         if (realpath(some_file, fullpath) == NULL) {
9941                 fprintf(stderr, "Could not find path '%s': %s\n",
9942                         some_file, strerror(errno));
9943         }
9944         rc = llapi_hsm_request(fullpath, hur);
9945         if (rc) {
9946                 fprintf(stderr, "Cannot send HSM request (use of %s): %s\n",
9947                         some_file, strerror(-rc));
9948                 goto out_free;
9949         }
9950
9951 out_free:
9952         free(some_file);
9953         free(hur);
9954         return rc;
9955 }
9956
9957 static int lfs_hsm_archive(int argc, char **argv)
9958 {
9959         return lfs_hsm_request(argc, argv, HUA_ARCHIVE);
9960 }
9961
9962 static int lfs_hsm_restore(int argc, char **argv)
9963 {
9964         return lfs_hsm_request(argc, argv, HUA_RESTORE);
9965 }
9966
9967 static int lfs_hsm_release(int argc, char **argv)
9968 {
9969         return lfs_hsm_request(argc, argv, HUA_RELEASE);
9970 }
9971
9972 static int lfs_hsm_remove(int argc, char **argv)
9973 {
9974         return lfs_hsm_request(argc, argv, HUA_REMOVE);
9975 }
9976
9977 static int lfs_hsm_cancel(int argc, char **argv)
9978 {
9979         return lfs_hsm_request(argc, argv, HUA_CANCEL);
9980 }
9981
9982 static int lfs_swap_layouts(int argc, char **argv)
9983 {
9984         if (argc != 3)
9985                 return CMD_HELP;
9986
9987         return llapi_swap_layouts(argv[1], argv[2], 0, 0,
9988                                   SWAP_LAYOUTS_KEEP_MTIME |
9989                                   SWAP_LAYOUTS_KEEP_ATIME);
9990 }
9991
9992 static const char *const ladvise_names[] = LU_LADVISE_NAMES;
9993
9994 static const char *const lock_mode_names[] = LOCK_MODE_NAMES;
9995
9996 int lfs_get_mode(const char *string)
9997 {
9998         enum lock_mode_user mode;
9999
10000         for (mode = 0; mode < ARRAY_SIZE(lock_mode_names); mode++) {
10001                 if (lock_mode_names[mode] == NULL)
10002                         continue;
10003                 if (strcasecmp(string, lock_mode_names[mode]) == 0)
10004                         return mode;
10005         }
10006
10007         return -EINVAL;
10008 }
10009
10010 static enum lu_ladvise_type lfs_get_ladvice(const char *string)
10011 {
10012         enum lu_ladvise_type advice;
10013
10014         for (advice = 0;
10015              advice < ARRAY_SIZE(ladvise_names); advice++) {
10016                 if (ladvise_names[advice] == NULL)
10017                         continue;
10018                 if (strcmp(string, ladvise_names[advice]) == 0)
10019                         return advice;
10020         }
10021
10022         return LU_LADVISE_INVALID;
10023 }
10024
10025 static int lfs_ladvise(int argc, char **argv)
10026 {
10027         struct option long_opts[] = {
10028         { .val = 'a',   .name = "advice",       .has_arg = required_argument },
10029         { .val = 'b',   .name = "background",   .has_arg = no_argument },
10030         { .val = 'e',   .name = "end",          .has_arg = required_argument },
10031         { .val = 'h',   .name = "help",         .has_arg = no_argument },
10032         { .val = 'l',   .name = "length",       .has_arg = required_argument },
10033         { .val = 'm',   .name = "mode",         .has_arg = required_argument },
10034         { .val = 's',   .name = "start",        .has_arg = required_argument },
10035         { .val = 'u',   .name = "unset",        .has_arg = no_argument },
10036         { .name = NULL } };
10037         struct llapi_lu_ladvise advice;
10038         enum lu_ladvise_type advice_type = LU_LADVISE_INVALID;
10039         unsigned long long start = 0;
10040         unsigned long long end = LUSTRE_EOF;
10041         unsigned long long length = 0;
10042         unsigned long long size_units;
10043         unsigned long long flags = 0;
10044         int c, fd, rc = 0;
10045         const char *path;
10046         int mode = 0;
10047
10048         optind = 0;
10049         while ((c = getopt_long(argc, argv, "a:be:hl:m:s:u",
10050                                 long_opts, NULL)) != -1) {
10051                 switch (c) {
10052                 case 'a':
10053                         advice_type = lfs_get_ladvice(optarg);
10054                         if (advice_type == LU_LADVISE_INVALID) {
10055                                 fprintf(stderr,
10056                                         "%s: invalid advice type '%s'\n",
10057                                         progname, optarg);
10058                                 fprintf(stderr, "Valid types:");
10059
10060                                 for (advice_type = 0;
10061                                      advice_type < ARRAY_SIZE(ladvise_names);
10062                                      advice_type++) {
10063                                         if (ladvise_names[advice_type] == NULL)
10064                                                 continue;
10065                                         fprintf(stderr, " %s",
10066                                                 ladvise_names[advice_type]);
10067                                 }
10068                                 fprintf(stderr, "\n");
10069
10070                                 return CMD_HELP;
10071                         }
10072                         break;
10073                 case 'b':
10074                         flags |= LF_ASYNC;
10075                         break;
10076                 case 'u':
10077                         flags |= LF_UNSET;
10078                         break;
10079                 case 'e':
10080                         size_units = 1;
10081                         rc = llapi_parse_size(optarg, &end,
10082                                               &size_units, 0);
10083                         if (rc) {
10084                                 fprintf(stderr, "%s: bad end offset '%s'\n",
10085                                         argv[0], optarg);
10086                                 return CMD_HELP;
10087                         }
10088                         break;
10089                 case 's':
10090                         size_units = 1;
10091                         rc = llapi_parse_size(optarg, &start,
10092                                               &size_units, 0);
10093                         if (rc) {
10094                                 fprintf(stderr,
10095                                         "%s: bad start offset '%s'\n",
10096                                         argv[0], optarg);
10097                                 return CMD_HELP;
10098                         }
10099                         break;
10100                 case 'l':
10101                         size_units = 1;
10102                         rc = llapi_parse_size(optarg, &length,
10103                                               &size_units, 0);
10104                         if (rc) {
10105                                 fprintf(stderr, "%s: bad length '%s'\n",
10106                                         argv[0], optarg);
10107                                 return CMD_HELP;
10108                         }
10109                         break;
10110                 case 'm':
10111                         mode = lfs_get_mode(optarg);
10112                         if (mode < 0) {
10113                                 fprintf(stderr,
10114                                         "%s: bad mode '%s', valid modes are READ or WRITE\n",
10115                                         argv[0], optarg);
10116                                 return CMD_HELP;
10117                         }
10118                         break;
10119                 default:
10120                         fprintf(stderr, "%s: unrecognized option '%s'\n",
10121                                 progname, argv[optind - 1]);
10122                         /* fallthrough */
10123                 case 'h':
10124                         return CMD_HELP;
10125                 }
10126         }
10127
10128         if (advice_type == LU_LADVISE_INVALID) {
10129                 fprintf(stderr, "%s: please give an advice type\n", argv[0]);
10130                 fprintf(stderr, "Valid types:");
10131                 for (advice_type = 0; advice_type < ARRAY_SIZE(ladvise_names);
10132                      advice_type++) {
10133                         if (ladvise_names[advice_type] == NULL)
10134                                 continue;
10135                         fprintf(stderr, " %s", ladvise_names[advice_type]);
10136                 }
10137                 fprintf(stderr, "\n");
10138                 return CMD_HELP;
10139         }
10140
10141         if (advice_type == LU_LADVISE_LOCKNOEXPAND) {
10142                 fprintf(stderr,
10143                         "%s: Lock no expand advice is a per file descriptor advice, so when called from lfs, it does nothing.\n",
10144                         argv[0]);
10145                 return CMD_HELP;
10146         }
10147
10148         if (argc <= optind) {
10149                 fprintf(stderr, "%s: please give one or more file names\n",
10150                         argv[0]);
10151                 return CMD_HELP;
10152         }
10153
10154         if (end != LUSTRE_EOF && length != 0 && end != start + length) {
10155                 fprintf(stderr, "%s: conflicting arguments of -l and -e\n",
10156                         argv[0]);
10157                 return CMD_HELP;
10158         }
10159
10160         if (end == LUSTRE_EOF && length != 0)
10161                 end = start + length;
10162
10163         if (end <= start) {
10164                 fprintf(stderr, "%s: range [%llu, %llu] is invalid\n",
10165                         argv[0], start, end);
10166                 return CMD_HELP;
10167         }
10168
10169         if (advice_type != LU_LADVISE_LOCKAHEAD && mode != 0) {
10170                 fprintf(stderr, "%s: mode is only valid with lockahead\n",
10171                         argv[0]);
10172                 return CMD_HELP;
10173         }
10174
10175         if (advice_type == LU_LADVISE_LOCKAHEAD && mode == 0) {
10176                 fprintf(stderr, "%s: mode is required with lockahead\n",
10177                         argv[0]);
10178                 return CMD_HELP;
10179         }
10180
10181         while (optind < argc) {
10182                 int rc2;
10183
10184                 path = argv[optind++];
10185
10186                 fd = open(path, O_RDONLY);
10187                 if (fd < 0) {
10188                         fprintf(stderr, "%s: cannot open file '%s': %s\n",
10189                                 argv[0], path, strerror(errno));
10190                         rc2 = -errno;
10191                         goto next;
10192                 }
10193
10194                 advice.lla_start = start;
10195                 advice.lla_end = end;
10196                 advice.lla_advice = advice_type;
10197                 advice.lla_value1 = 0;
10198                 advice.lla_value2 = 0;
10199                 advice.lla_value3 = 0;
10200                 advice.lla_value4 = 0;
10201                 if (advice_type == LU_LADVISE_LOCKAHEAD) {
10202                         advice.lla_lockahead_mode = mode;
10203                         advice.lla_peradvice_flags = flags;
10204                 }
10205
10206                 rc2 = llapi_ladvise(fd, flags, 1, &advice);
10207                 close(fd);
10208                 if (rc2 < 0) {
10209                         fprintf(stderr,
10210                                 "%s: cannot give advice '%s' to file '%s': %s\n",
10211                                 argv[0], ladvise_names[advice_type],
10212                                 path, strerror(errno));
10213
10214                         goto next;
10215                 }
10216
10217 next:
10218                 if (rc == 0 && rc2 < 0)
10219                         rc = rc2;
10220         }
10221         return rc;
10222 }
10223
10224 static const char *const heat_names[] = LU_HEAT_NAMES;
10225
10226 static int lfs_heat_get(int argc, char **argv)
10227 {
10228         struct lu_heat *heat;
10229         int rc = 0, rc2;
10230         char *path;
10231         int fd;
10232         int i;
10233
10234         if (argc <= 1)
10235                 return CMD_HELP;
10236
10237         heat = calloc(sizeof(*heat) + sizeof(__u64) * OBD_HEAT_COUNT, 1);
10238         if (!heat) {
10239                 fprintf(stderr, "%s: memory allocation failed\n", argv[0]);
10240                 return -ENOMEM;
10241         }
10242
10243         optind = 1;
10244         while (optind < argc) {
10245                 path = argv[optind++];
10246
10247                 fd = open(path, O_RDONLY);
10248                 if (fd < 0) {
10249                         fprintf(stderr, "%s: cannot open file '%s': %s\n",
10250                                 argv[0], path, strerror(errno));
10251                         rc2 = -errno;
10252                         goto next;
10253                 }
10254
10255                 heat->lh_count = OBD_HEAT_COUNT;
10256                 rc2 = llapi_heat_get(fd, heat);
10257                 close(fd);
10258                 if (rc2 < 0) {
10259                         fprintf(stderr,
10260                                 "%s: cannot get heat of file '%s': %s\n",
10261                                 argv[0], path, strerror(errno));
10262                         goto next;
10263                 }
10264
10265                 printf("flags: %x\n", heat->lh_flags);
10266                 for (i = 0; i < heat->lh_count; i++)
10267                         printf("%s: %llu\n", heat_names[i],
10268                                (unsigned long long)heat->lh_heat[i]);
10269 next:
10270                 if (rc == 0 && rc2 < 0)
10271                         rc = rc2;
10272         }
10273
10274         free(heat);
10275         return rc;
10276 }
10277
10278 static int lfs_heat_set(int argc, char **argv)
10279 {
10280         struct option long_opts[] = {
10281         { .val = 'c',   .name = "clear",        .has_arg = no_argument },
10282         { .val = 'h',   .name = "help",         .has_arg = no_argument },
10283         { .val = 'o',   .name = "off",          .has_arg = no_argument },
10284         { .val = 'O',   .name = "on",           .has_arg = no_argument },
10285         { .name = NULL } };
10286         enum lu_heat_flag flags = 0;
10287         int rc = 0, rc2;
10288         char *path;
10289         int fd;
10290         int c;
10291
10292         if (argc <= 1)
10293                 return CMD_HELP;
10294
10295         optind = 0;
10296         while ((c = getopt_long(argc, argv, "choO", long_opts, NULL)) != -1) {
10297                 switch (c) {
10298                 case 'c':
10299                         flags |= LU_HEAT_FLAG_CLEAR;
10300                         break;
10301                 case 'o':
10302                         flags |= LU_HEAT_FLAG_CLEAR;
10303                         flags |= LU_HEAT_FLAG_OFF;
10304                         break;
10305                 case 'O':
10306                         flags &= ~LU_HEAT_FLAG_OFF;
10307                         break;
10308                 default:
10309                         fprintf(stderr, "%s: unrecognized option '%s'\n",
10310                                 progname, argv[optind - 1]);
10311                         /* fallthrough */
10312                 case 'h':
10313                         return CMD_HELP;
10314                 }
10315         }
10316
10317         if (argc <= optind) {
10318                 fprintf(stderr, "%s: please give one or more file names\n",
10319                         argv[0]);
10320                 return CMD_HELP;
10321         }
10322
10323         while (optind < argc) {
10324                 path = argv[optind++];
10325
10326                 fd = open(path, O_RDONLY);
10327                 if (fd < 0) {
10328                         fprintf(stderr, "%s: cannot open file '%s': %s\n",
10329                                 argv[0], path, strerror(errno));
10330                         rc2 = -errno;
10331                         goto next;
10332                 }
10333
10334                 rc2 = llapi_heat_set(fd, flags);
10335                 close(fd);
10336                 if (rc2 < 0) {
10337                         fprintf(stderr,
10338                                 "%s: cannot setflags heat of file '%s': %s\n",
10339                                 argv[0], path, strerror(errno));
10340                         goto next;
10341                 }
10342 next:
10343                 if (rc == 0 && rc2 < 0)
10344                         rc = rc2;
10345         }
10346         return rc;
10347 }
10348
10349 /**
10350  * The input string contains a comma delimited list of component ids and
10351  * ranges, for example "1,2-4,7".
10352  */
10353 static int parse_mirror_ids(__u16 *ids, int size, char *arg)
10354 {
10355         bool end_of_loop = false;
10356         char *ptr = NULL;
10357         int nr = 0;
10358         int rc;
10359
10360         if (!arg)
10361                 return -EINVAL;
10362
10363         while (!end_of_loop) {
10364                 int start_index;
10365                 int end_index;
10366                 int i;
10367                 char *endptr = NULL;
10368
10369                 rc = -EINVAL;
10370                 ptr = strchrnul(arg, ',');
10371                 end_of_loop = *ptr == '\0';
10372                 *ptr = '\0';
10373
10374                 start_index = strtol(arg, &endptr, 0);
10375                 if (endptr == arg) /* no data at all */
10376                         break;
10377                 if (*endptr != '-' && *endptr != '\0') /* has invalid data */
10378                         break;
10379                 if (start_index < 0)
10380                         break;
10381
10382                 end_index = start_index;
10383                 if (*endptr == '-') {
10384                         end_index = strtol(endptr + 1, &endptr, 0);
10385                         if (*endptr != '\0')
10386                                 break;
10387                         if (end_index < start_index)
10388                                 break;
10389                 }
10390
10391                 for (i = start_index; i <= end_index && size > 0; i++) {
10392                         int j;
10393
10394                         /* remove duplicate */
10395                         for (j = 0; j < nr; j++) {
10396                                 if (ids[j] == i)
10397                                         break;
10398                         }
10399                         if (j == nr) { /* no duplicate */
10400                                 ids[nr++] = i;
10401                                 --size;
10402                         }
10403                 }
10404
10405                 if (size == 0 && i < end_index)
10406                         break;
10407
10408                 *ptr = ',';
10409                 arg = ++ptr;
10410                 rc = 0;
10411         }
10412         if (!end_of_loop && ptr)
10413                 *ptr = ',';
10414
10415         return rc < 0 ? rc : nr;
10416 }
10417
10418 /**
10419  * struct verify_mirror_id - Mirror id to be verified.
10420  * @mirror_id:   A specified mirror id.
10421  * @is_valid_id: @mirror_id is valid or not in the mirrored file.
10422  */
10423 struct verify_mirror_id {
10424         __u16 mirror_id;
10425         bool is_valid_id;
10426 };
10427
10428 /**
10429  * compare_mirror_ids() - Compare mirror ids.
10430  * @layout: Mirror component list.
10431  * @cbdata: Callback data in verify_mirror_id structure.
10432  *
10433  * This is a callback function called by llapi_layout_comp_iterate()
10434  * to compare the specified mirror id with the one in the current
10435  * component of @layout. If they are the same, then the specified
10436  * mirror id is valid.
10437  *
10438  * Return: a negative error code on failure or
10439  *         LLAPI_LAYOUT_ITER_CONT: Proceed iteration
10440  *         LLAPI_LAYOUT_ITER_STOP: Stop iteration
10441  */
10442 static inline
10443 int compare_mirror_ids(struct llapi_layout *layout, void *cbdata)
10444 {
10445         struct verify_mirror_id *mirror_id_cbdata =
10446                                  (struct verify_mirror_id *)cbdata;
10447         uint32_t mirror_id;
10448         int rc = 0;
10449
10450         rc = llapi_layout_mirror_id_get(layout, &mirror_id);
10451         if (rc < 0) {
10452                 rc = -errno;
10453                 fprintf(stderr,
10454                         "%s: llapi_layout_mirror_id_get failed: %s.\n",
10455                         progname, strerror(errno));
10456                 return rc;
10457         }
10458
10459         if (mirror_id_cbdata->mirror_id == mirror_id) {
10460                 mirror_id_cbdata->is_valid_id = true;
10461                 return LLAPI_LAYOUT_ITER_STOP;
10462         }
10463
10464         return LLAPI_LAYOUT_ITER_CONT;
10465 }
10466
10467 /**
10468  * verify_mirror_ids() - Verify specified mirror ids.
10469  * @fname:      Mirrored file name.
10470  * @mirror_ids: Specified mirror ids to be verified.
10471  * @ids_nr:     Number of specified mirror ids.
10472  *
10473  * This function verifies that specified @mirror_ids are valid
10474  * in the mirrored file @fname.
10475  *
10476  * Return: 0 on success or a negative error code on failure.
10477  */
10478 static inline
10479 int verify_mirror_ids(const char *fname, __u16 *mirror_ids, int ids_nr)
10480 {
10481         struct llapi_layout *layout = NULL;
10482         struct verify_mirror_id mirror_id_cbdata = { 0 };
10483         struct stat stbuf;
10484         uint32_t flr_state;
10485         int i;
10486         int fd;
10487         int rc = 0;
10488         int rc2 = 0;
10489
10490         if (ids_nr <= 0)
10491                 return -EINVAL;
10492
10493         if (stat(fname, &stbuf) < 0) {
10494                 fprintf(stderr, "%s: cannot stat file '%s': %s.\n",
10495                         progname, fname, strerror(errno));
10496                 rc = -errno;
10497                 goto error;
10498         }
10499
10500         if (!S_ISREG(stbuf.st_mode)) {
10501                 fprintf(stderr, "%s: '%s' is not a regular file.\n",
10502                         progname, fname);
10503                 rc = -EINVAL;
10504                 goto error;
10505         }
10506
10507         fd = open(fname, O_DIRECT | O_RDONLY);
10508         if (fd < 0) {
10509                 fprintf(stderr, "%s: cannot open '%s': %s.\n",
10510                         progname, fname, strerror(errno));
10511                 rc = -errno;
10512                 goto error;
10513         }
10514
10515         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
10516         if (rc < 0) {
10517                 fprintf(stderr, "%s: '%s' llapi_lease_acquire failed: %s.\n",
10518                         progname, fname, strerror(errno));
10519                 goto close_fd;
10520         }
10521
10522         layout = llapi_layout_get_by_fd(fd, 0);
10523         if (!layout) {
10524                 fprintf(stderr, "%s: '%s' llapi_layout_get_by_fd failed: %s.\n",
10525                         progname, fname, strerror(errno));
10526                 rc = -errno;
10527                 llapi_lease_release(fd);
10528                 goto close_fd;
10529         }
10530
10531         rc = llapi_layout_flags_get(layout, &flr_state);
10532         if (rc < 0) {
10533                 fprintf(stderr, "%s: '%s' llapi_layout_flags_get failed: %s.\n",
10534                         progname, fname, strerror(errno));
10535                 rc = -errno;
10536                 goto free_layout;
10537         }
10538
10539         flr_state &= LCM_FL_FLR_MASK;
10540         switch (flr_state) {
10541         case LCM_FL_NONE:
10542                 rc = -EINVAL;
10543                 fprintf(stderr, "%s: '%s' file state error: %s.\n",
10544                         progname, fname, llapi_layout_flags_string(flr_state));
10545                 goto free_layout;
10546         default:
10547                 break;
10548         }
10549
10550         rc2 = 0;
10551         for (i = 0; i < ids_nr; i++) {
10552                 mirror_id_cbdata.mirror_id = mirror_ids[i];
10553                 mirror_id_cbdata.is_valid_id = false;
10554
10555                 rc = llapi_layout_comp_iterate(layout, compare_mirror_ids,
10556                                                &mirror_id_cbdata);
10557                 if (rc < 0) {
10558                         rc = -errno;
10559                         fprintf(stderr,
10560                                 "%s: '%s' failed to verify mirror id: %u.\n",
10561                                 progname, fname, mirror_ids[i]);
10562                         goto free_layout;
10563                 }
10564
10565                 if (!mirror_id_cbdata.is_valid_id) {
10566                         rc2 = -EINVAL;
10567                         fprintf(stderr,
10568                                 "%s: '%s' invalid specified mirror id: %u.\n",
10569                                 progname, fname, mirror_ids[i]);
10570                 }
10571         }
10572         rc = rc2;
10573
10574 free_layout:
10575         llapi_layout_free(layout);
10576         llapi_lease_release(fd);
10577 close_fd:
10578         close(fd);
10579 error:
10580         return rc;
10581 }
10582
10583 static inline
10584 int lfs_mirror_resync_file(const char *fname, struct ll_ioc_lease *ioc,
10585                            __u16 *mirror_ids, int ids_nr)
10586 {
10587         struct llapi_resync_comp comp_array[1024] = { { 0 } };
10588         struct llapi_layout *layout;
10589         struct stat stbuf;
10590         uint32_t flr_state;
10591         uint64_t start;
10592         uint64_t end;
10593         int comp_size = 0;
10594         int idx;
10595         int fd;
10596         int rc;
10597         int rc2;
10598
10599         if (stat(fname, &stbuf) < 0) {
10600                 fprintf(stderr, "%s: cannot stat file '%s': %s.\n",
10601                         progname, fname, strerror(errno));
10602                 rc = -errno;
10603                 goto error;
10604         }
10605         if (!S_ISREG(stbuf.st_mode)) {
10606                 fprintf(stderr, "%s: '%s' is not a regular file.\n",
10607                         progname, fname);
10608                 rc = -EINVAL;
10609                 goto error;
10610         }
10611
10612         /* Allow mirror resync even without the key on encrypted files */
10613         fd = open(fname, O_DIRECT | O_RDWR | O_FILE_ENC);
10614         if (fd < 0) {
10615                 fprintf(stderr, "%s: cannot open '%s': %s.\n",
10616                         progname, fname, strerror(errno));
10617                 rc = -errno;
10618                 goto error;
10619         }
10620
10621         layout = llapi_layout_get_by_fd(fd, 0);
10622         if (!layout) {
10623                 fprintf(stderr, "%s: '%s' llapi_layout_get_by_fd failed: %s.\n",
10624                         progname, fname, strerror(errno));
10625                 rc = -errno;
10626                 goto close_fd;
10627         }
10628
10629         rc = llapi_layout_flags_get(layout, &flr_state);
10630         if (rc) {
10631                 fprintf(stderr, "%s: '%s' llapi_layout_flags_get failed: %s.\n",
10632                         progname, fname, strerror(errno));
10633                 rc = -errno;
10634                 goto free_layout;
10635         }
10636
10637         flr_state &= LCM_FL_FLR_MASK;
10638         if (flr_state == LCM_FL_NONE) {
10639                 rc = -EINVAL;
10640                 fprintf(stderr, "%s: '%s' is not a FLR file.\n",
10641                         progname, fname);
10642                 goto free_layout;
10643         }
10644
10645         /* get stale component info */
10646         comp_size = llapi_mirror_find_stale(layout, comp_array,
10647                                             ARRAY_SIZE(comp_array),
10648                                             mirror_ids, ids_nr);
10649         if (comp_size <= 0) {
10650                 rc = comp_size;
10651                 goto free_layout;
10652         }
10653
10654         ioc->lil_mode = LL_LEASE_WRLCK;
10655         ioc->lil_flags = LL_LEASE_RESYNC;
10656         rc = llapi_lease_set(fd, ioc);
10657         if (rc < 0) {
10658                 if (rc == -EALREADY)
10659                         rc = 0;
10660                 else
10661                         fprintf(stderr,
10662                             "%s: '%s' llapi_lease_get_ext resync failed: %s.\n",
10663                                 progname, fname, strerror(-rc));
10664                 goto free_layout;
10665         }
10666
10667         /* get the read range [start, end) */
10668         start = comp_array[0].lrc_start;
10669         end = comp_array[0].lrc_end;
10670         for (idx = 1; idx < comp_size; idx++) {
10671                 if (comp_array[idx].lrc_start < start)
10672                         start = comp_array[idx].lrc_start;
10673                 if (end < comp_array[idx].lrc_end)
10674                         end = comp_array[idx].lrc_end;
10675         }
10676
10677         rc = llapi_lease_check(fd);
10678         if (rc != LL_LEASE_WRLCK) {
10679                 fprintf(stderr, "%s: '%s' lost lease lock.\n",
10680                         progname, fname);
10681                 goto free_layout;
10682         }
10683
10684         rc = llapi_mirror_resync_many(fd, layout, comp_array, comp_size,
10685                                       start, end);
10686         if (rc < 0)
10687                 fprintf(stderr, "%s: '%s' llapi_mirror_resync_many: %s.\n",
10688                         progname, fname, strerror(-rc));
10689
10690         rc = migrate_set_timestamps(fd, &stbuf);
10691         if (rc < 0) {
10692                 fprintf(stderr, "%s: '%s' cannot set timestamps: %s\n",
10693                         progname, fname, strerror(-rc));
10694                 goto free_layout;
10695         }
10696
10697         /* need to do the lease unlock even resync fails */
10698         ioc->lil_mode = LL_LEASE_UNLCK;
10699         ioc->lil_flags = LL_LEASE_RESYNC_DONE;
10700         ioc->lil_count = 0;
10701         for (idx = 0; idx < comp_size; idx++) {
10702                 if (comp_array[idx].lrc_synced) {
10703                         ioc->lil_ids[ioc->lil_count] = comp_array[idx].lrc_id;
10704                         ioc->lil_count++;
10705                 }
10706         }
10707
10708         rc2 = llapi_lease_set(fd, ioc);
10709         /**
10710          * llapi_lease_set returns lease mode when it request to unlock
10711          * the lease lock.
10712          */
10713         if (rc2 <= 0) {
10714                 /* rc2 == 0 means lost lease lock */
10715                 if (rc2 == 0 && rc == 0)
10716                         rc = -EBUSY;
10717                 else
10718                         rc = rc2;
10719                 fprintf(stderr, "%s: resync file '%s' failed: %s.\n",
10720                         progname, fname,
10721                         rc2 == 0 ? "lost lease lock" : strerror(-rc2));
10722
10723                 llapi_lease_release(fd);
10724                 goto free_layout;
10725         }
10726
10727 free_layout:
10728         llapi_layout_free(layout);
10729 close_fd:
10730         close(fd);
10731 error:
10732         return rc;
10733 }
10734
10735 static inline int lfs_mirror_resync(int argc, char **argv)
10736 {
10737         struct option long_opts[] = {
10738         { .val = 'h',   .name = "help",         .has_arg = no_argument },
10739         { .val = 'o',   .name = "only",         .has_arg = required_argument },
10740         { .name = NULL } };
10741         struct ll_ioc_lease *ioc = NULL;
10742         __u16 mirror_ids[128] = { 0 };
10743         int ids_nr = 0;
10744         int c;
10745         int rc = 0;
10746
10747         while ((c = getopt_long(argc, argv, "ho:", long_opts, NULL)) >= 0) {
10748                 switch (c) {
10749                 case 'o':
10750                         rc = parse_mirror_ids(mirror_ids,
10751                                         sizeof(mirror_ids) / sizeof(__u16),
10752                                         optarg);
10753                         if (rc < 0) {
10754                                 fprintf(stderr,
10755                                         "%s: bad mirror ids '%s'.\n",
10756                                         argv[0], optarg);
10757                                 goto error;
10758                         }
10759                         ids_nr = rc;
10760                         break;
10761                 default:
10762                         fprintf(stderr, "%s: unrecognized option '%s'\n",
10763                                 progname, argv[optind - 1]);
10764                         /* fallthrough */
10765                 case 'h':
10766                         rc = CMD_HELP;
10767                         goto error;
10768                 }
10769         }
10770
10771         if (argc == optind) {
10772                 fprintf(stderr, "%s: no file name given.\n", argv[0]);
10773                 rc = CMD_HELP;
10774                 goto error;
10775         }
10776
10777         if (ids_nr > 0 && argc > optind + 1) {
10778                 fprintf(stderr,
10779                     "%s: option '--only' cannot be used upon multiple files.\n",
10780                         argv[0]);
10781                 rc = CMD_HELP;
10782                 goto error;
10783         }
10784
10785         if (ids_nr > 0) {
10786                 rc = verify_mirror_ids(argv[optind], mirror_ids, ids_nr);
10787                 if (rc < 0)
10788                         goto error;
10789         }
10790
10791         /* set the lease on the file */
10792         ioc = calloc(sizeof(*ioc) + sizeof(__u32) * 4096, 1);
10793         if (!ioc) {
10794                 fprintf(stderr, "%s: cannot alloc id array for ioc: %s.\n",
10795                         argv[0], strerror(errno));
10796                 rc = -errno;
10797                 goto error;
10798         }
10799
10800         for (; optind < argc; optind++) {
10801                 rc = lfs_mirror_resync_file(argv[optind], ioc,
10802                                             mirror_ids, ids_nr);
10803                 /* ignore previous file's error, continue with next file */
10804
10805                 /* reset ioc */
10806                 memset(ioc, 0, sizeof(*ioc) + sizeof(__u32) * 4096);
10807         }
10808
10809         free(ioc);
10810 error:
10811         return rc;
10812 }
10813
10814 static inline int verify_mirror_id_by_fd(int fd, __u16 mirror_id)
10815 {
10816         struct llapi_layout *layout;
10817         int rc;
10818
10819         layout = llapi_layout_get_by_fd(fd, 0);
10820         if (!layout) {
10821                 fprintf(stderr, "could not get layout.\n");
10822                 return  -EINVAL;
10823         }
10824
10825         rc = llapi_layout_comp_iterate(layout, find_mirror_id, &mirror_id);
10826         if (rc < 0) {
10827                 fprintf(stderr, "failed to iterate layout\n");
10828                 llapi_layout_free(layout);
10829
10830                 return rc;
10831         } else if (rc == LLAPI_LAYOUT_ITER_CONT) {
10832                 fprintf(stderr, "does not find mirror with ID %u\n", mirror_id);
10833                 llapi_layout_free(layout);
10834
10835                 return -EINVAL;
10836         }
10837         llapi_layout_free(layout);
10838
10839         return 0;
10840 }
10841
10842 /**
10843  * Check whether two files are the same file
10844  * \retval      0  same file
10845  * \retval      1  not the same file
10846  * \retval      <0 error code
10847  */
10848 static inline int check_same_file(int fd, const char *f2)
10849 {
10850         struct stat stbuf1;
10851         struct stat stbuf2;
10852
10853         if (fstat(fd, &stbuf1) < 0)
10854                 return -errno;
10855
10856         if (stat(f2, &stbuf2) < 0)
10857                 return 1;
10858
10859         if (stbuf1.st_rdev == stbuf2.st_rdev &&
10860             stbuf1.st_ino == stbuf2.st_ino)
10861                 return 0;
10862
10863         return 1;
10864 }
10865
10866 static inline int lfs_mirror_read(int argc, char **argv)
10867 {
10868         int rc = CMD_HELP;
10869         __u16 mirror_id = 0;
10870         const char *outfile = NULL;
10871         char *fname;
10872         int fd = 0;
10873         int outfd;
10874         int c;
10875         void *buf;
10876         const size_t buflen = 4 << 20;
10877         off_t pos;
10878         struct option long_opts[] = {
10879         { .val = 'h',   .name = "help",         .has_arg = no_argument },
10880         { .val = 'N',   .name = "mirror-id",    .has_arg = required_argument },
10881         { .val = 'o',   .name = "outfile",      .has_arg = required_argument },
10882         { .name = NULL } };
10883
10884         while ((c = getopt_long(argc, argv, "hN:o:", long_opts, NULL)) >= 0) {
10885                 char *end;
10886
10887                 switch (c) {
10888                 case 'N': {
10889                         unsigned long int id;
10890
10891                         errno = 0;
10892                         id = strtoul(optarg, &end, 0);
10893                         if (errno != 0 || *end != '\0' || id == 0 ||
10894                             id > UINT16_MAX) {
10895                                 fprintf(stderr,
10896                                         "%s %s: invalid mirror ID '%s'\n",
10897                                         progname, argv[0], optarg);
10898                                 return rc;
10899                         }
10900
10901                         mirror_id = (__u16)id;
10902                         break;
10903                 }
10904                 case 'o':
10905                         outfile = optarg;
10906                         break;
10907                 default:
10908                         fprintf(stderr, "%s: unrecognized option '%s'\n",
10909                                 progname, argv[optind - 1]);
10910                         /* fallthrough */
10911                 case 'h':
10912                         return CMD_HELP;
10913                 }
10914         }
10915
10916         if (argc == optind) {
10917                 fprintf(stderr, "%s %s: no mirrored file provided\n",
10918                         progname, argv[0]);
10919                 return rc;
10920         } else if (argc > optind + 1) {
10921                 fprintf(stderr, "%s %s: too many files\n", progname, argv[0]);
10922                 return rc;
10923         }
10924
10925         if (mirror_id == 0) {
10926                 fprintf(stderr, "%s %s: no valid mirror ID is provided\n",
10927                         progname, argv[0]);
10928                 return rc;
10929         }
10930
10931         /* open mirror file */
10932         fname = argv[optind];
10933         fd = open(fname, O_DIRECT | O_RDONLY);
10934         if (fd < 0) {
10935                 fprintf(stderr, "%s %s: cannot open '%s': %s\n",
10936                         progname, argv[0], fname, strerror(errno));
10937                 return rc;
10938         }
10939
10940         /* verify mirror id */
10941         rc = verify_mirror_id_by_fd(fd, mirror_id);
10942         if (rc) {
10943                 fprintf(stderr,
10944                         "%s %s: cannot find mirror with ID %u in '%s'\n",
10945                         progname, argv[0], mirror_id, fname);
10946                 goto close_fd;
10947         }
10948
10949         /* open output file - O_EXCL ensures output is not the same as input */
10950         if (outfile) {
10951                 outfd = open(outfile, O_EXCL | O_WRONLY | O_CREAT, 0644);
10952                 if (outfd < 0) {
10953                         fprintf(stderr, "%s %s: cannot create file '%s': %s\n",
10954                                 progname, argv[0], outfile, strerror(errno));
10955                         rc = -errno;
10956                         goto close_fd;
10957                 }
10958         } else {
10959                 outfd = STDOUT_FILENO;
10960         }
10961
10962         /* allocate buffer */
10963         rc = posix_memalign(&buf, sysconf(_SC_PAGESIZE), buflen);
10964         if (rc) {
10965                 fprintf(stderr, "%s %s: posix_memalign returns %d\n",
10966                                 progname, argv[0], rc);
10967                 goto close_outfd;
10968         }
10969
10970         pos = 0;
10971         while (1) {
10972                 ssize_t bytes_read;
10973                 ssize_t written = 0;
10974
10975                 bytes_read = llapi_mirror_read(fd, mirror_id, buf, buflen, pos);
10976                 if (bytes_read < 0) {
10977                         rc = bytes_read;
10978                         fprintf(stderr,
10979                                 "%s %s: fail to read data from mirror %u: %s\n",
10980                                 progname, argv[0], mirror_id, strerror(-rc));
10981                         goto free_buf;
10982                 }
10983
10984                 /* EOF reached */
10985                 if (bytes_read == 0)
10986                         break;
10987
10988                 while (written < bytes_read) {
10989                         ssize_t written2;
10990
10991                         written2 = write(outfd, buf + written,
10992                                          bytes_read - written);
10993                         if (written2 < 0) {
10994                                 fprintf(stderr,
10995                                         "%s %s: fail to write %s: %s\n",
10996                                         progname, argv[0], outfile ? : "STDOUT",
10997                                         strerror(errno));
10998                                 rc = -errno;
10999                                 goto free_buf;
11000                         }
11001                         written += written2;
11002                 }
11003
11004                 if (written != bytes_read) {
11005                         fprintf(stderr,
11006                 "%s %s: written %ld bytes does not match with %ld read.\n",
11007                                 progname, argv[0], written, bytes_read);
11008                         rc = -EIO;
11009                         goto free_buf;
11010                 }
11011
11012                 pos += bytes_read;
11013         }
11014
11015         fsync(outfd);
11016         rc = 0;
11017
11018 free_buf:
11019         free(buf);
11020 close_outfd:
11021         if (outfile)
11022                 close(outfd);
11023 close_fd:
11024         close(fd);
11025
11026         return rc;
11027 }
11028
11029 static inline int lfs_mirror_write(int argc, char **argv)
11030 {
11031         int rc = CMD_HELP;
11032         __u16 mirror_id = 0;
11033         const char *inputfile = NULL;
11034         char *fname;
11035         int fd = 0;
11036         int inputfd;
11037         int c;
11038         void *buf;
11039         const size_t buflen = 4 << 20;
11040         off_t pos;
11041         size_t page_size = sysconf(_SC_PAGESIZE);
11042         struct ll_ioc_lease_id ioc;
11043         struct option long_opts[] = {
11044         { .val = 'h',   .name = "help",         .has_arg = no_argument },
11045         { .val = 'i',   .name = "inputfile",    .has_arg = required_argument },
11046         { .val = 'N',   .name = "mirror-id",    .has_arg = required_argument },
11047         { .name = NULL } };
11048
11049         while ((c = getopt_long(argc, argv, "hi:N:", long_opts, NULL)) >= 0) {
11050                 char *end;
11051
11052                 switch (c) {
11053                 case 'N': {
11054                         unsigned long int id;
11055
11056                         errno = 0;
11057                         id = strtoul(optarg, &end, 0);
11058                         if (errno != 0 || *end != '\0' || id == 0 ||
11059                             id > UINT16_MAX) {
11060                                 fprintf(stderr,
11061                                         "%s %s: invalid mirror ID '%s'\n",
11062                                         progname, argv[0], optarg);
11063                                 return rc;
11064                         }
11065
11066                         mirror_id = (__u16)id;
11067                         break;
11068                 }
11069                 case 'i':
11070                         inputfile = optarg;
11071                         break;
11072                 default:
11073                         fprintf(stderr, "%s: unrecognized option '%s'\n",
11074                                 progname, argv[optind - 1]);
11075                         /* fallthrough */
11076                 case 'h':
11077                         return CMD_HELP;
11078                 }
11079         }
11080
11081         if (argc == optind) {
11082                 fprintf(stderr, "%s %s: no mirrored file provided\n",
11083                         progname, argv[0]);
11084                 return rc;
11085         } else if (argc > optind + 1) {
11086                 fprintf(stderr, "%s %s: too many files\n", progname, argv[0]);
11087                 return rc;
11088         }
11089
11090         if (mirror_id == 0) {
11091                 fprintf(stderr, "%s %s: no valid mirror ID is provided\n",
11092                         progname, argv[0]);
11093                 return rc;
11094         }
11095
11096         /* open mirror file */
11097         fname = argv[optind];
11098         fd = open(fname, O_DIRECT | O_WRONLY);
11099         if (fd < 0) {
11100                 fprintf(stderr, "%s %s: cannot open '%s': %s\n",
11101                         progname, argv[0], fname, strerror(errno));
11102                 return rc;
11103         }
11104
11105         /* verify mirror id */
11106         rc = verify_mirror_id_by_fd(fd, mirror_id);
11107         if (rc) {
11108                 fprintf(stderr,
11109                         "%s %s: cannot find mirror with ID %u in '%s'\n",
11110                         progname, argv[0], mirror_id, fname);
11111                 goto close_fd;
11112         }
11113
11114         /* open input file */
11115         if (inputfile) {
11116                 rc = check_same_file(fd, inputfile);
11117                 if (rc == 0) {
11118                         fprintf(stderr,
11119                         "%s %s: input file cannot be the mirrored file\n",
11120                                 progname, argv[0]);
11121                         goto close_fd;
11122                 }
11123                 if (rc < 0)
11124                         goto close_fd;
11125
11126                 inputfd = open(inputfile, O_RDONLY, 0644);
11127                 if (inputfd < 0) {
11128                         fprintf(stderr, "%s %s: cannot open file '%s': %s\n",
11129                                 progname, argv[0], inputfile, strerror(errno));
11130                         rc = -errno;
11131                         goto close_fd;
11132                 }
11133         } else {
11134                 inputfd = STDIN_FILENO;
11135         }
11136
11137         /* allocate buffer */
11138         rc = posix_memalign(&buf, page_size, buflen);
11139         if (rc) {
11140                 fprintf(stderr, "%s %s: posix_memalign returns %d\n",
11141                         progname, argv[0], rc);
11142                 goto close_inputfd;
11143         }
11144
11145         /* prepare target mirror components instantiation */
11146         ioc.lil_mode = LL_LEASE_WRLCK;
11147         ioc.lil_flags = LL_LEASE_RESYNC;
11148         ioc.lil_mirror_id = mirror_id;
11149         rc = llapi_lease_set(fd, (struct ll_ioc_lease *)&ioc);
11150         if (rc < 0) {
11151                 fprintf(stderr,
11152                         "%s %s: '%s' llapi_lease_get_ext failed: %s\n",
11153                         progname, argv[0], fname, strerror(errno));
11154                 goto free_buf;
11155         }
11156
11157         pos = 0;
11158         while (1) {
11159                 ssize_t bytes_read;
11160                 ssize_t written;
11161                 size_t to_write;
11162
11163                 rc = llapi_lease_check(fd);
11164                 if (rc != LL_LEASE_WRLCK) {
11165                         fprintf(stderr, "%s %s: '%s' lost lease lock\n",
11166                                 progname, argv[0], fname);
11167                         goto free_buf;
11168                 }
11169
11170                 bytes_read = read(inputfd, buf, buflen);
11171                 if (bytes_read < 0) {
11172                         rc = bytes_read;
11173                         fprintf(stderr,
11174                                 "%s %s: fail to read data from '%s': %s\n",
11175                                 progname, argv[0], inputfile ? : "STDIN",
11176                                 strerror(errno));
11177                         rc = -errno;
11178                         goto free_buf;
11179                 }
11180
11181                 /* EOF reached */
11182                 if (bytes_read == 0)
11183                         break;
11184
11185                 /* round up to page align to make direct IO happy. */
11186                 to_write = (bytes_read + page_size - 1) & ~(page_size - 1);
11187
11188                 written = llapi_mirror_write(fd, mirror_id, buf, to_write,
11189                                              pos);
11190                 if (written < 0) {
11191                         rc = written;
11192                         fprintf(stderr,
11193                               "%s %s: fail to write to mirror %u: %s\n",
11194                                 progname, argv[0], mirror_id,
11195                                 strerror(-rc));
11196                         goto free_buf;
11197                 }
11198
11199                 pos += bytes_read;
11200         }
11201
11202         if (pos & (page_size - 1)) {
11203                 rc = llapi_mirror_truncate(fd, mirror_id, pos);
11204                 if (rc < 0)
11205                         goto free_buf;
11206         }
11207
11208         ioc.lil_mode = LL_LEASE_UNLCK;
11209         ioc.lil_flags = LL_LEASE_RESYNC_DONE;
11210         ioc.lil_count = 0;
11211         rc = llapi_lease_set(fd, (struct ll_ioc_lease *)&ioc);
11212         if (rc <= 0) {
11213                 if (rc == 0)
11214                         rc = -EBUSY;
11215                 fprintf(stderr,
11216                         "%s %s: release lease lock of '%s' failed: %s\n",
11217                         progname, argv[0], fname, strerror(errno));
11218                 goto free_buf;
11219         }
11220
11221         rc = 0;
11222
11223 free_buf:
11224         free(buf);
11225 close_inputfd:
11226         if (inputfile)
11227                 close(inputfd);
11228 close_fd:
11229         close(fd);
11230
11231         return rc;
11232 }
11233
11234 static inline int get_other_mirror_ids(int fd, __u16 *ids, __u16 exclude_id)
11235 {
11236         struct llapi_layout *layout;
11237         struct collect_ids_data cid = { .cid_ids = ids,
11238                                         .cid_count = 0,
11239                                         .cid_exclude = exclude_id, };
11240         int rc;
11241
11242         layout = llapi_layout_get_by_fd(fd, 0);
11243         if (!layout) {
11244                 fprintf(stderr, "could not get layout\n");
11245                 return -EINVAL;
11246         }
11247
11248         rc = llapi_layout_comp_iterate(layout, collect_mirror_id, &cid);
11249         if (rc < 0) {
11250                 fprintf(stderr, "failed to iterate layout\n");
11251                 llapi_layout_free(layout);
11252
11253                 return rc;
11254         }
11255         llapi_layout_free(layout);
11256
11257         return cid.cid_count;
11258 }
11259
11260 #ifndef MIRROR_ID_NEG
11261 #define MIRROR_ID_NEG         0x8000
11262 #endif
11263
11264 static inline int lfs_mirror_copy(int argc, char **argv)
11265 {
11266         int rc = CMD_HELP;
11267         __u16 read_mirror_id = 0;
11268         __u16 ids[128] = { 0 };
11269         int count = 0;
11270         struct llapi_layout *layout = NULL;
11271         struct llapi_resync_comp comp_array[1024] = { { 0 } };
11272         int comp_size = 0;
11273         char *fname;
11274         int fd = 0;
11275         int c;
11276         int i;
11277         ssize_t copied;
11278         struct ll_ioc_lease *ioc = NULL;
11279         struct ll_ioc_lease_id *resync_ioc;
11280         struct option long_opts[] = {
11281         { .val = 'h',   .name = "help",         .has_arg = no_argument },
11282         { .val = 'i',   .name = "read-mirror",  .has_arg = required_argument },
11283         { .val = 'o',   .name = "write-mirror", .has_arg = required_argument },
11284         { .name = NULL } };
11285         char cmd[PATH_MAX];
11286
11287         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
11288         progname = cmd;
11289         while ((c = getopt_long(argc, argv, "hi:o:", long_opts, NULL)) >= 0) {
11290                 char *end;
11291
11292                 switch (c) {
11293                 case 'i': {
11294                         unsigned long int id;
11295
11296                         errno = 0;
11297                         id = strtoul(optarg, &end, 0);
11298                         if (errno != 0 || *end != '\0' || id == 0 ||
11299                             id > UINT16_MAX) {
11300                                 fprintf(stderr,
11301                                         "%s: invalid read mirror ID '%s'\n",
11302                                         progname, optarg);
11303                                 return rc;
11304                         }
11305
11306                         read_mirror_id = (__u16)id;
11307                         break;
11308                 }
11309                 case 'o':
11310                         if (!strcmp(optarg, "-1")) {
11311                                 /* specify all other mirrors */
11312                                 ids[0] = (__u16)-1;
11313                                 count = 1;
11314                         } else {
11315                                 count = parse_mirror_ids((__u16 *)ids,
11316                                                          ARRAY_SIZE(ids),
11317                                                          optarg);
11318                                 if (count < 0)
11319                                         return rc;
11320                         }
11321                         break;
11322                 default:
11323                         fprintf(stderr, "%s: unrecognized option '%s'\n",
11324                                 progname, argv[optind - 1]);
11325                         /* fallthrough */
11326                 case 'h':
11327                         return CMD_HELP;
11328                 }
11329         }
11330
11331         if (argc == optind) {
11332                 fprintf(stderr, "%s %s: no mirrored file provided\n",
11333                         progname, argv[0]);
11334                 return rc;
11335         } else if (argc > optind + 1) {
11336                 fprintf(stderr, "%s %s: too many files\n", progname, argv[0]);
11337                 return rc;
11338         }
11339
11340         if (read_mirror_id == 0) {
11341                 fprintf(stderr,
11342                         "%s %s: no valid read mirror ID %d is provided\n",
11343                         progname, argv[0], read_mirror_id);
11344                 return rc;
11345         }
11346
11347         if (count == 0) {
11348                 fprintf(stderr,
11349                         "%s %s: no write mirror ID is provided\n",
11350                         progname, argv[0]);
11351                 return rc;
11352         }
11353
11354         for (i = 0; i < count; i++) {
11355                 if (read_mirror_id == ids[i]) {
11356                         fprintf(stderr,
11357                         "%s %s: read and write mirror ID cannot be the same\n",
11358                                 progname, argv[0]);
11359                         return rc;
11360                 }
11361         }
11362
11363         /* open mirror file */
11364         fname = argv[optind];
11365
11366         fd = open(fname, O_DIRECT | O_RDWR);
11367         if (fd < 0) {
11368                 fprintf(stderr, "%s %s: cannot open '%s': %s\n",
11369                         progname, argv[0], fname, strerror(errno));
11370                 return rc;
11371         }
11372
11373         /* write to all other mirrors */
11374         if (ids[0] == (__u16)-1) {
11375                 count = get_other_mirror_ids(fd, ids, read_mirror_id);
11376                 if (count <= 0) {
11377                         rc = count;
11378                         fprintf(stderr,
11379                         "%s %s: failed to get other mirror ids in '%s': %d\n",
11380                                 progname, argv[0], fname, rc);
11381                         goto close_fd;
11382                 }
11383         }
11384
11385         /* verify mirror id */
11386         rc = verify_mirror_id_by_fd(fd, read_mirror_id);
11387         if (rc) {
11388                 fprintf(stderr,
11389                         "%s %s: cannot find mirror with ID %u in '%s'\n",
11390                         progname, argv[0], read_mirror_id, fname);
11391                 goto close_fd;
11392         }
11393
11394         for (i = 0; i < count; i++) {
11395                 rc = verify_mirror_id_by_fd(fd, ids[i]);
11396                 if (rc) {
11397                         fprintf(stderr,
11398                         "%s %s: cannot find mirror with ID %u in '%s'\n",
11399                                 progname, argv[0], ids[i], fname);
11400                         goto close_fd;
11401                 }
11402         }
11403
11404         ioc = calloc(sizeof(*ioc) + sizeof(__u32) * 4096, 1);
11405         if (!ioc) {
11406                 fprintf(stderr,
11407                         "%s %s: cannot alloc comp id array for ioc: %s\n",
11408                         progname, argv[0], strerror(errno));
11409                 rc = -errno;
11410                 goto close_fd;
11411         }
11412
11413         /* get stale component info */
11414         layout = llapi_layout_get_by_fd(fd, 0);
11415         if (!layout) {
11416                 fprintf(stderr, "%s %s: failed to get layout of '%s': %s\n",
11417                         progname, argv[0], fname, strerror(errno));
11418                 rc = -errno;
11419                 goto free_ioc;
11420         }
11421         comp_size = llapi_mirror_find_stale(layout, comp_array,
11422                                             ARRAY_SIZE(comp_array),
11423                                             ids, count);
11424         llapi_layout_free(layout);
11425         if (comp_size < 0) {
11426                 rc = comp_size;
11427                 goto free_ioc;
11428         }
11429
11430         /* prepare target mirror components instantiation */
11431         resync_ioc = (struct ll_ioc_lease_id *)ioc;
11432         resync_ioc->lil_mode = LL_LEASE_WRLCK;
11433         resync_ioc->lil_flags = LL_LEASE_RESYNC;
11434         if (count == 1)
11435                 resync_ioc->lil_mirror_id = ids[0];
11436         else
11437                 resync_ioc->lil_mirror_id = read_mirror_id | MIRROR_ID_NEG;
11438         rc = llapi_lease_set(fd, ioc);
11439         if (rc < 0) {
11440                 fprintf(stderr,
11441                         "%s %s: '%s' llapi_lease_get_ext failed: %s\n",
11442                         progname, argv[0], fname, strerror(errno));
11443                 goto free_ioc;
11444         }
11445
11446         copied = llapi_mirror_copy_many(fd, read_mirror_id, ids, count);
11447         if (copied < 0) {
11448                 rc = copied;
11449                 fprintf(stderr, "%s %s: copy error: %d\n",
11450                         progname, argv[0], rc);
11451                 goto free_ioc;
11452         }
11453
11454         fprintf(stdout, "mirror copied successfully: ");
11455         for (i = 0; i < copied; i++)
11456                 fprintf(stdout, "%d ", ids[i]);
11457         fprintf(stdout, "\n");
11458
11459         ioc->lil_mode = LL_LEASE_UNLCK;
11460         ioc->lil_flags = LL_LEASE_RESYNC_DONE;
11461         ioc->lil_count = 0;
11462         for (i = 0; i < comp_size; i++) {
11463                 int j;
11464
11465                 for (j = 0; j < copied; j++) {
11466                         if (comp_array[i].lrc_mirror_id != ids[j])
11467                                 continue;
11468
11469                         ioc->lil_ids[ioc->lil_count] = comp_array[i].lrc_id;
11470                         ioc->lil_count++;
11471                 }
11472         }
11473         rc = llapi_lease_set(fd, ioc);
11474         if (rc <= 0) {
11475                 if (rc == 0)
11476                         rc = -EBUSY;
11477                 fprintf(stderr,
11478                         "%s %s: release lease lock of '%s' failed: %s\n",
11479                         progname, argv[0], fname, strerror(errno));
11480                 goto free_ioc;
11481         }
11482
11483         rc = 0;
11484
11485 free_ioc:
11486         free(ioc);
11487 close_fd:
11488         close(fd);
11489
11490         return rc;
11491 }
11492
11493 /**
11494  * struct verify_chunk - Mirror chunk to be verified.
11495  * @chunk:        [start, end) of the chunk.
11496  * @mirror_count: Number of mirror ids in @mirror_id array.
11497  * @mirror_id:    Array of valid mirror ids that cover the chunk.
11498  */
11499 struct verify_chunk {
11500         struct lu_extent chunk;
11501         unsigned int mirror_count;
11502         __u16 mirror_id[LUSTRE_MIRROR_COUNT_MAX];
11503 };
11504
11505 /**
11506  * print_chunks() - Print chunk information.
11507  * @fname:       Mirrored file name.
11508  * @chunks:      Array of chunks.
11509  * @chunk_count: Number of chunks in @chunks array.
11510  *
11511  * This function prints [start, end) of each chunk in @chunks
11512  * for mirrored file @fname, and also prints the valid mirror ids
11513  * that cover the chunk.
11514  *
11515  * Return: void.
11516  */
11517 static inline
11518 void print_chunks(const char *fname, struct verify_chunk *chunks,
11519                   int chunk_count)
11520 {
11521         int i;
11522         int j;
11523
11524         fprintf(stdout, "Chunks to be verified in %s:\n", fname);
11525         for (i = 0; i < chunk_count; i++) {
11526                 fprintf(stdout, DEXT, PEXT(&chunks[i].chunk));
11527
11528                 if (chunks[i].mirror_count == 0)
11529                         fprintf(stdout, "\t[");
11530                 else {
11531                         fprintf(stdout, "\t[%u", chunks[i].mirror_id[0]);
11532                         for (j = 1; j < chunks[i].mirror_count; j++)
11533                                 fprintf(stdout, ", %u", chunks[i].mirror_id[j]);
11534                 }
11535                 fprintf(stdout, "]\t%u\n", chunks[i].mirror_count);
11536         }
11537         fprintf(stdout, "\n");
11538 }
11539
11540 /**
11541  * print_checksums() - Print CRC-32 checksum values.
11542  * @chunk: A chunk and its corresponding valid mirror ids.
11543  * @crc:   CRC-32 checksum values on the chunk for each valid mirror.
11544  *
11545  * This function prints CRC-32 checksum values on @chunk for
11546  * each valid mirror that covers it.
11547  *
11548  * Return: void.
11549  */
11550 static inline
11551 void print_checksums(struct verify_chunk *chunk, unsigned long *crc)
11552 {
11553         int i;
11554
11555         fprintf(stdout,
11556                 "CRC-32 checksum value for chunk "DEXT":\n",
11557                 PEXT(&chunk->chunk));
11558         for (i = 0; i < chunk->mirror_count; i++)
11559                 fprintf(stdout, "Mirror %u:\t%#lx\n",
11560                         chunk->mirror_id[i], crc[i]);
11561         fprintf(stdout, "\n");
11562 }
11563
11564 /**
11565  * filter_mirror_id() - Filter specified mirror ids.
11566  * @chunks:      Array of chunks.
11567  * @chunk_count: Number of chunks in @chunks array.
11568  * @mirror_ids:  Specified mirror ids to be verified.
11569  * @ids_nr:      Number of specified mirror ids.
11570  *
11571  * This function scans valid mirror ids that cover each chunk in @chunks
11572  * and filters specified mirror ids.
11573  *
11574  * Return: void.
11575  */
11576 static inline
11577 void filter_mirror_id(struct verify_chunk *chunks, int chunk_count,
11578                       __u16 *mirror_ids, int ids_nr)
11579 {
11580         int i;
11581         int j;
11582         int k;
11583         __u16 valid_id[LUSTRE_MIRROR_COUNT_MAX] = { 0 };
11584         unsigned int valid_count = 0;
11585
11586         for (i = 0; i < chunk_count; i++) {
11587                 if (chunks[i].mirror_count == 0)
11588                         continue;
11589
11590                 valid_count = 0;
11591                 for (j = 0; j < ids_nr; j++) {
11592                         for (k = 0; k < chunks[i].mirror_count; k++) {
11593                                 if (chunks[i].mirror_id[k] == mirror_ids[j]) {
11594                                         valid_id[valid_count] = mirror_ids[j];
11595                                         valid_count++;
11596                                         break;
11597                                 }
11598                         }
11599                 }
11600
11601                 memcpy(chunks[i].mirror_id, valid_id,
11602                        sizeof(__u16) * valid_count);
11603                 chunks[i].mirror_count = valid_count;
11604         }
11605 }
11606
11607 /**
11608  * lfs_mirror_prepare_chunk() - Find mirror chunks to be verified.
11609  * @layout:      Mirror component list.
11610  * @chunks:      Array of chunks.
11611  * @chunks_size: Array size of @chunks.
11612  *
11613  * This function scans the components in @layout from offset 0 to LUSTRE_EOF
11614  * to find out chunk segments and store them in @chunks array.
11615  *
11616  * The @mirror_id array in each element of @chunks will store the valid
11617  * mirror ids that cover the chunk. If a mirror component covering the
11618  * chunk has LCME_FL_STALE or LCME_FL_OFFLINE flag, then the mirror id
11619  * will not be stored into the @mirror_id array, and the chunk for that
11620  * mirror will not be verified.
11621  *
11622  * The @mirror_count in each element of @chunks will store the number of
11623  * mirror ids in @mirror_id array. If @mirror_count is 0, it indicates the
11624  * chunk is invalid in all of the mirrors. And if @mirror_count is 1, it
11625  * indicates the chunk is valid in only one mirror. In both cases, the
11626  * chunk will not be verified.
11627  *
11628  * Here is an example:
11629  *
11630  *  0      1M     2M     3M     4M           EOF
11631  *  +------+-------------+--------------------+
11632  *  |      |             |      S             |       mirror1
11633  *  +------+------+------+------+-------------+
11634  *  |             |   S  |   S  |             |       mirror2
11635  *  +-------------+------+------+-------------+
11636  *
11637  * prepared @chunks array will contain 5 elements:
11638  * (([0, 1M), [1, 2], 2),
11639  *  ([1M, 2M), [1, 2], 2),
11640  *  ([2M, 3M), [1], 1),
11641  *  ([3M, 4M], [], 0),
11642  *  ([4M, EOF), [2], 1))
11643  *
11644  * Return: the actual array size of @chunks on success
11645  *         or a negative error code on failure.
11646  */
11647 static inline
11648 int lfs_mirror_prepare_chunk(struct llapi_layout *layout,
11649                              struct verify_chunk *chunks,
11650                              size_t chunks_size)
11651 {
11652         uint64_t start;
11653         uint64_t end;
11654         uint32_t mirror_id;
11655         uint32_t flags;
11656         int idx = 0;
11657         int i = 0;
11658         int rc = 0;
11659
11660         memset(chunks, 0, sizeof(*chunks) * chunks_size);
11661
11662         while (1) {
11663                 rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_FIRST);
11664                 if (rc < 0) {
11665                         fprintf(stderr,
11666                                 "%s: move to the first layout component: %s.\n",
11667                                 progname, strerror(errno));
11668                         goto error;
11669                 }
11670
11671                 i = 0;
11672                 rc = 0;
11673                 chunks[idx].chunk.e_end = LUSTRE_EOF;
11674                 while (rc == 0) {
11675                         rc = llapi_layout_comp_extent_get(layout, &start, &end);
11676                         if (rc < 0) {
11677                                 fprintf(stderr,
11678                                         "%s: llapi_layout_comp_extent_get failed: %s.\n",
11679                                         progname, strerror(errno));
11680                                 goto error;
11681                         }
11682
11683                         if (start > chunks[idx].chunk.e_start ||
11684                             end <= chunks[idx].chunk.e_start)
11685                                 goto next;
11686
11687                         if (end < chunks[idx].chunk.e_end)
11688                                 chunks[idx].chunk.e_end = end;
11689
11690                         rc = llapi_layout_comp_flags_get(layout, &flags);
11691                         if (rc < 0) {
11692                                 fprintf(stderr,
11693                                         "%s: llapi_layout_comp_flags_get failed: %s.\n",
11694                                         progname, strerror(errno));
11695                                 goto error;
11696                         }
11697
11698                         if (flags & LCME_FL_STALE || flags & LCME_FL_OFFLINE)
11699                                 goto next;
11700
11701                         rc = llapi_layout_mirror_id_get(layout, &mirror_id);
11702                         if (rc < 0) {
11703                                 fprintf(stderr,
11704                                         "%s: llapi_layout_mirror_id_get failed: %s.\n",
11705                                         progname, strerror(errno));
11706                                 goto error;
11707                         }
11708
11709                         chunks[idx].mirror_id[i] = mirror_id;
11710                         i++;
11711                         if (i >= ARRAY_SIZE(chunks[idx].mirror_id)) {
11712                                 fprintf(stderr,
11713                                         "%s: mirror_id array is too small.\n",
11714                                         progname);
11715                                 rc = -EINVAL;
11716                                 goto error;
11717                         }
11718
11719 next:
11720                         rc = llapi_layout_comp_use(layout,
11721                                                    LLAPI_LAYOUT_COMP_USE_NEXT);
11722                         if (rc < 0) {
11723                                 fprintf(stderr,
11724                                         "%s: move to the next layout component: %s.\n",
11725                                         progname, strerror(errno));
11726                                 goto error;
11727                         }
11728                 } /* loop through all components */
11729
11730                 chunks[idx].mirror_count = i;
11731
11732                 if (chunks[idx].chunk.e_end == LUSTRE_EOF)
11733                         break;
11734
11735                 idx++;
11736                 if (idx >= chunks_size) {
11737                         fprintf(stderr, "%s: chunks array is too small.\n",
11738                                 progname);
11739                         rc = -EINVAL;
11740                         goto error;
11741                 }
11742
11743                 chunks[idx].chunk.e_start = chunks[idx - 1].chunk.e_end;
11744         }
11745
11746 error:
11747         return rc < 0 ? rc : idx + 1;
11748 }
11749
11750 /**
11751  * lfs_mirror_verify_chunk() - Verify a chunk.
11752  * @fd:        File descriptor of the mirrored file.
11753  * @file_size: Size of the mirrored file.
11754  * @chunk:     A chunk and its corresponding valid mirror ids.
11755  * @verbose:   Verbose mode.
11756  *
11757  * This function verifies a @chunk contains exactly the same data
11758  * ammong the mirrors that cover it.
11759  *
11760  * If @verbose is specified, then the function will print where the
11761  * differences are if the data do not match. Otherwise, it will
11762  * just return an error in that case.
11763  *
11764  * Return: 0 on success or a negative error code on failure.
11765  */
11766 static inline
11767 int lfs_mirror_verify_chunk(int fd, size_t file_size,
11768                             struct verify_chunk *chunk, int verbose)
11769 {
11770         const size_t buflen = 4 * 1024 * 1024; /* 4M */
11771         void *buf;
11772         size_t page_size = sysconf(_SC_PAGESIZE);
11773         ssize_t bytes_read;
11774         ssize_t bytes_done;
11775         size_t count;
11776         off_t pos;
11777         unsigned long crc;
11778         unsigned long crc_array[LUSTRE_MIRROR_COUNT_MAX] = { 0 };
11779         int i;
11780         int rc = 0;
11781
11782         if (file_size == 0)
11783                 return 0;
11784
11785         rc = posix_memalign(&buf, page_size, buflen);
11786         if (rc) /* error code is returned directly */
11787                 return -rc;
11788
11789         if (verbose > 1) {
11790                 fprintf(stdout, "Verifying chunk "DEXT" on mirror:",
11791                         PEXT(&chunk->chunk));
11792                 for (i = 0; i < chunk->mirror_count; i++)
11793                         fprintf(stdout, " %u", chunk->mirror_id[i]);
11794                 fprintf(stdout, "\n");
11795         }
11796
11797         bytes_done = 0;
11798         count = MIN(chunk->chunk.e_end, file_size) - chunk->chunk.e_start;
11799         pos = chunk->chunk.e_start;
11800         while (bytes_done < count) {
11801                 /* compute initial CRC-32 checksum */
11802                 crc = crc32(0L, Z_NULL, 0);
11803                 memset(crc_array, 0, sizeof(crc_array));
11804
11805                 bytes_read = 0;
11806                 for (i = 0; i < chunk->mirror_count; i++) {
11807                         bytes_read = llapi_mirror_read(fd, chunk->mirror_id[i],
11808                                                        buf, buflen, pos);
11809                         if (bytes_read < 0) {
11810                                 rc = bytes_read;
11811                                 fprintf(stderr,
11812                                         "%s: failed to read data from mirror %u: %s.\n",
11813                                         progname, chunk->mirror_id[i],
11814                                         strerror(-rc));
11815                                 goto error;
11816                         }
11817
11818                         /* compute new CRC-32 checksum */
11819                         crc_array[i] = crc32(crc, buf, bytes_read);
11820                 }
11821
11822                 if (verbose)
11823                         print_checksums(chunk, crc_array);
11824
11825                 /* compare CRC-32 checksum values */
11826                 for (i = 1; i < chunk->mirror_count; i++) {
11827                         if (crc_array[i] != crc_array[0]) {
11828                                 rc = -EINVAL;
11829
11830                                 fprintf(stderr,
11831                                         "%s: chunk "DEXT" has different checksum value on mirror %u and mirror %u.\n",
11832                                         progname, PEXT(&chunk->chunk),
11833                                         chunk->mirror_id[0],
11834                                         chunk->mirror_id[i]);
11835                         }
11836                 }
11837
11838                 pos += bytes_read;
11839                 bytes_done += bytes_read;
11840         }
11841
11842         if (verbose > 1 && rc == 0) {
11843                 fprintf(stdout, "Verifying chunk "DEXT" on mirror:",
11844                         PEXT(&chunk->chunk));
11845                 for (i = 0; i < chunk->mirror_count; i++)
11846                         fprintf(stdout, " %u", chunk->mirror_id[i]);
11847                 fprintf(stdout, " PASS\n\n");
11848         }
11849
11850 error:
11851         free(buf);
11852         return rc;
11853 }
11854
11855 /**
11856  * lfs_mirror_verify_file() - Verify a mirrored file.
11857  * @fname:      Mirrored file name.
11858  * @mirror_ids: Specified mirror ids to be verified.
11859  * @ids_nr:     Number of specified mirror ids.
11860  * @verbose:    Verbose mode.
11861  *
11862  * This function verifies that each SYNC mirror of a mirrored file
11863  * specified by @fname contains exactly the same data.
11864  *
11865  * If @mirror_ids is specified, then the function will verify the
11866  * mirrors specified by @mirror_ids contain exactly the same data.
11867  *
11868  * If @verbose is specified, then the function will print where the
11869  * differences are if the data do not match. Otherwise, it will
11870  * just return an error in that case.
11871  *
11872  * Return: 0 on success or a negative error code on failure.
11873  */
11874 static inline
11875 int lfs_mirror_verify_file(const char *fname, __u16 *mirror_ids, int ids_nr,
11876                            int verbose)
11877 {
11878         struct verify_chunk chunks_array[1024] = { };
11879         struct llapi_layout *layout = NULL;
11880         struct stat stbuf;
11881         uint32_t flr_state;
11882         int fd;
11883         int chunk_count = 0;
11884         int idx = 0;
11885         int rc = 0;
11886         int rc1 = 0;
11887         int rc2 = 0;
11888
11889         if (stat(fname, &stbuf) < 0) {
11890                 fprintf(stderr, "%s: cannot stat file '%s': %s.\n",
11891                         progname, fname, strerror(errno));
11892                 rc = -errno;
11893                 goto error;
11894         }
11895
11896         if (!S_ISREG(stbuf.st_mode)) {
11897                 fprintf(stderr, "%s: '%s' is not a regular file.\n",
11898                         progname, fname);
11899                 rc = -EINVAL;
11900                 goto error;
11901         }
11902
11903         if (stbuf.st_size == 0) {
11904                 if (verbose)
11905                         fprintf(stdout, "%s: '%s' file size is 0.\n",
11906                                 progname, fname);
11907                 rc = 0;
11908                 goto error;
11909         }
11910
11911         /* Allow mirror verify even without the key on encrypted files */
11912         fd = open(fname, O_DIRECT | O_RDONLY | O_FILE_ENC);
11913         if (fd < 0) {
11914                 fprintf(stderr, "%s: cannot open '%s': %s.\n",
11915                         progname, fname, strerror(errno));
11916                 rc = -errno;
11917                 goto error;
11918         }
11919
11920         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
11921         if (rc < 0) {
11922                 fprintf(stderr, "%s: '%s' llapi_lease_acquire failed: %s.\n",
11923                         progname, fname, strerror(errno));
11924                 goto close_fd;
11925         }
11926
11927         layout = llapi_layout_get_by_fd(fd, 0);
11928         if (!layout) {
11929                 fprintf(stderr, "%s: '%s' llapi_layout_get_by_fd failed: %s.\n",
11930                         progname, fname, strerror(errno));
11931                 rc = -errno;
11932                 llapi_lease_release(fd);
11933                 goto close_fd;
11934         }
11935
11936         rc = llapi_layout_flags_get(layout, &flr_state);
11937         if (rc < 0) {
11938                 fprintf(stderr, "%s: '%s' llapi_layout_flags_get failed: %s.\n",
11939                         progname, fname, strerror(errno));
11940                 rc = -errno;
11941                 goto free_layout;
11942         }
11943
11944         flr_state &= LCM_FL_FLR_MASK;
11945         switch (flr_state) {
11946         case LCM_FL_NONE:
11947                 rc = -EINVAL;
11948                 fprintf(stderr, "%s: '%s' file state error: %s.\n",
11949                         progname, fname, llapi_layout_flags_string(flr_state));
11950                 goto free_layout;
11951         default:
11952                 break;
11953         }
11954
11955         /* find out mirror chunks to be verified */
11956         chunk_count = lfs_mirror_prepare_chunk(layout, chunks_array,
11957                                                ARRAY_SIZE(chunks_array));
11958         if (chunk_count < 0) {
11959                 rc = chunk_count;
11960                 goto free_layout;
11961         }
11962
11963         if (ids_nr > 0)
11964                 /* filter specified mirror ids */
11965                 filter_mirror_id(chunks_array, chunk_count, mirror_ids, ids_nr);
11966
11967         if (verbose > 2)
11968                 print_chunks(fname, chunks_array, chunk_count);
11969
11970         for (idx = 0; idx < chunk_count; idx++) {
11971                 if (chunks_array[idx].chunk.e_start >= stbuf.st_size) {
11972                         if (verbose)
11973                                 fprintf(stdout,
11974                                         "%s: '%s' chunk "DEXT" exceeds file size %#llx: skipped\n",
11975                                         progname, fname,
11976                                         PEXT(&chunks_array[idx].chunk),
11977                                         (unsigned long long)stbuf.st_size);
11978                         break;
11979                 }
11980
11981                 if (chunks_array[idx].mirror_count == 0) {
11982                         fprintf(stderr,
11983                                 "%s: '%s' chunk "DEXT" is invalid in all of the mirrors: ",
11984                                 progname, fname,
11985                                 PEXT(&chunks_array[idx].chunk));
11986                         if (verbose) {
11987                                 fprintf(stderr, "skipped\n");
11988                                 continue;
11989                         }
11990                         rc = -EINVAL;
11991                         fprintf(stderr, "failed\n");
11992                         goto free_layout;
11993                 }
11994
11995                 if (chunks_array[idx].mirror_count == 1) {
11996                         if (verbose)
11997                                 fprintf(stdout,
11998                                         "%s: '%s' chunk "DEXT" is only valid in mirror %u: skipped\n",
11999                                         progname, fname,
12000                                         PEXT(&chunks_array[idx].chunk),
12001                                         chunks_array[idx].mirror_id[0]);
12002                         continue;
12003                 }
12004
12005                 rc = llapi_lease_check(fd);
12006                 if (rc != LL_LEASE_RDLCK) {
12007                         fprintf(stderr, "%s: '%s' lost lease lock.\n",
12008                                 progname, fname);
12009                         goto free_layout;
12010                 }
12011
12012                 /* verify one chunk */
12013                 rc1 = lfs_mirror_verify_chunk(fd, stbuf.st_size,
12014                                               &chunks_array[idx], verbose);
12015                 if (rc1 < 0) {
12016                         rc2 = rc1;
12017                         if (!verbose) {
12018                                 rc = rc1;
12019                                 goto free_layout;
12020                         }
12021                 }
12022         }
12023
12024         if (rc2 < 0)
12025                 rc = rc2;
12026
12027 free_layout:
12028         llapi_layout_free(layout);
12029         llapi_lease_release(fd);
12030 close_fd:
12031         close(fd);
12032 error:
12033         return rc;
12034 }
12035
12036 /**
12037  * lfs_mirror_verify() - Parse and execute lfs mirror verify command.
12038  * @argc: The count of lfs mirror verify command line arguments.
12039  * @argv: Array of strings for lfs mirror verify command line arguments.
12040  *
12041  * This function parses lfs mirror verify command and verifies the
12042  * specified mirrored file(s).
12043  *
12044  * Return: 0 on success or a negative error code on failure.
12045  */
12046 static inline int lfs_mirror_verify(int argc, char **argv)
12047 {
12048         __u16 mirror_ids[LUSTRE_MIRROR_COUNT_MAX] = { 0 };
12049         int ids_nr = 0;
12050         int c;
12051         int verbose = 0;
12052         int rc = 0;
12053         int rc1 = 0;
12054         char cmd[PATH_MAX];
12055
12056         struct option long_opts[] = {
12057         { .val = 'h',   .name = "help",         .has_arg = no_argument },
12058         { .val = 'o',   .name = "only",         .has_arg = required_argument },
12059         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
12060         { .name = NULL } };
12061
12062         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
12063         progname = cmd;
12064         while ((c = getopt_long(argc, argv, "ho:v", long_opts, NULL)) >= 0) {
12065                 switch (c) {
12066                 case 'o':
12067                         rc = parse_mirror_ids(mirror_ids,
12068                                               ARRAY_SIZE(mirror_ids),
12069                                               optarg);
12070                         if (rc < 0) {
12071                                 fprintf(stderr,
12072                                         "%s: bad mirror ids '%s'.\n",
12073                                         progname, optarg);
12074                                 goto error;
12075                         }
12076                         ids_nr = rc;
12077                         if (ids_nr < 2) {
12078                                 fprintf(stderr,
12079                                         "%s: at least 2 mirror ids needed with '--only' option.\n",
12080                                         progname);
12081                                 rc = CMD_HELP;
12082                                 goto error;
12083                         }
12084                         break;
12085                 case 'v':
12086                         verbose++;
12087                         break;
12088                 default:
12089                         fprintf(stderr, "%s: unrecognized option '%s'\n",
12090                                 progname, argv[optind - 1]);
12091                         /* fallthrough */
12092                 case 'h':
12093                         rc = CMD_HELP;
12094                         goto error;
12095                 }
12096         }
12097
12098         if (argc == optind) {
12099                 fprintf(stderr, "%s: no file name given.\n", progname);
12100                 rc = CMD_HELP;
12101                 goto error;
12102         }
12103
12104         if (ids_nr > 0 && argc > optind + 1) {
12105                 fprintf(stderr,
12106                         "%s: '--only' cannot be used upon multiple files.\n",
12107                         progname);
12108                 rc = CMD_HELP;
12109                 goto error;
12110         }
12111
12112         if (ids_nr > 0) {
12113                 rc = verify_mirror_ids(argv[optind], mirror_ids, ids_nr);
12114                 if (rc < 0)
12115                         goto error;
12116         }
12117
12118         rc = 0;
12119         for (; optind < argc; optind++) {
12120                 rc1 = lfs_mirror_verify_file(argv[optind], mirror_ids, ids_nr,
12121                                              verbose);
12122                 if (rc1 < 0)
12123                         rc = rc1;
12124         }
12125 error:
12126         return rc;
12127 }
12128
12129 /**
12130  * lfs_mirror() - Parse and execute lfs mirror commands.
12131  * @argc: The count of lfs mirror command line arguments.
12132  * @argv: Array of strings for lfs mirror command line arguments.
12133  *
12134  * This function parses lfs mirror commands and performs the
12135  * corresponding functions specified in mirror_cmdlist[].
12136  *
12137  * Return: 0 on success or an error code on failure.
12138  */
12139 static int lfs_mirror(int argc, char **argv)
12140 {
12141         char cmd[PATH_MAX];
12142         int rc = 0;
12143
12144         setlinebuf(stdout);
12145
12146         Parser_init("lfs-mirror > ", mirror_cmdlist);
12147
12148         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
12149         progname = cmd;
12150         program_invocation_short_name = cmd;
12151         if (argc > 1)
12152                 rc = Parser_execarg(argc - 1, argv + 1, mirror_cmdlist);
12153         else
12154                 rc = Parser_commands();
12155
12156         return rc < 0 ? -rc : rc;
12157 }
12158
12159 static void lustre_som_swab(struct lustre_som_attrs *attrs)
12160 {
12161 #if __BYTE_ORDER == __BIG_ENDIAN
12162         __swab16s(&attrs->lsa_valid);
12163         __swab64s(&attrs->lsa_size);
12164         __swab64s(&attrs->lsa_blocks);
12165 #endif
12166 }
12167
12168 enum lfs_som_type {
12169         LFS_SOM_SIZE = 0x1,
12170         LFS_SOM_BLOCKS = 0x2,
12171         LFS_SOM_FLAGS = 0x4,
12172         LFS_SOM_ATTR_ALL = LFS_SOM_SIZE | LFS_SOM_BLOCKS |
12173                            LFS_SOM_FLAGS,
12174 };
12175
12176 static int lfs_getsom(int argc, char **argv)
12177 {
12178         const char *path;
12179         struct lustre_som_attrs *attrs;
12180         char buf[sizeof(*attrs) + 64];
12181         enum lfs_som_type type = LFS_SOM_ATTR_ALL;
12182         int rc = 0, c;
12183
12184         while ((c = getopt(argc, argv, "bfhs")) != -1) {
12185                 switch (c) {
12186                 case 'b':
12187                         type = LFS_SOM_BLOCKS;
12188                         break;
12189                 case 'f':
12190                         type = LFS_SOM_FLAGS;
12191                         break;
12192                 case 's':
12193                         type = LFS_SOM_SIZE;
12194                         break;
12195                 default:
12196                         fprintf(stderr, "%s: unrecognized option '%s'\n",
12197                                 progname, argv[optind - 1]);
12198                         /* fallthrough */
12199                 case 'h':
12200                         return CMD_HELP;
12201                 }
12202         }
12203
12204         argc -= optind;
12205         argv += optind;
12206
12207         if (argc != 1) {
12208                 fprintf(stderr, "%s: %s\n",
12209                         progname, argc == 0 ? "miss file target" :
12210                         "input more than 2 files");
12211                 return CMD_HELP;
12212         }
12213
12214         path = argv[0];
12215         attrs = (void *)buf;
12216         rc = lgetxattr(path, "trusted.som", attrs, sizeof(buf));
12217         if (rc < 0) {
12218                 rc = -errno;
12219                 fprintf(stderr, "%s failed to get som xattr: %s (%d)\n",
12220                         argv[0], strerror(errno), errno);
12221                 return rc;
12222         }
12223
12224         lustre_som_swab(attrs);
12225
12226         switch (type) {
12227         case LFS_SOM_ATTR_ALL:
12228                 printf("file: %s size: %llu blocks: %llu flags: %x\n",
12229                        path, (unsigned long long)attrs->lsa_size,
12230                        (unsigned long long)attrs->lsa_blocks,
12231                        attrs->lsa_valid);
12232                 break;
12233         case LFS_SOM_SIZE:
12234                 printf("%llu\n", (unsigned long long)attrs->lsa_size);
12235                 break;
12236         case LFS_SOM_BLOCKS:
12237                 printf("%llu\n", (unsigned long long)attrs->lsa_blocks);
12238                 break;
12239         case LFS_SOM_FLAGS:
12240                 printf("%x\n", attrs->lsa_valid);
12241                 break;
12242         default:
12243                 fprintf(stderr, "%s: unknown option\n", progname);
12244                 return CMD_HELP;
12245         }
12246
12247         return 0;
12248 }
12249
12250 /**
12251  * lfs_mirror_list_commands() - List lfs mirror commands.
12252  * @argc: The count of command line arguments.
12253  * @argv: Array of strings for command line arguments.
12254  *
12255  * This function lists lfs mirror commands defined in mirror_cmdlist[].
12256  *
12257  * Return: 0 on success.
12258  */
12259 static int lfs_mirror_list_commands(int argc, char **argv)
12260 {
12261         char buffer[81] = "";
12262
12263         Parser_list_commands(mirror_cmdlist, buffer, sizeof(buffer),
12264                              NULL, 0, 4);
12265
12266         return 0;
12267 }
12268
12269 static int lfs_pcc_attach(int argc, char **argv)
12270 {
12271         struct option long_opts[] = {
12272         { .val = 'h',   .name = "help", .has_arg = no_argument },
12273         { .val = 'i',   .name = "id",   .has_arg = required_argument },
12274         { .name = NULL } };
12275         int c;
12276         int rc = 0;
12277         __u32 archive_id = 0;
12278         const char *path;
12279         char *end;
12280         char fullpath[PATH_MAX];
12281         enum lu_pcc_type type = LU_PCC_READWRITE;
12282
12283         optind = 0;
12284         while ((c = getopt_long(argc, argv, "hi:",
12285                                 long_opts, NULL)) != -1) {
12286                 switch (c) {
12287                 case 'i':
12288                         errno = 0;
12289                         archive_id = strtoul(optarg, &end, 0);
12290                         if (errno != 0 || *end != '\0' ||
12291                             archive_id == 0 || archive_id > UINT32_MAX) {
12292                                 fprintf(stderr,
12293                                         "error: %s: bad archive ID '%s'\n",
12294                                         progname, optarg);
12295                                 return CMD_HELP;
12296                         }
12297                         break;
12298                 default:
12299                         fprintf(stderr, "%s: unrecognized option '%s'\n",
12300                                 progname, argv[optind - 1]);
12301                         /* fallthrough */
12302                 case 'h':
12303                         return CMD_HELP;
12304                 }
12305         }
12306
12307         if (archive_id == 0) {
12308                 fprintf(stderr, "%s: must specify attach ID\n", argv[0]);
12309                 return CMD_HELP;
12310         }
12311
12312         if (argc <= optind) {
12313                 fprintf(stderr, "%s: must specify one or more file names\n",
12314                         argv[0]);
12315                 return CMD_HELP;
12316         }
12317
12318         while (optind < argc) {
12319                 int rc2;
12320
12321                 path = argv[optind++];
12322                 if (!realpath(path, fullpath)) {
12323                         fprintf(stderr, "%s: could not find path '%s': %s\n",
12324                                 argv[0], path, strerror(errno));
12325                         if (rc == 0)
12326                                 rc = -EINVAL;
12327                         continue;
12328                 }
12329
12330                 rc2 = llapi_pcc_attach(fullpath, archive_id, type);
12331                 if (rc2 < 0) {
12332                         fprintf(stderr,
12333                                 "%s: cannot attach '%s' to PCC with archive ID '%u': %s\n",
12334                                 argv[0], path, archive_id, strerror(-rc2));
12335                         if (rc == 0)
12336                                 rc = rc2;
12337                 }
12338         }
12339         return rc;
12340 }
12341
12342 static int lfs_pcc_attach_fid(int argc, char **argv)
12343 {
12344         struct option long_opts[] = {
12345         { .val = 'h',   .name = "help", .has_arg = no_argument },
12346         { .val = 'i',   .name = "id",   .has_arg = required_argument },
12347         { .val = 'm',   .name = "mnt",  .has_arg = required_argument },
12348         { .name = NULL } };
12349         int c;
12350         int rc = 0;
12351         __u32 archive_id = 0;
12352         char *end;
12353         const char *mntpath = NULL;
12354         const char *fidstr;
12355         enum lu_pcc_type type = LU_PCC_READWRITE;
12356
12357         optind = 0;
12358         while ((c = getopt_long(argc, argv, "hi:m:",
12359                                 long_opts, NULL)) != -1) {
12360                 switch (c) {
12361                 case 'i':
12362                         errno = 0;
12363                         archive_id = strtoul(optarg, &end, 0);
12364                         if (errno != 0 || *end != '\0' ||
12365                             archive_id > UINT32_MAX) {
12366                                 fprintf(stderr,
12367                                         "error: %s: bad archive ID '%s'\n",
12368                                         argv[0], optarg);
12369                                 return CMD_HELP;
12370                         }
12371                         break;
12372                 case 'm':
12373                         mntpath = optarg;
12374                         break;
12375                 default:
12376                         fprintf(stderr, "%s: unrecognized option '%s'\n",
12377                                 progname, argv[optind - 1]);
12378                         /* fallthrough */
12379                 case 'h':
12380                         return CMD_HELP;
12381                 }
12382         }
12383
12384         if (archive_id == 0) {
12385                 fprintf(stderr, "%s: must specify an archive ID\n", argv[0]);
12386                 return CMD_HELP;
12387         }
12388
12389         if (!mntpath) {
12390                 fprintf(stderr, "%s: must specify Lustre mount point\n",
12391                         argv[0]);
12392                 return CMD_HELP;
12393         }
12394
12395         if (argc <= optind) {
12396                 fprintf(stderr, "%s: must specify one or more fids\n", argv[0]);
12397                 return CMD_HELP;
12398         }
12399
12400         while (optind < argc) {
12401                 int rc2;
12402
12403                 fidstr = argv[optind++];
12404
12405                 rc2 = llapi_pcc_attach_fid_str(mntpath, fidstr,
12406                                                archive_id, type);
12407                 if (rc2 < 0) {
12408                         fprintf(stderr,
12409                                 "%s: cannot attach '%s' on '%s' to PCC with archive ID '%u': %s\n",
12410                                 argv[0], fidstr, mntpath, archive_id,
12411                                 strerror(rc2));
12412                 }
12413                 if (rc == 0 && rc2 < 0)
12414                         rc = rc2;
12415         }
12416         return rc;
12417 }
12418
12419 static int lfs_pcc_detach(int argc, char **argv)
12420 {
12421         struct option long_opts[] = {
12422         { .val = 'h',   .name = "help", .has_arg = no_argument },
12423         { .val = 'k',   .name = "keep", .has_arg = no_argument },
12424         { .name = NULL } };
12425         int c;
12426         int rc = 0;
12427         const char *path;
12428         char fullpath[PATH_MAX];
12429         __u32 detach_opt = PCC_DETACH_OPT_UNCACHE;
12430
12431         optind = 0;
12432         while ((c = getopt_long(argc, argv, "hk",
12433                                 long_opts, NULL)) != -1) {
12434                 switch (c) {
12435                 case 'k':
12436                         detach_opt = PCC_DETACH_OPT_NONE;
12437                         break;
12438                 default:
12439                         fprintf(stderr, "%s: unrecognized option '%s'\n",
12440                                 progname, argv[optind - 1]);
12441                         /* fallthrough */
12442                 case 'h':
12443                         return CMD_HELP;
12444                 }
12445         }
12446
12447         while (optind < argc) {
12448                 int rc2;
12449
12450                 path = argv[optind++];
12451                 if (!realpath(path, fullpath)) {
12452                         fprintf(stderr, "%s: could not find path '%s': %s\n",
12453                                 argv[0], path, strerror(errno));
12454                         if (rc == 0)
12455                                 rc = -EINVAL;
12456                         continue;
12457                 }
12458
12459                 rc2 = llapi_pcc_detach_file(fullpath, detach_opt);
12460                 if (rc2 < 0) {
12461                         rc2 = -errno;
12462                         fprintf(stderr,
12463                                 "%s: cannot detach '%s' from PCC: %s\n",
12464                                 argv[0], path, strerror(errno));
12465                         if (rc == 0)
12466                                 rc = rc2;
12467                 }
12468         }
12469         return rc;
12470 }
12471
12472 static int lfs_pcc_detach_fid(int argc, char **argv)
12473 {
12474         struct option long_opts[] = {
12475         { .val = 'h',   .name = "help", .has_arg = no_argument },
12476         { .val = 'k',   .name = "keep", .has_arg = no_argument },
12477         { .name = NULL } };
12478         int c;
12479         int rc = 0;
12480         const char *fid;
12481         const char *mntpath;
12482         __u32 detach_opt = PCC_DETACH_OPT_UNCACHE;
12483
12484         optind = 0;
12485         while ((c = getopt_long(argc, argv, "hk",
12486                                 long_opts, NULL)) != -1) {
12487                 switch (c) {
12488                 case 'k':
12489                         detach_opt = PCC_DETACH_OPT_NONE;
12490                         break;
12491                 default:
12492                         fprintf(stderr, "%s: unrecognized option '%s'\n",
12493                                 progname, argv[optind - 1]);
12494                         /* fallthrough */
12495                 case 'h':
12496                         return CMD_HELP;
12497                 }
12498         }
12499
12500         mntpath = argv[optind++];
12501
12502         while (optind < argc) {
12503                 int rc2;
12504
12505                 fid = argv[optind++];
12506
12507                 rc2 = llapi_pcc_detach_fid_str(mntpath, fid, detach_opt);
12508                 if (rc2 < 0) {
12509                         fprintf(stderr,
12510                                 "%s: cannot detach '%s' on '%s' from PCC: %s\n",
12511                                 argv[0], fid, mntpath, strerror(-rc2));
12512                         if (rc == 0)
12513                                 rc = rc2;
12514                 }
12515         }
12516         return rc;
12517 }
12518
12519 static int lfs_pcc_state(int argc, char **argv)
12520 {
12521         int rc = 0;
12522         const char *path;
12523         char fullpath[PATH_MAX];
12524         struct lu_pcc_state state;
12525
12526         optind = 1;
12527
12528         if (argc <= 1) {
12529                 fprintf(stderr, "%s: must specify one or more file names\n",
12530                         progname);
12531                 return CMD_HELP;
12532         }
12533
12534         while (optind < argc) {
12535                 int rc2;
12536
12537                 path = argv[optind++];
12538                 if (!realpath(path, fullpath)) {
12539                         fprintf(stderr, "%s: could not find path '%s': %s\n",
12540                                 argv[0], path, strerror(errno));
12541                         if (rc == 0)
12542                                 rc = -EINVAL;
12543                         continue;
12544                 }
12545
12546                 rc2 = llapi_pcc_state_get(fullpath, &state);
12547                 if (rc2 < 0) {
12548                         if (rc == 0)
12549                                 rc = rc2;
12550                         fprintf(stderr,
12551                                 "%s: cannot get PCC state of '%s': %s\n",
12552                                 argv[0], path, strerror(-rc2));
12553                         continue;
12554                 }
12555
12556                 printf("file: %s", path);
12557                 printf(", type: %s", pcc_type2string(state.pccs_type));
12558                 if (state.pccs_type == LU_PCC_NONE &&
12559                     state.pccs_open_count == 0) {
12560                         printf("\n");
12561                         continue;
12562                 }
12563
12564                 printf(", PCC file: %s", state.pccs_path);
12565                 printf(", user number: %u", state.pccs_open_count);
12566                 printf(", flags: %x", state.pccs_flags);
12567                 printf("\n");
12568         }
12569         return rc;
12570 }
12571
12572 /**
12573  * lfs_pcc_list_commands() - List lfs pcc commands.
12574  * @argc: The count of command line arguments.
12575  * @argv: Array of strings for command line arguments.
12576  *
12577  * This function lists lfs pcc commands defined in pcc_cmdlist[].
12578  *
12579  * Return: 0 on success.
12580  */
12581 static int lfs_pcc_list_commands(int argc, char **argv)
12582 {
12583         char buffer[81] = "";
12584
12585         Parser_list_commands(pcc_cmdlist, buffer, sizeof(buffer),
12586                              NULL, 0, 4);
12587
12588         return 0;
12589 }
12590
12591 /**
12592  * lfs_pcc() - Parse and execute lfs pcc commands.
12593  * @argc: The count of lfs pcc command line arguments.
12594  * @argv: Array of strings for lfs pcc command line arguments.
12595  *
12596  * This function parses lfs pcc commands and performs the
12597  * corresponding functions specified in pcc_cmdlist[].
12598  *
12599  * Return: 0 on success or an error code on failure.
12600  */
12601 static int lfs_pcc(int argc, char **argv)
12602 {
12603         char cmd[PATH_MAX];
12604         int rc = 0;
12605
12606         setlinebuf(stdout);
12607
12608         Parser_init("lfs-pcc > ", pcc_cmdlist);
12609
12610         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
12611         progname = cmd;
12612         program_invocation_short_name = cmd;
12613         if (argc > 1)
12614                 rc = Parser_execarg(argc - 1, argv + 1, pcc_cmdlist);
12615         else
12616                 rc = Parser_commands();
12617
12618         return rc < 0 ? -rc : rc;
12619 }
12620
12621 static int lfs_list_commands(int argc, char **argv)
12622 {
12623         char buffer[81] = ""; /* 80 printable chars + terminating NUL */
12624
12625         Parser_list_commands(cmdlist, buffer, sizeof(buffer), NULL, 0, 4);
12626
12627         return 0;
12628 }
12629
12630 int main(int argc, char **argv)
12631 {
12632         int rc;
12633
12634         /* Ensure that liblustreapi constructor has run */
12635         if (!llapi_liblustreapi_initialized())
12636                 fprintf(stderr, "liblustreapi was not properly initialized\n");
12637
12638         setlinebuf(stdout);
12639         opterr = 0;
12640
12641         Parser_init("lfs > ", cmdlist);
12642
12643         progname = program_invocation_short_name; /* Used in error messages */
12644         if (argc > 1) {
12645                 llapi_set_command_name(argv[1]);
12646                 rc = Parser_execarg(argc - 1, argv + 1, cmdlist);
12647                 llapi_clear_command_name();
12648         } else {
12649                 rc = Parser_commands();
12650         }
12651
12652         return rc < 0 ? -rc : rc;
12653 }
12654
12655 #ifdef _LUSTRE_IDL_H_
12656 /* Everything we need here should be included by lustreapi.h. */
12657 # error "lfs should not depend on lustre_idl.h"
12658 #endif /* _LUSTRE_IDL_H_ */