Whamcloud - gitweb
c4ee1f1b422d7d4e462da5e3933b17419316992d
[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]] [[!] --ctime|-C [+-]N[smhdwy]]\n"
403          "     [[!] --mtime|-M [+-]N[smhdwy]]\n"
404          "     [[!] --btime|--Btime|-B [+-]N[smhdwy]] [--help|-h]\n"
405          "     [[!] --newer[XY] <reference>] [[!] --blocks|-b N]\n"
406          "     [--maxdepth|-D N] [[!] --mdt-index|--mdt|-m <uuid|index,...>]\n"
407          "     [[!] --name|-n <pattern>] [[!] --ost|-O <uuid|index,...>]\n"
408          "     [[!] --perm [/-]mode] [[!] --pool <pool>] [--print|-P]\n"
409          "     [--print0|-0] [[!] --projid <projid>]\n"
410          "     [[!] --size|-s [+-]N[bkMGTPE]]\n"
411          "     [[!] --stripe-count|-c [+-]<stripes>]\n"
412          "     [[!] --stripe-index|-i <index,...>]\n"
413          "     [[!] --stripe-size|-S [+-]N[kMGT]] [[!] --type|-t <filetype>]\n"
414          "     [[!] --extension-size|--ext-size|-z [+-]N[kMGT]]\n"
415          "     [[!] --gid|-g|--group|-G <gid>|<gname>]\n"
416          "     [[!] --uid|-u|--user|-U <uid>|<uname>]\n"
417          "     [[!] --layout|-L released,raid0,mdt]\n"
418          "     [[!] --foreign[=<foreign_type>]]\n"
419          "     [[!] --component-count [+-]<comp_cnt>]\n"
420          "     [[!] --component-start [+-]N[kMGTPE]]\n"
421          "     [[!] --component-end|-E [+-]N[kMGTPE]]\n"
422          "     [[!] --component-flags {init,stale,prefer,offline,nosync,extension}]\n"
423          "     [[!] --mirror-count|-N [+-]<n>]\n"
424          "     [[!] --mirror-state <[^]state>]\n"
425          "     [[!] --mdt-count|-T [+-]<stripes>]\n"
426          "     [[!] --mdt-hash|-H <[^][blm],[^]fnv_1a_64,all_char,crush,...>\n"
427          "     [[!] --mdt-index|-m <uuid|index,...>]\n"
428          "\t !: used before an option indicates 'NOT' requested attribute\n"
429          "\t -: used before a value indicates less than requested value\n"
430          "\t +: used before a value indicates more than requested value\n"
431          "\t ^: used before a flag indicates to exclude it\n"},
432         {"check", lfs_check, 0,
433          "Display the status of MGTs, MDTs or OSTs (as specified in the command)\n"
434          "or all the servers (MGTs, MDTs and OSTs).\n"
435          "usage: check {mgts|osts|mdts|all}"},
436         {"osts", lfs_osts, 0, "list OSTs connected to client "
437          "[for specified path only]\n" "usage: osts [path]"},
438         {"mdts", lfs_mdts, 0, "list MDTs connected to client "
439          "[for specified path only]\n" "usage: mdts [path]"},
440         {"df", lfs_df, 0,
441          "report filesystem disk space usage or inodes usage "
442          "of each MDS and all OSDs or a batch belonging to a specific pool.\n"
443          "Usage: df [--inodes|-i] [--human-readable|-h] [--lazy|-l]\n"
444          "          [--pool|-p <fsname>[.<pool>]] [path]"},
445         {"getname", lfs_getname, 0,
446          "list instances and specified mount points [for specified path only]\n"
447          "Usage: getname [--help|-h] [--instance|-i] [--fsname|-n] [path ...]"},
448 #ifdef HAVE_SYS_QUOTA_H
449         {"setquota", lfs_setquota, 0, "Set filesystem quotas.\n"
450          "usage: setquota [-t][-d] {-u|-U|-g|-G|-p|-P} {-b|-B|-i|-I LIMIT} [--pool POOL] FILESYSTEM"},
451         {"quota", lfs_quota, 0, "Display disk usage and limits.\n"
452          "usage: quota [-q] [-v] [-h] [-o OBD_UUID|-i MDT_IDX|-I OST_IDX]\n"
453          "             [{-u|-g|-p} UNAME|UID|GNAME|GID|PROJID]\n"
454          "             [--pool <OST pool name>] <filesystem>\n"
455          "       quota -t <-u|-g|-p> [--pool <OST pool name>] <filesystem>\n"
456          "       quota [-q] [-v] [h] {-U|-G|-P} [--pool <OST pool name>] <filesystem>"},
457         {"project", lfs_project, 0,
458          "Change or list project attribute for specified file or directory.\n"
459          "usage: project [-d|-r] <file|directory...>\n"
460          "         list project ID and flags on file(s) or directories\n"
461          "       project [-p id] [-s] [-r] <file|directory...>\n"
462          "         set project ID and/or inherit flag for specified file(s) or directories\n"
463          "       project -c [-d|-r [-p id] [-0]] <file|directory...>\n"
464          "         check project ID and flags on file(s) or directories, print outliers\n"
465          "       project -C [-r] [-k] <file|directory...>\n"
466          "         clear the project inherit flag and ID on the file or directory\n"
467         },
468 #endif
469         {"flushctx", lfs_flushctx, 0,
470          "Flush security context for current user.\n"
471          "usage: flushctx [-k] [-r] [mountpoint...]"},
472         {"changelog", lfs_changelog, 0,
473          "Show the metadata changes on an MDT."
474          "\nusage: changelog <mdtname> [startrec [endrec]]"},
475         {"changelog_clear", lfs_changelog_clear, 0,
476          "Indicate that old changelog records up to <endrec> are no longer of "
477          "interest to consumer <id>, allowing the system to free up space.\n"
478          "An <endrec> of 0 means all records.\n"
479          "usage: changelog_clear <mdtname> <id> <endrec>"},
480         {"fid2path", lfs_fid2path, 0,
481          "Resolve the full path(s) for given FID(s). For a specific hardlink "
482          "specify link number <linkno>.\n"
483          "usage: fid2path [--print-fid|-f] [--print-link|-c] [--link|-l <linkno>] "
484          "<fsname|root> <fid>..."},
485         {"path2fid", lfs_path2fid, 0, "Display the fid(s) for a given path(s).\n"
486          "usage: path2fid [--parents] <path> ..."},
487         {"rmfid", lfs_rmfid, 0, "Remove file(s) by FID(s)\n"
488          "usage: rmfid <fsname|rootpath> <fid> ..."},
489         {"data_version", lfs_data_version, 0, "Display file data version for "
490          "a given path.\n" "usage: data_version [-n|-r|-w] <path>"},
491         {"hsm_state", lfs_hsm_state, 0, "Display the HSM information (states, "
492          "undergoing actions) for given files.\n usage: hsm_state <file> ..."},
493         {"hsm_set", lfs_hsm_set, 0, "Set HSM user flag on specified files.\n"
494          "usage: hsm_set [--norelease] [--noarchive] [--dirty] [--exists] "
495          "[--archived] [--lost] [--archive-id NUM] <file> ..."},
496         {"hsm_clear", lfs_hsm_clear, 0, "Clear HSM user flag on specified "
497          "files.\n"
498          "usage: hsm_clear [--norelease] [--noarchive] [--dirty] [--exists] "
499          "[--archived] [--lost] <file> ..."},
500         {"hsm_action", lfs_hsm_action, 0, "Display current HSM request for "
501          "given files.\n" "usage: hsm_action <file> ..."},
502         {"hsm_archive", lfs_hsm_archive, 0,
503          "Archive file to external storage.\n"
504          "usage: hsm_archive [--filelist FILELIST] [--data DATA] [--archive NUM] "
505          "<file> ..."},
506         {"hsm_restore", lfs_hsm_restore, 0,
507          "Restore file from external storage.\n"
508          "usage: hsm_restore [--filelist FILELIST] [--data DATA] <file> ..."},
509         {"hsm_release", lfs_hsm_release, 0,
510          "Release files from Lustre.\n"
511          "usage: hsm_release [--filelist FILELIST] [--data DATA] <file> ..."},
512         {"hsm_remove", lfs_hsm_remove, 0,
513          "Remove file copy from external storage.\n"
514          "usage: hsm_remove [--filelist FILELIST] [--data DATA] "
515          "[--archive NUM]\n"
516          "                  (FILE [FILE ...] | "
517          "--mntpath MOUNTPATH FID [FID ...])\n"
518          "\n"
519          "Note: To remove an archived copy of a file already deleted from a "
520          "Lustre FS, the\n"
521          "--mntpath option and a list of FIDs must be specified"
522         },
523         {"hsm_cancel", lfs_hsm_cancel, 0,
524          "Cancel requests related to specified files.\n"
525          "usage: hsm_cancel [--filelist FILELIST] [--data DATA] <file> ..."},
526         {"swap_layouts", lfs_swap_layouts, 0, "Swap layouts between 2 files.\n"
527          "usage: swap_layouts <path1> <path2>"},
528         {"migrate", lfs_setstripe_migrate, 0,
529          "migrate directories and their inodes between MDTs.\n"
530          "usage: migrate [--mdt-count|-c STRIPE_COUNT] [--directory|-d]\n"
531          "               [--mdt-hash|-H HASH_TYPE]\n"
532          "               [--mdt-index|-m START_MDT_INDEX] [--verbose|-v]\n"
533          "               DIRECTORY\n"
534          "\n"
535          "migrate file objects from one OST layout to another\n"
536          "(may be not safe with concurent writes).\n"
537          MIGRATE_USAGE },
538         {"mv", lfs_mv, 0,
539          "To move directories between MDTs. This command is deprecated, "
540          "use \"migrate\" instead.\n"
541          "usage: mv <directory|filename> [--mdt-index|-m MDT_INDEX] "
542          "[--verbose|-v]\n"},
543         {"ladvise", lfs_ladvise, 0,
544          "Provide servers with advice about access patterns for a file.\n"
545          "usage: ladvise [--advice|-a ADVICE] [--start|-s START[kMGT]]\n"
546          "               [--background|-b] [--unset|-u]\n\n"
547          "               {--end|-e END[kMGT]|--length|-l LENGTH[kMGT]}\n"
548          "               {[--mode|-m [READ,WRITE]}\n"
549          "               <file> ...\n"},
550         {"mirror", lfs_mirror, mirror_cmdlist,
551          "lfs commands used to manage files with mirrored components:\n"
552          "lfs mirror create - create a mirrored file or directory\n"
553          "lfs mirror extend - add mirror(s) to an existing file\n"
554          "lfs mirror split  - split a mirror from an existing mirrored file\n"
555          "lfs mirror resync - resynchronize out-of-sync mirrored file(s)\n"
556          "lfs mirror read   - read a mirror content of a mirrored file\n"
557          "lfs mirror write  - write to a mirror of a mirrored file\n"
558          "lfs mirror copy   - copy a mirror to other mirror(s) of a file\n"
559          "lfs mirror verify - verify mirrored file(s)\n"},
560         {"getsom", lfs_getsom, 0, "To list the SOM info for a given file.\n"
561          "usage: getsom [-s] [-b] [-f] <path>\n"
562          "\t-s: Only show the size value of the SOM data for a given file\n"
563          "\t-b: Only show the blocks value of the SOM data for a given file\n"
564          "\t-f: Only show the flags value of the SOM data for a given file\n"},
565         {"heat_get", lfs_heat_get, 0,
566          "To get heat of files.\n"
567          "usage: heat_get <file> ...\n"},
568         {"heat_set", lfs_heat_set, 0,
569          "To set heat flags of files.\n"
570          "usage: heat_set [--clear|-c] [--off|-o] [--on|-O] <file> ...\n"
571          "\t--clear|-c: Clear file heat for given files\n"
572          "\t--off|-o:   Turn off file heat for given files\n"
573          "\t--on|-O:    Turn on file heat for given files\n"},
574         {"pcc", lfs_pcc, pcc_cmdlist,
575          "lfs commands used to interact with PCC features:\n"
576          "lfs pcc attach - attach given files to Persistent Client Cache\n"
577          "lfs pcc attach_fid - attach given files into PCC by FID(s)\n"
578          "lfs pcc state  - display the PCC state for given files\n"
579          "lfs pcc detach - detach given files from Persistent Client Cache\n"
580          "lfs pcc detach_fid - detach given files from PCC by FID(s)\n"},
581         {"help", Parser_help, 0, "help"},
582         {"exit", Parser_quit, 0, "quit"},
583         {"quit", Parser_quit, 0, "quit"},
584         {"--version", Parser_version, 0,
585          "output build version of the utility and exit"},
586         {"--list-commands", lfs_list_commands, 0,
587          "list commands supported by the utility and exit"},
588         { 0, 0, 0, NULL }
589 };
590
591 static int check_hashtype(const char *hashtype)
592 {
593         int type_num = atoi(hashtype);
594         int i;
595
596         /* numeric hash type */
597         if (hashtype && strlen(hashtype) == 1 &&
598             (type_num > 0 && type_num < LMV_HASH_TYPE_MAX))
599                 return type_num;
600         /* string hash type */
601         for (i = LMV_HASH_TYPE_ALL_CHARS; i < LMV_HASH_TYPE_MAX; i++)
602                 if (strcmp(hashtype, mdt_hash_name[i]) == 0)
603                         return i;
604
605         return 0;
606 }
607
608 static uint32_t check_foreign_type_name(const char *foreign_type_name)
609 {
610         uint32_t i;
611
612         for (i = 0; i < LU_FOREIGN_TYPE_UNKNOWN; i++) {
613                 if (!lu_foreign_types[i].lft_name)
614                         break;
615                 if (strcmp(foreign_type_name,
616                            lu_foreign_types[i].lft_name) == 0)
617                         return lu_foreign_types[i].lft_type;
618         }
619
620         return LU_FOREIGN_TYPE_UNKNOWN;
621 }
622
623 static const char *error_loc = "syserror";
624
625 static int
626 migrate_open_files(const char *name, __u64 migration_flags,
627                    const struct llapi_stripe_param *param,
628                    struct llapi_layout *layout, int *fd_src, int *fd_tgt)
629 {
630         int                      fd = -1;
631         int                      fdv = -1;
632         int                      rflags;
633         int                      mdt_index;
634         int                      random_value;
635         char                     parent[PATH_MAX];
636         char                     volatile_file[PATH_MAX];
637         char                    *ptr;
638         int                      rc;
639         struct stat              st;
640         struct stat              stv;
641
642         if (!param && !layout) {
643                 error_loc = "layout information";
644                 return -EINVAL;
645         }
646
647         /* search for file directory pathname */
648         if (strlen(name) > sizeof(parent) - 1) {
649                 error_loc = "source file name";
650                 return -ERANGE;
651         }
652
653         strncpy(parent, name, sizeof(parent));
654         ptr = strrchr(parent, '/');
655         if (!ptr) {
656                 if (!getcwd(parent, sizeof(parent))) {
657                         error_loc = "getcwd";
658                         return -errno;
659                 }
660         } else {
661                 if (ptr == parent) /* leading '/' */
662                         ptr = parent + 1;
663                 *ptr = '\0';
664         }
665
666         /* even if the file is only read, WR mode is nedeed to allow
667          * layout swap on fd
668          */
669         /* Allow migrating even without the key on encrypted files */
670         rflags = O_RDWR | O_NOATIME | O_FILE_ENC;
671         if (!(migration_flags & LLAPI_MIGRATION_NONDIRECT))
672                 rflags |= O_DIRECT;
673 source_open:
674         fd = open(name, rflags);
675         if (fd < 0) {
676                 /* If encrypted file without the key,
677                  * retry mirror extend in O_DIRECT.
678                  */
679                 if (errno == ENOKEY && !(rflags & O_DIRECT) &&
680                     migration_flags & LLAPI_MIGRATION_MIRROR) {
681                         rflags |= O_DIRECT;
682                         goto source_open;
683                 }
684                 rc = -errno;
685                 error_loc = "cannot open source file";
686                 return rc;
687         }
688
689         rc = llapi_file_fget_mdtidx(fd, &mdt_index);
690         if (rc < 0) {
691                 error_loc = "cannot get MDT index";
692                 goto out;
693         }
694
695         do {
696                 int open_flags = O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW |
697                         /* Allow migrating without the key on encrypted files */
698                         O_FILE_ENC;
699                 mode_t open_mode = S_IRUSR | S_IWUSR;
700
701                 if (rflags & O_DIRECT)
702                         open_flags |= O_DIRECT;
703                 random_value = random();
704                 rc = snprintf(volatile_file, sizeof(volatile_file),
705                               "%s/%s:%.4X:%.4X:fd=%.2d", parent,
706                               LUSTRE_VOLATILE_HDR, mdt_index,
707                               random_value, fd);
708                 if (rc >= sizeof(volatile_file)) {
709                         rc = -ENAMETOOLONG;
710                         break;
711                 }
712
713                 /* create, open a volatile file, use caching (ie no directio) */
714                 if (layout) {
715                         /* Returns -1 and sets errno on error: */
716                         fdv = llapi_layout_file_open(volatile_file, open_flags,
717                                                      open_mode, layout);
718                         if (fdv < 0)
719                                 fdv = -errno;
720                 } else {
721                         /* Does the right thing on error: */
722                         fdv = llapi_file_open_param(volatile_file, open_flags,
723                                                     open_mode, param);
724                 }
725         } while (fdv < 0 && (rc = fdv) == -EEXIST);
726
727         if (rc < 0) {
728                 error_loc = "cannot create volatile file";
729                 goto out;
730         }
731
732         /*
733          * In case the MDT does not support creation of volatile files
734          * we should try to unlink it.
735          */
736         (void)unlink(volatile_file);
737
738         /*
739          * Not-owner (root?) special case.
740          * Need to set owner/group of volatile file like original.
741          * This will allow to pass related check during layout_swap.
742          */
743         rc = fstat(fd, &st);
744         if (rc != 0) {
745                 rc = -errno;
746                 error_loc = "cannot stat source file";
747                 goto out;
748         }
749
750         rc = fstat(fdv, &stv);
751         if (rc != 0) {
752                 rc = -errno;
753                 error_loc = "cannot stat volatile";
754                 goto out;
755         }
756
757         if (st.st_uid != stv.st_uid || st.st_gid != stv.st_gid) {
758                 rc = fchown(fdv, st.st_uid, st.st_gid);
759                 if (rc != 0) {
760                         rc = -errno;
761                         error_loc = "cannot change ownwership of volatile";
762                         goto out;
763                 }
764         }
765
766 out:
767         if (rc < 0) {
768                 if (fd > 0)
769                         close(fd);
770                 if (fdv > 0)
771                         close(fdv);
772         } else {
773                 *fd_src = fd;
774                 *fd_tgt = fdv;
775                 error_loc = NULL;
776         }
777         return rc;
778 }
779
780 static int migrate_copy_data(int fd_src, int fd_dst, int (*check_file)(int))
781 {
782         struct llapi_layout *layout;
783         size_t buf_size = 4 * 1024 * 1024;
784         void *buf = NULL;
785         off_t pos = 0;
786         off_t data_end = 0;
787         size_t page_size = sysconf(_SC_PAGESIZE);
788         bool sparse;
789         int rc;
790
791         layout = llapi_layout_get_by_fd(fd_src, 0);
792         if (layout) {
793                 uint64_t stripe_size;
794
795                 rc = llapi_layout_stripe_size_get(layout, &stripe_size);
796                 if (rc == 0)
797                         buf_size = stripe_size;
798
799                 llapi_layout_free(layout);
800         }
801
802         /* Use a page-aligned buffer for direct I/O */
803         rc = posix_memalign(&buf, page_size, buf_size);
804         if (rc != 0)
805                 return -rc;
806
807         sparse = llapi_file_is_sparse(fd_src);
808         if (sparse) {
809                 rc = ftruncate(fd_dst, pos);
810                 if (rc < 0) {
811                         rc = -errno;
812                         return rc;
813                 }
814         }
815
816         while (1) {
817                 off_t data_off;
818                 size_t to_read, to_write;
819                 ssize_t rsize;
820
821                 if (sparse && pos >= data_end) {
822                         size_t data_size;
823
824                         data_off = llapi_data_seek(fd_src, pos, &data_size);
825                         if (data_off < 0) {
826                                 /* Non-fatal, switch to full copy */
827                                 sparse = false;
828                                 continue;
829                         }
830                         /* hole at the end of file, truncate up to it */
831                         if (!data_size) {
832                                 rc = ftruncate(fd_dst, data_off);
833                                 if (rc < 0)
834                                         goto out;
835                         }
836                         pos = data_off & ~(page_size - 1);
837                         data_end = data_off + data_size;
838                         to_read = ((data_end - pos - 1) | (page_size - 1)) + 1;
839                         to_read = MIN(to_read, buf_size);
840                 } else {
841                         to_read = buf_size;
842                 }
843
844                 if (check_file) {
845                         rc = check_file(fd_src);
846                         if (rc < 0)
847                                 goto out;
848                 }
849
850                 rsize = pread(fd_src, buf, to_read, pos);
851                 if (rsize < 0) {
852                         rc = -errno;
853                         goto out;
854                 }
855                 /* EOF */
856                 if (rsize == 0)
857                         break;
858
859                 to_write = rsize;
860                 while (to_write > 0) {
861                         ssize_t written;
862
863                         written = pwrite(fd_dst, buf, to_write, pos);
864                         if (written < 0) {
865                                 rc = -errno;
866                                 goto out;
867                         }
868                         pos += written;
869                         to_write -= written;
870                 }
871                 if (rc || rsize < to_read)
872                         break;
873         }
874
875         rc = fsync(fd_dst);
876         if (rc < 0)
877                 rc = -errno;
878 out:
879         /* Try to avoid page cache pollution after migration. */
880         (void)posix_fadvise(fd_src, 0, 0, POSIX_FADV_DONTNEED);
881         (void)posix_fadvise(fd_dst, 0, 0, POSIX_FADV_DONTNEED);
882
883         free(buf);
884         return rc;
885 }
886
887 static int migrate_set_timestamps(int fd, const struct stat *st)
888 {
889         struct timeval tv[2] = {
890                 {.tv_sec = st->st_atime},
891                 {.tv_sec = st->st_mtime}
892         };
893
894         return futimes(fd, tv);
895 }
896
897 static int migrate_block(int fd, int fdv)
898 {
899         struct stat st;
900         __u64   dv1;
901         int     gid;
902         int     rc;
903         int     rc2;
904
905         rc = fstat(fd, &st);
906         if (rc < 0) {
907                 error_loc = "cannot stat source file";
908                 return -errno;
909         }
910
911         rc = llapi_get_data_version(fd, &dv1, LL_DV_RD_FLUSH);
912         if (rc < 0) {
913                 error_loc = "cannot get dataversion";
914                 return rc;
915         }
916
917         do
918                 gid = random();
919         while (gid == 0);
920
921         /*
922          * The grouplock blocks all concurrent accesses to the file.
923          * It has to be taken after llapi_get_data_version as it would
924          * block it too.
925          */
926         rc = llapi_group_lock(fd, gid);
927         if (rc < 0) {
928                 error_loc = "cannot get group lock";
929                 return rc;
930         }
931
932         rc = migrate_copy_data(fd, fdv, NULL);
933         if (rc < 0) {
934                 error_loc = "data copy failed";
935                 goto out_unlock;
936         }
937
938         /* Make sure we keep original atime/mtime values */
939         rc = migrate_set_timestamps(fdv, &st);
940         if (rc < 0) {
941                 error_loc = "set target file timestamp failed";
942                 goto out_unlock;
943         }
944
945         /*
946          * swap layouts
947          * for a migration we need to check data version on file did
948          * not change.
949          *
950          * Pass in gid=0 since we already own grouplock.
951          */
952         rc = llapi_fswap_layouts_grouplock(fd, fdv, dv1, 0, 0,
953                                            SWAP_LAYOUTS_CHECK_DV1);
954         if (rc == -EAGAIN) {
955                 error_loc = "file changed";
956                 goto out_unlock;
957         } else if (rc < 0) {
958                 error_loc = "cannot swap layout";
959                 goto out_unlock;
960         }
961
962 out_unlock:
963         rc2 = llapi_group_unlock(fd, gid);
964         if (rc2 < 0 && rc == 0) {
965                 error_loc = "unlock group lock";
966                 rc = rc2;
967         }
968
969         return rc;
970 }
971
972 /**
973  * Internal helper for migrate_copy_data(). Check lease and report error if
974  * need be.
975  *
976  * \param[in]  fd           File descriptor on which to check the lease.
977  *
978  * \retval 0       Migration can keep on going.
979  * \retval -errno  Error occurred, abort migration.
980  */
981 static int check_lease(int fd)
982 {
983         int rc;
984
985         rc = llapi_lease_check(fd);
986         if (rc > 0)
987                 return 0; /* llapi_check_lease returns > 0 on success. */
988
989         return -EBUSY;
990 }
991
992 static int migrate_nonblock(int fd, int fdv)
993 {
994         struct stat st;
995         __u64   dv1;
996         __u64   dv2;
997         int     rc;
998
999         rc = fstat(fd, &st);
1000         if (rc < 0) {
1001                 error_loc = "cannot stat source file";
1002                 return -errno;
1003         }
1004
1005         rc = llapi_get_data_version(fd, &dv1, LL_DV_RD_FLUSH);
1006         if (rc < 0) {
1007                 error_loc = "cannot get data version";
1008                 return rc;
1009         }
1010
1011         rc = migrate_copy_data(fd, fdv, check_lease);
1012         if (rc < 0) {
1013                 error_loc = "data copy failed";
1014                 return rc;
1015         }
1016
1017         rc = llapi_get_data_version(fd, &dv2, LL_DV_RD_FLUSH);
1018         if (rc != 0) {
1019                 error_loc = "cannot get data version";
1020                 return rc;
1021         }
1022
1023         if (dv1 != dv2) {
1024                 rc = -EAGAIN;
1025                 error_loc = "source file changed";
1026                 return rc;
1027         }
1028
1029         /* Make sure we keep original atime/mtime values */
1030         rc = migrate_set_timestamps(fdv, &st);
1031         if (rc < 0) {
1032                 error_loc = "set target file timestamp failed";
1033                 return -errno;
1034         }
1035         return 0;
1036 }
1037
1038 static
1039 int lfs_layout_compid_by_pool(char *fname, const char *pool, int *comp_id)
1040 {
1041         struct pool_to_id_cbdata data = { .pool = pool };
1042         struct llapi_layout *layout = NULL;
1043         int rc;
1044
1045         layout = llapi_layout_get_by_path(fname, 0);
1046         if (!layout) {
1047                 fprintf(stderr,
1048                         "error %s: file '%s' couldn't get layout: rc=%d\n",
1049                         progname, fname, errno);
1050                 rc = -errno;
1051                 goto free_layout;
1052         }
1053         rc = llapi_layout_sanity(layout, fname, false, true);
1054         if (rc < 0) {
1055                 llapi_layout_sanity_perror(errno);
1056                 goto free_layout;
1057         }
1058         rc = llapi_layout_comp_iterate(layout, find_comp_id_by_pool, &data);
1059         if (rc < 0)
1060                 goto free_layout;
1061
1062         *comp_id = data.id;
1063         rc = 0;
1064
1065 free_layout:
1066         if (layout)
1067                 llapi_layout_free(layout);
1068         return rc;
1069 }
1070
1071 static int lfs_component_set(char *fname, int comp_id, const char *pool,
1072                              __u32 flags, __u32 neg_flags)
1073 {
1074         __u32 ids[2];
1075         __u32 flags_array[2];
1076         size_t count = 0;
1077         int rc;
1078
1079         if (!comp_id) {
1080                 if (pool == NULL) {
1081                         fprintf(stderr,
1082                                 "error %s: neither component id nor pool is specified\n",
1083                                 progname);
1084                         return -EINVAL;
1085                 }
1086                 rc = lfs_layout_compid_by_pool(fname, pool, &comp_id);
1087                 if (rc)
1088                         return rc;
1089         }
1090
1091         if (flags) {
1092                 ids[count] = comp_id;
1093                 flags_array[count] = flags;
1094                 ++count;
1095         }
1096
1097         if (neg_flags) {
1098                 if (neg_flags & LCME_FL_STALE) {
1099                         fprintf(stderr,
1100                                 "%s: cannot clear 'stale' flags from component. Please use lfs-mirror-resync(1) instead\n",
1101                                 progname);
1102                         return -EINVAL;
1103                 }
1104
1105                 ids[count] = comp_id;
1106                 flags_array[count] = neg_flags | LCME_FL_NEG;
1107                 ++count;
1108         }
1109
1110         rc = llapi_layout_file_comp_set(fname, ids, flags_array, count);
1111         if (rc) {
1112                 if (errno == EUCLEAN) {
1113                         rc = -errno;
1114                         fprintf(stderr,
1115                                 "%s: cannot set 'stale' flag on component '%#x' of the last non-stale mirror of '%s'\n",
1116                                 progname, comp_id, fname);
1117                 } else {
1118                         fprintf(stderr,
1119                                 "%s: cannot change the flags of component '%#x' of file '%s': %x / ^(%x)\n",
1120                                 progname, comp_id, fname, flags, neg_flags);
1121                 }
1122         }
1123
1124         return rc;
1125 }
1126
1127 static int lfs_component_del(char *fname, __u32 comp_id,
1128                              __u32 flags, __u32 neg_flags)
1129 {
1130         int     rc = 0;
1131
1132         if (flags && neg_flags)
1133                 return -EINVAL;
1134
1135         if (!flags && neg_flags)
1136                 flags = neg_flags | LCME_FL_NEG;
1137
1138         if ((flags && comp_id) || (!flags && !comp_id))
1139                 return -EINVAL;
1140
1141         if (flags) {
1142                 if (flags & ~LCME_KNOWN_FLAGS) {
1143                         fprintf(stderr,
1144                                 "%s setstripe: unknown flags %#x\n",
1145                                 progname, flags);
1146                         return -EINVAL;
1147                 }
1148         } else if (comp_id > LCME_ID_MAX) {
1149                 fprintf(stderr, "%s setstripe: invalid component id %u\n",
1150                         progname, comp_id);
1151                 return -EINVAL;
1152         }
1153
1154         rc = llapi_layout_file_comp_del(fname, comp_id, flags);
1155         if (rc)
1156                 fprintf(stderr,
1157                         "%s setstripe: cannot delete component %#x from '%s': %s\n",
1158                         progname, comp_id, fname, strerror(errno));
1159         return rc;
1160 }
1161
1162 static int lfs_component_add(char *fname, struct llapi_layout *layout)
1163 {
1164         int     rc;
1165
1166         if (!layout)
1167                 return -EINVAL;
1168
1169         rc = llapi_layout_file_comp_add(fname, layout);
1170         if (rc)
1171                 fprintf(stderr, "Add layout component(s) to %s failed. %s\n",
1172                         fname, strerror(errno));
1173         return rc;
1174 }
1175
1176 static int lfs_component_create(char *fname, int open_flags, mode_t open_mode,
1177                                 struct llapi_layout *layout)
1178 {
1179         struct stat     st;
1180         int     fd;
1181
1182         if (!layout)
1183                 return -EINVAL;
1184
1185         fd = lstat(fname, &st);
1186         if (fd == 0 && S_ISDIR(st.st_mode))
1187                 open_flags = O_DIRECTORY | O_RDONLY;
1188
1189         fd = llapi_layout_file_open(fname, open_flags, open_mode, layout);
1190         if (fd < 0)
1191                 fprintf(stderr, "%s: cannot %s '%s': %s\n", progname,
1192                         S_ISDIR(st.st_mode) ?
1193                                 "set default composite layout for" :
1194                                 "create composite file",
1195                         fname, strerror(errno));
1196         return fd;
1197 }
1198
1199 static int lfs_migrate(char *name, __u64 migration_flags,
1200                        struct llapi_stripe_param *param,
1201                        struct llapi_layout *layout)
1202 {
1203         struct llapi_layout *existing;
1204         uint64_t dom_new, dom_cur;
1205         int fd = -1;
1206         int fdv = -1;
1207         int rc;
1208
1209         rc = migrate_open_files(name, migration_flags, param, layout,
1210                                 &fd, &fdv);
1211         if (rc < 0)
1212                 goto out;
1213
1214         rc = llapi_layout_dom_size(layout, &dom_new);
1215         if (rc) {
1216                 error_loc = "cannot get new layout DoM size";
1217                 goto out;
1218         }
1219         /* special case for migration to DOM layout*/
1220         existing = llapi_layout_get_by_fd(fd, 0);
1221         if (!existing) {
1222                 error_loc = "cannot get existing layout";
1223                 goto out;
1224         }
1225
1226         rc = llapi_layout_dom_size(existing, &dom_cur);
1227         if (rc) {
1228                 error_loc = "cannot get current layout DoM size";
1229                 goto out;
1230         }
1231
1232         /*
1233          * if file has DoM layout already then migration is possible to
1234          * the new layout with the same DoM component via swap layout,
1235          * if new layout used bigger DOM size, then mirroring is used
1236          */
1237         if (dom_new > dom_cur) {
1238                 rc = lfs_migrate_to_dom(fd, fdv, name, migration_flags);
1239                 if (rc)
1240                         error_loc = "cannot migrate to DOM layout";
1241                 goto out_closed;
1242         }
1243
1244         if (!(migration_flags & LLAPI_MIGRATION_NONBLOCK)) {
1245                 /*
1246                  * Blocking mode (forced if servers do not support file lease).
1247                  * It is also the default mode, since we cannot distinguish
1248                  * between a broken lease and a server that does not support
1249                  * atomic swap/close (LU-6785)
1250                  */
1251                 rc = migrate_block(fd, fdv);
1252                 goto out;
1253         }
1254
1255         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
1256         if (rc < 0) {
1257                 error_loc = "cannot get lease";
1258                 goto out;
1259         }
1260
1261         rc = migrate_nonblock(fd, fdv);
1262         if (rc < 0) {
1263                 llapi_lease_release(fd);
1264                 goto out;
1265         }
1266
1267         /*
1268          * Atomically put lease, swap layouts and close.
1269          * for a migration we need to check data version on file did
1270          * not change.
1271          */
1272         rc = llapi_fswap_layouts(fd, fdv, 0, 0, SWAP_LAYOUTS_CLOSE);
1273         if (rc < 0) {
1274                 error_loc = "cannot swap layout";
1275                 goto out;
1276         }
1277
1278 out:
1279         if (fd >= 0)
1280                 close(fd);
1281
1282         if (fdv >= 0)
1283                 close(fdv);
1284 out_closed:
1285         if (rc < 0)
1286                 fprintf(stderr, "error: %s: %s: %s: %s\n",
1287                         progname, name, error_loc, strerror(-rc));
1288         else if (migration_flags & LLAPI_MIGRATION_VERBOSE)
1289                 printf("%s\n", name);
1290
1291         return rc;
1292 }
1293
1294 static int comp_str2flags(char *string, __u32 *flags, __u32 *neg_flags)
1295 {
1296         char *name;
1297         char *dup_string = NULL;
1298         int rc = 0;
1299
1300         *flags = 0;
1301         *neg_flags = 0;
1302
1303         if (!string || !string[0])
1304                 return -EINVAL;
1305
1306         dup_string = strdup(string);
1307         if (!dup_string) {
1308                 llapi_printf(LLAPI_MSG_ERROR,
1309                              "%s: insufficient memory\n",
1310                              progname);
1311                 return -ENOMEM;
1312         }
1313
1314         for (name = strtok(dup_string, ","); name; name = strtok(NULL, ",")) {
1315                 bool found = false;
1316                 int i;
1317
1318                 for (i = 0; i < ARRAY_SIZE(comp_flags_table); i++) {
1319                         __u32 comp_flag = comp_flags_table[i].cfn_flag;
1320                         const char *comp_name = comp_flags_table[i].cfn_name;
1321
1322                         if (strcmp(name, comp_name) == 0) {
1323                                 *flags |= comp_flag;
1324                                 found = true;
1325                         } else if (strncmp(name, "^", 1) == 0 &&
1326                                    strcmp(name + 1, comp_name) == 0) {
1327                                 *neg_flags |= comp_flag;
1328                                 found = true;
1329                         }
1330                 }
1331                 if (!found) {
1332                         llapi_printf(LLAPI_MSG_ERROR,
1333                                      "%s: component flag '%s' not supported\n",
1334                                      progname, name);
1335                         rc = -EINVAL;
1336                         goto out_free;
1337                 }
1338         }
1339
1340         if (!*flags && !*neg_flags)
1341                 rc = -EINVAL;
1342
1343         /* don't allow to set and exclude the same flag */
1344         if (*flags & *neg_flags)
1345                 rc = -EINVAL;
1346
1347 out_free:
1348         free(dup_string);
1349         return rc;
1350 }
1351
1352 static int mdthash_input(char *string, __u32 *inflags,
1353                          __u32 *exflags, __u32 *type)
1354 {
1355         char *name;
1356         struct mhf_list {
1357                 char *name;
1358                 __u32 flag;
1359         } mhflist[] = {
1360                 {"migrating", LMV_HASH_FLAG_MIGRATION},
1361                 {"badtype", LMV_HASH_FLAG_BAD_TYPE},
1362                 {"lostlmv", LMV_HASH_FLAG_LOST_LMV},
1363         };
1364
1365         if (string == NULL)
1366                 return -EINVAL;
1367
1368         *inflags = 0;
1369         *exflags = 0;
1370         *type = 0;
1371         for (name = strtok(string, ","); name; name = strtok(NULL, ",")) {
1372                 bool found = false;
1373                 int i;
1374
1375                 for (i = 0; i < ARRAY_SIZE(mhflist); i++) {
1376                         if (strcmp(name, mhflist[i].name) == 0 ||
1377                             name[0] == mhflist[i].name[0]) {
1378                                 *inflags |= mhflist[i].flag;
1379                                 found = true;
1380                         } else if (name[0] == '^' &&
1381                                    (strcmp(name + 1, mhflist[i].name) == 0 ||
1382                                     name[1] == mhflist[i].name[0])) {
1383                                 *exflags |= mhflist[i].flag;
1384                                 found = true;
1385                         }
1386                 }
1387                 if (!found) {
1388                         i = check_hashtype(name);
1389                         if (i > 0) {
1390                                 *type |= 1 << i;
1391                                 continue;
1392                         }
1393                         llapi_printf(LLAPI_MSG_ERROR,
1394                                      "%s: invalid mdt_hash value '%s'\n",
1395                                      progname, name);
1396                         return -EINVAL;
1397                 }
1398         }
1399
1400         /* don't allow to include and exclude the same flag */
1401         if (*inflags & *exflags) {
1402                 llapi_printf(LLAPI_MSG_ERROR,
1403                              "%s: include and exclude same flag '%s'\n",
1404                              progname, string);
1405                 return -EINVAL;
1406         }
1407
1408         return 0;
1409 }
1410
1411 static int mirror_str2state(char *string, __u16 *state, __u16 *neg_state)
1412 {
1413         if (!string)
1414                 return -EINVAL;
1415
1416         *state = 0;
1417         *neg_state = 0;
1418
1419         if (strncmp(string, "^", 1) == 0) {
1420                 *neg_state = llapi_layout_string_flags(string + 1);
1421                 if (*neg_state != 0)
1422                         return 0;
1423         } else {
1424                 *state = llapi_layout_string_flags(string);
1425                 if (*state != 0)
1426                         return 0;
1427         }
1428
1429         llapi_printf(LLAPI_MSG_ERROR,
1430                      "%s: mirrored file state '%s' not supported\n",
1431                      progname, string);
1432         return -EINVAL;
1433 }
1434
1435 /**
1436  * struct mirror_args - Command-line arguments for mirror(s).
1437  * @m_count:  Number of mirrors to be created with this layout.
1438  * @m_flags:  Mirror level flags, only 'prefer' is supported.
1439  * @m_layout: Mirror layout.
1440  * @m_file:   A victim file. Its layout will be split and used as a mirror.
1441  * @m_next:   Point to the next node of the list.
1442  *
1443  * Command-line arguments for mirror(s) will be parsed and stored in
1444  * a linked list that consists of this structure.
1445  */
1446 struct mirror_args {
1447         __u32                   m_count;
1448         __u32                   m_flags;
1449         struct llapi_layout     *m_layout;
1450         const char              *m_file;
1451         struct mirror_args      *m_next;
1452         bool                    m_inherit;
1453 };
1454
1455 /**
1456  * enum mirror_flags - Flags for extending a mirrored file.
1457  * @MF_NO_VERIFY: Indicates not to verify the mirror(s) from victim file(s)
1458  *             in case the victim file(s) contains the same data as the
1459  *             original mirrored file.
1460  * @MF_DESTROY: Indicates to delete the mirror from the mirrored file.
1461  * @MF_COMP_ID: specified component id instead of mirror id
1462  *
1463  * Flags for extending a mirrored file.
1464  */
1465 enum mirror_flags {
1466         MF_NO_VERIFY    = 0x1,
1467         MF_DESTROY      = 0x2,
1468         MF_COMP_ID      = 0x4,
1469         MF_COMP_POOL    = 0x8,
1470 };
1471
1472 /**
1473  * mirror_create_sanity_check() - Check mirror list.
1474  * @list:  A linked list that stores the mirror arguments.
1475  *
1476  * This function does a sanity check on @list for creating
1477  * a mirrored file.
1478  *
1479  * Return: 0 on success or a negative error code on failure.
1480  */
1481 static int mirror_create_sanity_check(const char *fname,
1482                                       struct mirror_args *list,
1483                                       bool check_fname)
1484 {
1485         int rc = 0;
1486         bool has_m_file = false;
1487         bool has_m_layout = false;
1488
1489         if (!list)
1490                 return -EINVAL;
1491
1492         if (fname && check_fname) {
1493                 struct llapi_layout *layout;
1494
1495                 layout = llapi_layout_get_by_path(fname, 0);
1496                 if (!layout) {
1497                         fprintf(stderr,
1498                                 "error: %s: file '%s' couldn't get layout\n",
1499                                 progname, fname);
1500                         return -ENODATA;
1501                 }
1502
1503                 rc = llapi_layout_sanity(layout, fname, false, true);
1504
1505                 llapi_layout_free(layout);
1506
1507                 if (rc) {
1508                         llapi_layout_sanity_perror(rc);
1509                         return rc;
1510                 }
1511         }
1512
1513         while (list) {
1514                 if (list->m_file) {
1515                         has_m_file = true;
1516                         llapi_layout_free(list->m_layout);
1517
1518                         list->m_layout =
1519                                 llapi_layout_get_by_path(list->m_file, 0);
1520                         if (!list->m_layout) {
1521                                 fprintf(stderr,
1522                                         "error: %s: file '%s' has no layout\n",
1523                                         progname, list->m_file);
1524                                 return -ENODATA;
1525                         }
1526                 } else {
1527                         has_m_layout = true;
1528                         if (!list->m_layout) {
1529                                 fprintf(stderr, "error: %s: no mirror layout\n",
1530                                         progname);
1531                                 return -EINVAL;
1532                         }
1533                 }
1534
1535                 rc = llapi_layout_sanity(list->m_layout, fname, false, true);
1536                 if (rc) {
1537                         llapi_layout_sanity_perror(rc);
1538                         return rc;
1539                 }
1540
1541                 list = list->m_next;
1542         }
1543
1544         if (has_m_file && has_m_layout) {
1545                 fprintf(stderr,
1546                         "error: %s: -f <victim_file> option should not be specified with setstripe options\n",
1547                         progname);
1548                 return -EINVAL;
1549         }
1550
1551         return 0;
1552 }
1553
1554 static int mirror_set_flags(struct llapi_layout *layout, void *cbdata)
1555 {
1556         __u32 mirror_flags = *(__u32 *)cbdata;
1557         uint32_t flags;
1558         int rc;
1559
1560         rc = llapi_layout_comp_flags_get(layout, &flags);
1561         if (rc < 0)
1562                 return rc;
1563
1564         if (!flags) {
1565                 rc = llapi_layout_comp_flags_set(layout, mirror_flags);
1566                 if (rc)
1567                         return rc;
1568         }
1569
1570         return LLAPI_LAYOUT_ITER_CONT;
1571 }
1572
1573 /**
1574  * mirror_create() - Create a mirrored file.
1575  * @fname:        The file to be created.
1576  * @mirror_list:  A linked list that stores the mirror arguments.
1577  *
1578  * This function creates a mirrored file @fname with the mirror(s)
1579  * from @mirror_list.
1580  *
1581  * Return: 0 on success or a negative error code on failure.
1582  */
1583 static int mirror_create(char *fname, struct mirror_args *mirror_list)
1584 {
1585         struct llapi_layout *layout = NULL;
1586         struct mirror_args *cur_mirror = NULL;
1587         uint16_t mirror_count = 0;
1588         int i = 0;
1589         int rc = 0;
1590
1591         rc = mirror_create_sanity_check(fname, mirror_list, false);
1592         if (rc)
1593                 return rc;
1594
1595         cur_mirror = mirror_list;
1596         while (cur_mirror) {
1597                 rc = llapi_layout_comp_iterate(cur_mirror->m_layout,
1598                                                mirror_set_flags,
1599                                                &cur_mirror->m_flags);
1600                 if (rc) {
1601                         rc = -errno;
1602                         fprintf(stderr, "%s: failed to set mirror flags\n",
1603                                 progname);
1604                         goto error;
1605                 }
1606
1607                 for (i = 0; i < cur_mirror->m_count; i++) {
1608                         rc = llapi_layout_merge(&layout, cur_mirror->m_layout);
1609                         if (rc) {
1610                                 rc = -errno;
1611                                 fprintf(stderr,
1612                                         "error: %s: merge layout failed: %s\n",
1613                                         progname, strerror(errno));
1614                                 goto error;
1615                         }
1616                 }
1617                 mirror_count += cur_mirror->m_count;
1618                 cur_mirror = cur_mirror->m_next;
1619         }
1620
1621         if (!layout) {
1622                 fprintf(stderr, "error: %s: layout is NULL\n", progname);
1623                 return -EINVAL;
1624         }
1625
1626         rc = llapi_layout_mirror_count_set(layout, mirror_count);
1627         if (rc) {
1628                 rc = -errno;
1629                 fprintf(stderr, "error: %s: set mirror count failed: %s\n",
1630                         progname, strerror(errno));
1631                 goto error;
1632         }
1633
1634         rc = lfs_component_create(fname, O_CREAT | O_WRONLY, 0666,
1635                                   layout);
1636         if (rc >= 0) {
1637                 close(rc);
1638                 rc = 0;
1639         }
1640
1641 error:
1642         llapi_layout_free(layout);
1643         return rc;
1644 }
1645
1646 /**
1647  * Compare files and check lease on @fd.
1648  *
1649  * \retval bytes number of bytes are the same
1650  */
1651 static ssize_t mirror_file_compare(int fd, int fdv)
1652 {
1653         const size_t buflen = 4 * 1024 * 1024; /* 4M */
1654         void *buf;
1655         ssize_t bytes_done = 0;
1656         ssize_t bytes_read = 0;
1657
1658         buf = malloc(buflen * 2);
1659         if (!buf)
1660                 return -ENOMEM;
1661
1662         while (1) {
1663                 if (!llapi_lease_check(fd)) {
1664                         bytes_done = -EBUSY;
1665                         break;
1666                 }
1667
1668                 bytes_read = read(fd, buf, buflen);
1669                 if (bytes_read <= 0)
1670                         break;
1671
1672                 if (bytes_read != read(fdv, buf + buflen, buflen))
1673                         break;
1674
1675                 /*
1676                  * XXX: should compute the checksum on each buffer and then
1677                  * compare checksum to avoid cache collision
1678                  */
1679                 if (memcmp(buf, buf + buflen, bytes_read))
1680                         break;
1681
1682                 bytes_done += bytes_read;
1683         }
1684
1685         free(buf);
1686
1687         return bytes_done;
1688 }
1689
1690 static int mirror_extend_file(const char *fname, const char *victim_file,
1691                               enum mirror_flags mirror_flags)
1692 {
1693         int fd = -1;
1694         int fdv = -1;
1695         struct stat stbuf;
1696         struct stat stbuf_v;
1697         struct ll_ioc_lease *data = NULL;
1698         int rc;
1699
1700         fd = open(fname, O_RDWR);
1701         if (fd < 0) {
1702                 error_loc = "open source file";
1703                 rc = -errno;
1704                 goto out;
1705         }
1706
1707         fdv = open(victim_file, O_RDWR);
1708         if (fdv < 0) {
1709                 error_loc = "open target file";
1710                 rc = -errno;
1711                 goto out;
1712         }
1713
1714         if (fstat(fd, &stbuf) || fstat(fdv, &stbuf_v)) {
1715                 error_loc = "stat source or target file";
1716                 rc = -errno;
1717                 goto out;
1718         }
1719
1720         if (stbuf.st_dev != stbuf_v.st_dev) {
1721                 error_loc = "stat source and target file";
1722                 rc = -EXDEV;
1723                 goto out;
1724         }
1725
1726         /* mirrors should be of the same size */
1727         if (stbuf.st_size != stbuf_v.st_size) {
1728                 error_loc = "file sizes don't match";
1729                 rc = -EINVAL;
1730                 goto out;
1731         }
1732
1733         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
1734         if (rc < 0) {
1735                 error_loc = "cannot get lease";
1736                 goto out;
1737         }
1738
1739         if (!(mirror_flags & MF_NO_VERIFY)) {
1740                 ssize_t ret;
1741                 /* mirrors should have the same contents */
1742                 ret = mirror_file_compare(fd, fdv);
1743                 if (ret != stbuf.st_size) {
1744                         error_loc = "file busy or contents don't match";
1745                         rc = ret < 0 ? ret : -EINVAL;
1746                         goto out;
1747                 }
1748         }
1749
1750         /* Get rid of caching pages from clients */
1751         rc = llapi_file_flush(fd);
1752         if (rc < 0) {
1753                 error_loc = "cannot get data version";
1754                 goto out;
1755         }
1756
1757         rc = llapi_file_flush(fdv);
1758         if (rc < 0) {
1759                 error_loc = "cannot get data version";
1760                 goto out;
1761         }
1762
1763         rc = migrate_set_timestamps(fd, &stbuf);
1764         if (rc < 0) {
1765                 error_loc = "cannot set source file timestamp";
1766                 goto out;
1767         }
1768
1769         /* Atomically put lease, merge layouts and close. */
1770         data = calloc(1, offsetof(typeof(*data), lil_ids[1]));
1771         if (!data) {
1772                 error_loc = "memory allocation";
1773                 goto out;
1774         }
1775         data->lil_mode = LL_LEASE_UNLCK;
1776         data->lil_flags = LL_LEASE_LAYOUT_MERGE;
1777         data->lil_count = 1;
1778         data->lil_ids[0] = fdv;
1779         rc = llapi_lease_set(fd, data);
1780         if (rc < 0) {
1781                 error_loc = "cannot merge layout";
1782                 goto out;
1783         } else if (rc == 0) {
1784                 rc = -EBUSY;
1785                 error_loc = "lost lease lock";
1786                 goto out;
1787         }
1788         rc = 0;
1789
1790 out:
1791         if (data)
1792                 free(data);
1793         if (fd >= 0)
1794                 close(fd);
1795         if (fdv >= 0)
1796                 close(fdv);
1797         if (!rc)
1798                 (void) unlink(victim_file);
1799         if (rc < 0)
1800                 fprintf(stderr, "error: %s: %s: %s: %s\n",
1801                         progname, fname, error_loc, strerror(-rc));
1802         return rc;
1803 }
1804
1805 static int mirror_extend_layout(char *name, struct llapi_layout *m_layout,
1806                                 bool inherit, uint32_t flags)
1807 {
1808         struct llapi_layout *f_layout = NULL;
1809         struct ll_ioc_lease *data = NULL;
1810         struct stat st;
1811         int fd = -1;
1812         int fdv = -1;
1813         int rc = 0;
1814
1815         if (inherit) {
1816                 f_layout = llapi_layout_get_by_path(name, 0);
1817                 if (!f_layout) {
1818                         rc = -EINVAL;
1819                         fprintf(stderr, "%s: cannot get layout\n", progname);
1820                         goto out;
1821                 }
1822                 rc = llapi_layout_get_last_init_comp(f_layout);
1823                 if (rc) {
1824                         fprintf(stderr, "%s: cannot get the last init comp\n",
1825                                 progname);
1826                         goto out;
1827                 }
1828                 rc = llapi_layout_mirror_inherit(f_layout, m_layout);
1829                 if (rc) {
1830                         fprintf(stderr,
1831                                 "%s: cannot inherit from the last init comp\n",
1832                                 progname);
1833                         goto out;
1834                 }
1835         }
1836
1837         llapi_layout_comp_flags_set(m_layout, flags);
1838         rc = migrate_open_files(name,
1839                              LLAPI_MIGRATION_NONDIRECT | LLAPI_MIGRATION_MIRROR,
1840                              NULL, m_layout, &fd, &fdv);
1841         if (rc < 0)
1842                 goto out;
1843
1844         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
1845         if (rc < 0) {
1846                 error_loc = "cannot get lease";
1847                 goto out;
1848         }
1849
1850         rc = fstat(fd, &st);
1851         if (rc < 0) {
1852                 error_loc = "cannot stat source file";
1853                 goto out;
1854         }
1855
1856         rc = migrate_nonblock(fd, fdv);
1857         if (rc < 0) {
1858                 llapi_lease_release(fd);
1859                 goto out;
1860         }
1861
1862         rc = migrate_set_timestamps(fd, &st);
1863         if (rc < 0) {
1864                 error_loc = "cannot set source file timestamp";
1865                 goto out;
1866         }
1867
1868         /* Atomically put lease, merge layouts and close. */
1869         data = calloc(1, offsetof(typeof(*data), lil_ids[1]));
1870         if (!data) {
1871                 error_loc = "memory allocation";
1872                 goto out;
1873         }
1874         data->lil_mode = LL_LEASE_UNLCK;
1875         data->lil_flags = LL_LEASE_LAYOUT_MERGE;
1876         data->lil_count = 1;
1877         data->lil_ids[0] = fdv;
1878         rc = llapi_lease_set(fd, data);
1879         if (rc < 0) {
1880                 error_loc = "cannot merge layout";
1881                 goto out;
1882         } else if (rc == 0) {
1883                 rc = -EBUSY;
1884                 error_loc = "lost lease lock";
1885                 goto out;
1886         }
1887         rc = 0;
1888
1889 out:
1890         if (data)
1891                 free(data);
1892         if (fd >= 0)
1893                 close(fd);
1894         if (fdv >= 0)
1895                 close(fdv);
1896         if (rc < 0)
1897                 fprintf(stderr, "error: %s: %s: %s: %s\n",
1898                         progname, name, error_loc, strerror(-rc));
1899         return rc;
1900 }
1901
1902 static int mirror_extend(char *fname, struct mirror_args *mirror_list,
1903                          enum mirror_flags mirror_flags)
1904 {
1905         int rc = 0;
1906
1907         while (mirror_list) {
1908                 if (mirror_list->m_file) {
1909                         rc = mirror_extend_file(fname, mirror_list->m_file,
1910                                                 mirror_flags);
1911                 } else {
1912                         __u32 mirror_count = mirror_list->m_count;
1913
1914                         while (mirror_count > 0) {
1915                                 rc = mirror_extend_layout(fname,
1916                                                         mirror_list->m_layout,
1917                                                         mirror_list->m_inherit,
1918                                                         mirror_list->m_flags);
1919                                 if (rc)
1920                                         break;
1921
1922                                 --mirror_count;
1923                         }
1924                 }
1925                 if (rc)
1926                         break;
1927
1928                 mirror_list = mirror_list->m_next;
1929         }
1930
1931         return rc;
1932 }
1933
1934 static int find_mirror_id(struct llapi_layout *layout, void *cbdata)
1935 {
1936         uint32_t id;
1937         int rc;
1938
1939         rc = llapi_layout_mirror_id_get(layout, &id);
1940         if (rc < 0)
1941                 return rc;
1942
1943         if ((__u16)id == *(__u16 *)cbdata)
1944                 return LLAPI_LAYOUT_ITER_STOP;
1945
1946         return LLAPI_LAYOUT_ITER_CONT;
1947 }
1948
1949 static int find_comp_id(struct llapi_layout *layout, void *cbdata)
1950 {
1951         uint32_t id;
1952         int rc;
1953
1954         rc = llapi_layout_comp_id_get(layout, &id);
1955         if (rc < 0)
1956                 return rc;
1957
1958         if (id == *(__u32 *)cbdata)
1959                 return LLAPI_LAYOUT_ITER_STOP;
1960
1961         return LLAPI_LAYOUT_ITER_CONT;
1962 }
1963
1964 static int find_mirror_id_by_pool(struct llapi_layout *layout, void *cbdata)
1965 {
1966         char buf[LOV_MAXPOOLNAME + 1];
1967         struct pool_to_id_cbdata *d = (void *)cbdata;
1968         uint32_t id;
1969         int rc;
1970
1971         rc = llapi_layout_pool_name_get(layout, buf, sizeof(buf));
1972         if (rc < 0)
1973                 return rc;
1974         if (strcmp(d->pool, buf))
1975                 return LLAPI_LAYOUT_ITER_CONT;
1976
1977         rc = llapi_layout_mirror_id_get(layout, &id);
1978         if (rc < 0)
1979                 return rc;
1980         d->id = id;
1981
1982         return LLAPI_LAYOUT_ITER_STOP;
1983 }
1984
1985 static int find_comp_id_by_pool(struct llapi_layout *layout, void *cbdata)
1986 {
1987         char buf[LOV_MAXPOOLNAME + 1];
1988         struct pool_to_id_cbdata *d = (void *)cbdata;
1989         uint32_t id;
1990         int rc;
1991
1992         rc = llapi_layout_pool_name_get(layout, buf, sizeof(buf));
1993         if (rc < 0)
1994                 return rc;
1995         if (strcmp(d->pool, buf))
1996                 return LLAPI_LAYOUT_ITER_CONT;
1997
1998         rc = llapi_layout_comp_id_get(layout, &id);
1999         if (rc < 0)
2000                 return rc;
2001         d->id = id;
2002
2003         return LLAPI_LAYOUT_ITER_STOP;
2004 }
2005
2006 struct collect_ids_data {
2007         __u16   *cid_ids;
2008         int     cid_count;
2009         __u16   cid_exclude;
2010 };
2011
2012 static int collect_mirror_id(struct llapi_layout *layout, void *cbdata)
2013 {
2014         struct collect_ids_data *cid = cbdata;
2015         uint32_t id;
2016         int rc;
2017
2018         rc = llapi_layout_mirror_id_get(layout, &id);
2019         if (rc < 0)
2020                 return rc;
2021
2022         if ((__u16)id != cid->cid_exclude) {
2023                 int i;
2024
2025                 for (i = 0; i < cid->cid_count; i++) {
2026                         /* already collected the mirror id */
2027                         if (id == cid->cid_ids[i])
2028                                 return LLAPI_LAYOUT_ITER_CONT;
2029                 }
2030                 cid->cid_ids[cid->cid_count] = id;
2031                 cid->cid_count++;
2032         }
2033
2034         return LLAPI_LAYOUT_ITER_CONT;
2035 }
2036
2037 /**
2038  * last_non_stale_mirror() - Check if a mirror is the last non-stale mirror.
2039  * @mirror_id: Mirror id to be checked.
2040  * @layout:    Mirror component list.
2041  *
2042  * This function checks if a mirror with specified @mirror_id is the last
2043  * non-stale mirror of a layout @layout.
2044  *
2045  * Return: true or false.
2046  */
2047 static inline
2048 bool last_non_stale_mirror(__u16 mirror_id, struct llapi_layout *layout)
2049 {
2050         __u16 mirror_ids[128] = { 0 };
2051         struct collect_ids_data cid = { .cid_ids = mirror_ids,
2052                                         .cid_count = 0,
2053                                         .cid_exclude = mirror_id, };
2054         int i;
2055
2056         llapi_layout_comp_iterate(layout, collect_mirror_id, &cid);
2057
2058         for (i = 0; i < cid.cid_count; i++) {
2059                 struct llapi_resync_comp comp_array[1024] = { { 0 } };
2060                 int comp_size = 0;
2061
2062                 comp_size = llapi_mirror_find_stale(layout, comp_array,
2063                                                     ARRAY_SIZE(comp_array),
2064                                                     &mirror_ids[i], 1);
2065                 if (comp_size == 0)
2066                         return false;
2067         }
2068
2069         return true;
2070 }
2071
2072 static int mirror_split(const char *fname, __u32 id, const char *pool,
2073                         enum mirror_flags mflags, const char *victim_file)
2074 {
2075         struct llapi_layout *layout;
2076         char parent[PATH_MAX];
2077         char victim[PATH_MAX];
2078         int flags = O_CREAT | O_EXCL | O_LOV_DELAY_CREATE | O_NOFOLLOW;
2079         char *ptr;
2080         struct ll_ioc_lease *data;
2081         uint16_t mirror_count;
2082         __u32 mirror_id;
2083         int mdt_index;
2084         int fd, fdv;
2085         bool purge = true; /* delete mirror by setting fdv=fd */
2086         bool is_encrypted;
2087         int rc;
2088
2089         if (victim_file && (strcmp(fname, victim_file) == 0)) {
2090                 fprintf(stderr,
2091                         "error %s: the source file '%s' and -f file are the same\n",
2092                         progname, fname);
2093                 return -EINVAL;
2094         }
2095
2096         /* check fname contains mirror with mirror_id/comp_id */
2097         layout = llapi_layout_get_by_path(fname, 0);
2098         if (!layout) {
2099                 fprintf(stderr,
2100                         "error %s: file '%s' couldn't get layout\n",
2101                         progname, fname);
2102                 return -EINVAL;
2103         }
2104
2105         rc = llapi_layout_sanity(layout, fname, false, true);
2106         if (rc) {
2107                 llapi_layout_sanity_perror(rc);
2108                 goto free_layout;
2109         }
2110
2111         rc = llapi_layout_mirror_count_get(layout, &mirror_count);
2112         if (rc) {
2113                 fprintf(stderr,
2114                         "error %s: file '%s' couldn't get mirror count\n",
2115                         progname, fname);
2116                 goto free_layout;
2117         }
2118         if (mirror_count < 2) {
2119                 fprintf(stderr,
2120                         "error %s: file '%s' has %d component, cannot split\n",
2121                         progname, fname, mirror_count);
2122                 goto free_layout;
2123         }
2124
2125         if (mflags & MF_COMP_POOL) {
2126                 struct pool_to_id_cbdata data = { .pool = pool };
2127
2128                 rc = llapi_layout_comp_iterate(layout, find_mirror_id_by_pool,
2129                                                &data);
2130                 mirror_id = data.id;
2131         } else if (mflags & MF_COMP_ID) {
2132                 rc = llapi_layout_comp_iterate(layout, find_comp_id, &id);
2133                 mirror_id = mirror_id_of(id);
2134         } else {
2135                 rc = llapi_layout_comp_iterate(layout, find_mirror_id, &id);
2136                 mirror_id = id;
2137         }
2138         if (rc < 0) {
2139                 fprintf(stderr, "error %s: failed to iterate layout of '%s'\n",
2140                         progname, fname);
2141                 goto free_layout;
2142         } else if (rc == LLAPI_LAYOUT_ITER_CONT) {
2143                 if (mflags & MF_COMP_POOL) {
2144                         fprintf(stderr,
2145                                 "error %s: file '%s' does not contain mirror with pool '%s'\n",
2146                                 progname, fname, pool);
2147                         goto free_layout;
2148                 } else if (mflags & MF_COMP_ID) {
2149                         fprintf(stderr,
2150                                 "error %s: file '%s' does not contain mirror with comp-id %u\n",
2151                                 progname, fname, id);
2152                         goto free_layout;
2153                 } else {
2154                         fprintf(stderr,
2155                                 "error %s: file '%s' does not contain mirror with id %u\n",
2156                                 progname, fname, id);
2157                         goto free_layout;
2158                 }
2159         }
2160
2161         if (!victim_file && mflags & MF_DESTROY)
2162                 /* Allow mirror split even without the key on encrypted files,
2163                  * and in this case of a 'split -d', open file with O_DIRECT
2164                  * (no IOs will be done).
2165                  */
2166                 fd = open(fname, O_RDWR | O_DIRECT | O_FILE_ENC);
2167         else
2168                 fd = open(fname, O_RDWR);
2169
2170         if (fd < 0) {
2171                 fprintf(stderr,
2172                         "error %s: open file '%s' failed: %s\n",
2173                         progname, fname, strerror(errno));
2174                 goto free_layout;
2175         }
2176
2177         /* get victim file directory pathname */
2178         if (strlen(fname) > sizeof(parent) - 1) {
2179                 fprintf(stderr, "error %s: file name of '%s' too long\n",
2180                         progname, fname);
2181                 rc = -ERANGE;
2182                 goto close_fd;
2183         }
2184         strncpy(parent, fname, sizeof(parent));
2185         ptr = strrchr(parent, '/');
2186         if (!ptr) {
2187                 if (!getcwd(parent, sizeof(parent))) {
2188                         fprintf(stderr, "error %s: getcwd failed: %s\n",
2189                                 progname, strerror(errno));
2190                         rc = -errno;
2191                         goto close_fd;
2192                 }
2193         } else {
2194                 if (ptr == parent)
2195                         ptr = parent + 1;
2196                 *ptr = '\0';
2197         }
2198
2199         rc = llapi_file_fget_mdtidx(fd, &mdt_index);
2200         if (rc < 0) {
2201                 fprintf(stderr, "%s: cannot get MDT index of '%s'\n",
2202                         progname, fname);
2203                 goto close_fd;
2204         }
2205
2206         rc = llapi_file_is_encrypted(fd);
2207         if (rc < 0) {
2208                 fprintf(stderr, "%s: cannot get flags of '%s': %d\n",
2209                         progname, fname, rc);
2210                 goto close_fd;
2211         }
2212         is_encrypted = rc;
2213
2214 again:
2215         if (!victim_file) {
2216                 /* use a temp file to store the splitted layout */
2217                 if (mflags & MF_DESTROY) {
2218                         char file_path[PATH_MAX];
2219                         unsigned int rnumber;
2220                         int open_flags;
2221
2222                         if (last_non_stale_mirror(mirror_id, layout)) {
2223                                 rc = -EUCLEAN;
2224                                 fprintf(stderr,
2225                                         "%s: cannot destroy the last non-stale mirror of file '%s'\n",
2226                                         progname, fname);
2227                                 goto close_fd;
2228                         }
2229
2230                         if (purge) {
2231                                 /* don't use volatile file for mirror destroy */
2232                                 fdv = fd;
2233                         } else {
2234                                 /**
2235                                  * try the old way to delete mirror using
2236                                  * volatile file.
2237                                  */
2238                                 do {
2239                                         rnumber = random();
2240                                         rc = snprintf(file_path,
2241                                                       sizeof(file_path),
2242                                                       "%s/" LUSTRE_VOLATILE_HDR ":%.4X:%.4X:fd=%.2d",
2243                                                       parent, mdt_index,
2244                                                       rnumber, fd);
2245                                         if (rc < 0 ||
2246                                             rc >= sizeof(file_path)) {
2247                                                 fdv = -ENAMETOOLONG;
2248                                                 break;
2249                                         }
2250
2251                                         open_flags = O_RDWR |
2252                                              (O_LOV_DELAY_CREATE & ~O_ACCMODE) |
2253                                              O_CREAT | O_EXCL | O_NOFOLLOW |
2254                                              /* O_DIRECT for mirror split -d */
2255                                              O_DIRECT |
2256                                              /* Allow split without the key */
2257                                              O_FILE_ENC;
2258                                         fdv = open(file_path, open_flags,
2259                                                    S_IRUSR | S_IWUSR);
2260                                         if (fdv < 0)
2261                                                 rc = -errno;
2262                                 } while (fdv < 0 && rc == -EEXIST);
2263                         }
2264                 } else {
2265                         if (is_encrypted) {
2266                                 rc = -1;
2267                                 fprintf(stderr,
2268                                         "error %s: not permitted on encrypted file '%s': %d\n",
2269                                         progname, fname, rc);
2270                                 goto close_fd;
2271                         }
2272
2273                         snprintf(victim, sizeof(victim), "%s.mirror~%u",
2274                                  fname, mirror_id);
2275                         fdv = open(victim, flags, S_IRUSR | S_IWUSR);
2276                 }
2277         } else {
2278                 /* user specified victim file */
2279                 if (is_encrypted) {
2280                         rc = -1;
2281                         fprintf(stderr,
2282                                 "error %s: not permitted on encrypted file '%s': %d\n",
2283                                 progname, fname, rc);
2284                         goto close_fd;
2285                 }
2286                 fdv = open(victim_file, flags, S_IRUSR | S_IWUSR);
2287         }
2288
2289         if (fdv < 0) {
2290                 fprintf(stderr,
2291                         "error %s: create victim file failed: %s\n",
2292                         progname, strerror(errno));
2293                 goto close_fd;
2294         }
2295
2296         /* get lease lock of fname */
2297         rc = llapi_lease_acquire(fd, LL_LEASE_WRLCK);
2298         if (rc < 0) {
2299                 fprintf(stderr,
2300                         "error %s: cannot get lease of file '%s': %d\n",
2301                         progname, fname, rc);
2302                 goto close_victim;
2303         }
2304
2305         /* Atomatically put lease, split layouts and close. */
2306         data = malloc(offsetof(typeof(*data), lil_ids[2]));
2307         if (!data) {
2308                 rc = -ENOMEM;
2309                 goto close_victim;
2310         }
2311
2312         data->lil_mode = LL_LEASE_UNLCK;
2313         data->lil_flags = LL_LEASE_LAYOUT_SPLIT;
2314         data->lil_count = 2;
2315         data->lil_ids[0] = fdv;
2316         data->lil_ids[1] = mirror_id;
2317         rc = llapi_lease_set(fd, data);
2318         if (rc <= 0) {
2319                 if (rc == -EINVAL && purge) {
2320                         /* could be old MDS which prohibit fd==fdv */
2321                         purge = false;
2322                         goto again;
2323
2324                 }
2325                 if (rc == 0) /* lost lease lock */
2326                         rc = -EBUSY;
2327                 fprintf(stderr,
2328                         "error %s: cannot split '%s': %s\n",
2329                         progname, fname, strerror(-rc));
2330         } else {
2331                 rc = 0;
2332         }
2333         free(data);
2334
2335 close_victim:
2336         if (!purge)
2337                 close(fdv);
2338 close_fd:
2339         close(fd);
2340 free_layout:
2341         llapi_layout_free(layout);
2342         return rc;
2343 }
2344
2345 static inline
2346 int lfs_mirror_resync_file(const char *fname, struct ll_ioc_lease *ioc,
2347                            __u16 *mirror_ids, int ids_nr);
2348
2349 static int lfs_migrate_to_dom(int fd, int fdv, char *name,
2350                               __u64 migration_flags)
2351 {
2352         struct ll_ioc_lease *data = NULL;
2353         int rc;
2354
2355         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
2356         if (rc < 0) {
2357                 error_loc = "cannot get lease";
2358                 goto out_close;
2359         }
2360
2361         rc = migrate_nonblock(fd, fdv);
2362         if (rc < 0)
2363                 goto out_release;
2364
2365         /* Atomically put lease, merge layouts, resync and close. */
2366         data = calloc(1, offsetof(typeof(*data), lil_ids[1]));
2367         if (!data) {
2368                 error_loc = "memory allocation";
2369                 goto out_release;
2370         }
2371         data->lil_mode = LL_LEASE_UNLCK;
2372         data->lil_flags = LL_LEASE_LAYOUT_MERGE;
2373         data->lil_count = 1;
2374         data->lil_ids[0] = fdv;
2375         rc = llapi_lease_set(fd, data);
2376         if (rc < 0) {
2377                 error_loc = "cannot merge layout";
2378                 goto out_close;
2379         } else if (rc == 0) {
2380                 rc = -EBUSY;
2381                 error_loc = "lost lease lock";
2382                 goto out_close;
2383         }
2384         close(fd);
2385         close(fdv);
2386
2387         rc = lfs_mirror_resync_file(name, data, NULL, 0);
2388         if (rc) {
2389                 error_loc = "cannot resync file";
2390                 goto out;
2391         }
2392
2393         /* delete first mirror now */
2394         rc = mirror_split(name, 1, NULL, MF_DESTROY, NULL);
2395         if (rc < 0)
2396                 error_loc = "cannot delete old layout";
2397         goto out;
2398
2399 out_release:
2400         llapi_lease_release(fd);
2401 out_close:
2402         close(fd);
2403         close(fdv);
2404 out:
2405         if (rc < 0)
2406                 fprintf(stderr, "error: %s: %s: %s: %s\n",
2407                         progname, name, error_loc, strerror(-rc));
2408         else if (migration_flags & LLAPI_MIGRATION_VERBOSE)
2409                 printf("%s\n", name);
2410         if (data)
2411                 free(data);
2412         return rc;
2413 }
2414
2415 /**
2416  * Parse a string containing an target index list into an array of integers.
2417  *
2418  * The input string contains a comma delimited list of individual
2419  * indices and ranges, for example "1,2-4,7". Add the indices into the
2420  * \a tgts array and remove duplicates.
2421  *
2422  * \param[out] tgts             array to store indices in
2423  * \param[in] size              size of \a tgts array
2424  * \param[in] offset            starting index in \a tgts
2425  * \param[in] arg               string containing OST index list
2426  * \param[in/out] overstriping  index list may contain duplicates
2427  *
2428  * \retval positive    number of indices in \a tgts
2429  * \retval -EINVAL     unable to parse \a arg
2430  */
2431 static int parse_targets(__u32 *tgts, int size, int offset, char *arg,
2432                          unsigned long long *pattern)
2433 {
2434         int rc;
2435         int nr = offset;
2436         int slots = size - offset;
2437         char *ptr = NULL;
2438         bool overstriped = false;
2439         bool end_of_loop;
2440
2441         if (!arg)
2442                 return -EINVAL;
2443
2444         end_of_loop = false;
2445         while (!end_of_loop) {
2446                 int start_index = 0;
2447                 int end_index = 0;
2448                 int i;
2449                 char *endptr = NULL;
2450
2451                 rc = -EINVAL;
2452
2453                 ptr = strchrnul(arg, ',');
2454
2455                 end_of_loop = *ptr == '\0';
2456                 *ptr = '\0';
2457
2458                 errno = 0;
2459                 start_index = strtol(arg, &endptr, 0);
2460                 if (endptr == arg) /* no data at all */
2461                         break;
2462                 if (errno != 0 || start_index < -1 ||
2463                     (*endptr != '-' && *endptr != '\0'))
2464                         break;
2465
2466                 end_index = start_index;
2467                 if (*endptr == '-') {
2468                         errno = 0;
2469                         end_index = strtol(endptr + 1, &endptr, 0);
2470                         if (errno != 0 || *endptr != '\0' || end_index < -1)
2471                                 break;
2472                         if (end_index < start_index)
2473                                 break;
2474                 }
2475
2476                 for (i = start_index; i <= end_index && slots > 0; i++) {
2477                         int j;
2478
2479                         /* remove duplicate */
2480                         for (j = 0; j < offset; j++) {
2481                                 if (tgts[j] == i && pattern &&
2482                                     *pattern == LLAPI_LAYOUT_OVERSTRIPING)
2483                                         overstriped = true;
2484                                 else if (tgts[j] == i)
2485                                         return -EINVAL;
2486                         }
2487
2488                         j = offset;
2489
2490                         if (j == offset) { /* check complete */
2491                                 tgts[nr++] = i;
2492                                 --slots;
2493                         }
2494                 }
2495
2496                 if (slots == 0 && i < end_index)
2497                         break;
2498
2499                 *ptr = ',';
2500                 arg = ++ptr;
2501                 offset = nr;
2502                 rc = 0;
2503         }
2504         if (!end_of_loop && ptr)
2505                 *ptr = ',';
2506
2507         if (!overstriped && pattern)
2508                 *pattern = LLAPI_LAYOUT_DEFAULT;
2509
2510         return rc < 0 ? rc : nr;
2511 }
2512
2513 struct lfs_setstripe_args {
2514         unsigned long long       lsa_comp_end;
2515         unsigned long long       lsa_stripe_size;
2516         unsigned long long       lsa_extension_size;
2517         long long                lsa_stripe_count;
2518         long long                lsa_stripe_off;
2519         __u32                    lsa_comp_flags;
2520         __u32                    lsa_comp_neg_flags;
2521         unsigned long long       lsa_pattern;
2522         unsigned int             lsa_mirror_count;
2523         int                      lsa_nr_tgts;
2524         bool                     lsa_first_comp;
2525         bool                     lsa_extension_comp;
2526         __u32                   *lsa_tgts;
2527         char                    *lsa_pool_name;
2528 };
2529
2530 static inline void setstripe_args_init(struct lfs_setstripe_args *lsa)
2531 {
2532         unsigned int mirror_count = lsa->lsa_mirror_count;
2533         bool first_comp = lsa->lsa_first_comp;
2534
2535         memset(lsa, 0, sizeof(*lsa));
2536
2537         lsa->lsa_stripe_size = LLAPI_LAYOUT_DEFAULT;
2538         lsa->lsa_stripe_count = LLAPI_LAYOUT_DEFAULT;
2539         lsa->lsa_stripe_off = LLAPI_LAYOUT_DEFAULT;
2540         lsa->lsa_pattern = LLAPI_LAYOUT_RAID0;
2541         lsa->lsa_pool_name = NULL;
2542
2543         lsa->lsa_mirror_count = mirror_count;
2544         lsa->lsa_first_comp = first_comp;
2545 }
2546
2547 /**
2548  * setstripe_args_init_inherit() - Initialize and inherit stripe options.
2549  * @lsa: Stripe options to be initialized and inherited.
2550  *
2551  * This function initializes stripe options in @lsa and inherit
2552  * stripe_size, stripe_count and OST pool_name options.
2553  *
2554  * Return: void.
2555  */
2556 static inline void setstripe_args_init_inherit(struct lfs_setstripe_args *lsa)
2557 {
2558         unsigned long long stripe_size;
2559         long long stripe_count;
2560         char *pool_name = NULL;
2561
2562         stripe_size = lsa->lsa_stripe_size;
2563         stripe_count = lsa->lsa_stripe_count;
2564         pool_name = lsa->lsa_pool_name;
2565
2566         setstripe_args_init(lsa);
2567
2568         lsa->lsa_stripe_size = stripe_size;
2569         lsa->lsa_stripe_count = stripe_count;
2570         lsa->lsa_pool_name = pool_name;
2571 }
2572
2573 static inline bool setstripe_args_specified(struct lfs_setstripe_args *lsa)
2574 {
2575         return (lsa->lsa_stripe_size != LLAPI_LAYOUT_DEFAULT ||
2576                 lsa->lsa_stripe_count != LLAPI_LAYOUT_DEFAULT ||
2577                 lsa->lsa_stripe_off != LLAPI_LAYOUT_DEFAULT ||
2578                 lsa->lsa_pattern != LLAPI_LAYOUT_RAID0 ||
2579                 lsa->lsa_comp_end != 0);
2580 }
2581
2582 static int lsa_args_stripe_count_check(struct lfs_setstripe_args *lsa)
2583 {
2584         if (lsa->lsa_nr_tgts) {
2585                 if (lsa->lsa_nr_tgts < 0 ||
2586                     lsa->lsa_nr_tgts >= LOV_MAX_STRIPE_COUNT) {
2587                         fprintf(stderr, "Invalid nr_tgts(%d)\n",
2588                                 lsa->lsa_nr_tgts);
2589                         errno = EINVAL;
2590                         return -1;
2591                 }
2592
2593                 if (lsa->lsa_stripe_count > 0 &&
2594                     lsa->lsa_stripe_count != LLAPI_LAYOUT_DEFAULT &&
2595                     lsa->lsa_stripe_count != LLAPI_LAYOUT_WIDE &&
2596                     lsa->lsa_nr_tgts != lsa->lsa_stripe_count) {
2597                         fprintf(stderr, "stripe_count(%lld) != nr_tgts(%d)\n",
2598                                 lsa->lsa_stripe_count,
2599                                 lsa->lsa_nr_tgts);
2600                         errno = EINVAL;
2601                         return -1;
2602                 }
2603         }
2604
2605         return 0;
2606
2607 }
2608
2609 /**
2610  * comp_args_to_layout() - Create or extend a composite layout.
2611  * @composite:       Pointer to the composite layout.
2612  * @lsa:             Stripe options for the new component.
2613  *
2614  * This function creates or extends a composite layout by adding a new
2615  * component with stripe options from @lsa.
2616  *
2617  * When modified, adjust llapi_stripe_param_verify() if needed as well.
2618  *
2619  * Return: 0 on success or an error code on failure.
2620  */
2621 static int comp_args_to_layout(struct llapi_layout **composite,
2622                                struct lfs_setstripe_args *lsa,
2623                                bool set_extent)
2624 {
2625         struct llapi_layout *layout = *composite;
2626         uint64_t prev_end = 0;
2627         uint64_t size;
2628         int i = 0, rc;
2629
2630 new_comp:
2631         if (!layout) {
2632                 layout = llapi_layout_alloc();
2633                 if (!layout) {
2634                         fprintf(stderr, "Alloc llapi_layout failed. %s\n",
2635                                 strerror(errno));
2636                         errno = ENOMEM;
2637                         return -1;
2638                 }
2639                 *composite = layout;
2640                 lsa->lsa_first_comp = true;
2641         } else {
2642                 uint64_t start;
2643
2644                 /*
2645                  * Get current component extent, current component
2646                  * must be the tail component.
2647                  */
2648                 rc = llapi_layout_comp_extent_get(layout, &start, &prev_end);
2649                 if (rc) {
2650                         fprintf(stderr, "Get comp extent failed. %s\n",
2651                                 strerror(errno));
2652                         return rc;
2653                 }
2654
2655                 if (lsa->lsa_first_comp) {
2656                         prev_end = 0;
2657                         rc = llapi_layout_add_first_comp(layout);
2658                 } else {
2659                         rc = llapi_layout_comp_add(layout);
2660                 }
2661                 if (rc) {
2662                         fprintf(stderr, "Add component failed. %s\n",
2663                                 strerror(errno));
2664                         return rc;
2665                 }
2666         }
2667
2668         rc = llapi_layout_comp_flags_set(layout, lsa->lsa_comp_flags);
2669         if (rc) {
2670                 fprintf(stderr, "Set flags 0x%x failed: %s\n",
2671                         lsa->lsa_comp_flags, strerror(errno));
2672                 return rc;
2673         }
2674
2675         if (set_extent) {
2676                 uint64_t comp_end = lsa->lsa_comp_end;
2677
2678                 /*
2679                  * The extendable component is 0-length, so it can be removed
2680                  * if there is insufficient space to extend it.
2681                  */
2682                 if (lsa->lsa_extension_comp)
2683                         comp_end = prev_end;
2684
2685                 rc = llapi_layout_comp_extent_set(layout, prev_end,
2686                                                   comp_end);
2687                 if (rc) {
2688                         fprintf(stderr, "Set extent [%lu, %lu) failed. %s\n",
2689                                 prev_end, comp_end, strerror(errno));
2690                         return rc;
2691                 }
2692         }
2693         /* reset lsa_first_comp */
2694         lsa->lsa_first_comp = false;
2695
2696         /* Data-on-MDT component setting */
2697         if (lsa->lsa_pattern == LLAPI_LAYOUT_MDT) {
2698                 /* Yaml support */
2699                 if (lsa->lsa_stripe_count == 0)
2700                         lsa->lsa_stripe_count = LLAPI_LAYOUT_DEFAULT;
2701                 if (lsa->lsa_stripe_size == lsa->lsa_comp_end)
2702                         lsa->lsa_stripe_size = LLAPI_LAYOUT_DEFAULT;
2703                 if (lsa->lsa_stripe_off == -1 ||
2704                     lsa->lsa_stripe_off == 0)
2705                         lsa->lsa_stripe_off = LLAPI_LAYOUT_DEFAULT;
2706                 /*
2707                  * In case of Data-on-MDT patterns the only extra option
2708                  * applicable is stripe size option.
2709                  */
2710                 if (lsa->lsa_stripe_count != LLAPI_LAYOUT_DEFAULT) {
2711                         fprintf(stderr,
2712                                 "Option 'stripe-count' can't be specified with Data-on-MDT component: %lld\n",
2713                                 lsa->lsa_stripe_count);
2714                         errno = EINVAL;
2715                         return -1;
2716                 }
2717                 if (lsa->lsa_stripe_size != LLAPI_LAYOUT_DEFAULT &&
2718                     lsa->lsa_stripe_size != lsa->lsa_comp_end - prev_end) {
2719                         fprintf(stderr,
2720                                 "Option 'stripe-size' can't be specified with Data-on-MDT component: %llu\n",
2721                                 lsa->lsa_stripe_size);
2722                         errno = EINVAL;
2723                         return -1;
2724                 }
2725                 if (lsa->lsa_nr_tgts != 0) {
2726                         fprintf(stderr,
2727                                 "Option 'ost-list' can't be specified with Data-on-MDT component: '%i'\n",
2728                                 lsa->lsa_nr_tgts);
2729                         errno = EINVAL;
2730                         return -1;
2731                 }
2732                 if (lsa->lsa_stripe_off != LLAPI_LAYOUT_DEFAULT) {
2733                         fprintf(stderr,
2734                                 "Option 'stripe-offset' can't be specified with Data-on-MDT component: %lld\n",
2735                                 lsa->lsa_stripe_off);
2736                         errno = EINVAL;
2737                         return -1;
2738                 }
2739                 if (lsa->lsa_pool_name != 0) {
2740                         fprintf(stderr,
2741                                 "Option 'pool' can't be specified with Data-on-MDT component: '%s'\n",
2742                                 lsa->lsa_pool_name);
2743                         errno = EINVAL;
2744                         return -1;
2745                 }
2746
2747                 rc = llapi_layout_pattern_set(layout, lsa->lsa_pattern);
2748                 if (rc) {
2749                         fprintf(stderr, "Set stripe pattern %#llx failed. %s\n",
2750                                 lsa->lsa_pattern,
2751                                 strerror(errno));
2752                         return rc;
2753                 }
2754                 /* Data-on-MDT component has always single stripe up to end */
2755                 lsa->lsa_stripe_size = lsa->lsa_comp_end;
2756         } else if (lsa->lsa_pattern == LLAPI_LAYOUT_OVERSTRIPING) {
2757                 rc = llapi_layout_pattern_set(layout, lsa->lsa_pattern);
2758                 if (rc) {
2759                         fprintf(stderr, "Set stripe pattern %#llx failed. %s\n",
2760                                 lsa->lsa_pattern,
2761                                 strerror(errno));
2762                         return rc;
2763                 }
2764         }
2765
2766         size = lsa->lsa_comp_flags & LCME_FL_EXTENSION ?
2767                 lsa->lsa_extension_size : lsa->lsa_stripe_size;
2768
2769         if (lsa->lsa_comp_flags & LCME_FL_EXTENSION)
2770                 rc = llapi_layout_extension_size_set(layout, size);
2771         else
2772                 rc = llapi_layout_stripe_size_set(layout, size);
2773
2774         if (rc) {
2775                 fprintf(stderr, "Set stripe size %lu failed: %s\n",
2776                         size, strerror(errno));
2777                 return rc;
2778         }
2779
2780         rc = llapi_layout_stripe_count_set(layout, lsa->lsa_stripe_count);
2781         if (rc) {
2782                 fprintf(stderr, "Set stripe count %lld failed: %s\n",
2783                         lsa->lsa_stripe_count, strerror(errno));
2784                 return rc;
2785         }
2786
2787         if (lsa->lsa_pool_name) {
2788                 rc = llapi_layout_pool_name_set(layout, lsa->lsa_pool_name);
2789                 if (rc) {
2790                         fprintf(stderr, "Set pool name: %s failed. %s\n",
2791                                 lsa->lsa_pool_name, strerror(errno));
2792                         return rc;
2793                 }
2794         } else {
2795                 rc = llapi_layout_pool_name_set(layout, "");
2796                 if (rc) {
2797                         fprintf(stderr, "Clear pool name failed: %s\n",
2798                                 strerror(errno));
2799                         return rc;
2800                 }
2801         }
2802
2803         rc = lsa_args_stripe_count_check(lsa);
2804         if (rc)
2805                 return rc;
2806
2807         if (lsa->lsa_nr_tgts > 0) {
2808                 bool found = false;
2809
2810                 for (i = 0; i < lsa->lsa_nr_tgts; i++) {
2811                         rc = llapi_layout_ost_index_set(layout, i,
2812                                                         lsa->lsa_tgts[i]);
2813                         if (rc)
2814                                 break;
2815
2816                         /* Make sure stripe offset is in OST list. */
2817                         if (lsa->lsa_tgts[i] == lsa->lsa_stripe_off)
2818                                 found = true;
2819                 }
2820                 if (!found) {
2821                         fprintf(stderr, "Invalid stripe offset '%lld', not in the target list",
2822                                 lsa->lsa_stripe_off);
2823                         errno = EINVAL;
2824                         return -1;
2825                 }
2826         } else if (lsa->lsa_stripe_off != LLAPI_LAYOUT_DEFAULT &&
2827                    lsa->lsa_stripe_off != -1) {
2828                 rc = llapi_layout_ost_index_set(layout, 0, lsa->lsa_stripe_off);
2829         }
2830         if (rc) {
2831                 fprintf(stderr, "Set ost index %d failed. %s\n",
2832                         i, strerror(errno));
2833                 return rc;
2834         }
2835
2836         /* Create the second, virtual component of extension space */
2837         if (lsa->lsa_extension_comp) {
2838                 lsa->lsa_comp_flags |= LCME_FL_EXTENSION;
2839                 lsa->lsa_extension_comp = false;
2840                 goto new_comp;
2841         }
2842
2843         return rc;
2844 }
2845
2846 static int build_component(struct llapi_layout **layout,
2847                            struct lfs_setstripe_args *lsa, bool set_extent)
2848 {
2849         int rc;
2850
2851         rc = comp_args_to_layout(layout, lsa, set_extent);
2852         if (rc)
2853                 return rc;
2854
2855         if (lsa->lsa_mirror_count > 0) {
2856                 rc = llapi_layout_mirror_count_set(*layout,
2857                                                    lsa->lsa_mirror_count);
2858                 if (rc)
2859                         return rc;
2860
2861                 rc = llapi_layout_flags_set(*layout, LCM_FL_RDONLY);
2862                 if (rc)
2863                         return rc;
2864                 lsa->lsa_mirror_count = 0;
2865         }
2866
2867         return rc;
2868 }
2869
2870 static int build_prev_component(struct llapi_layout **layout,
2871                                 struct lfs_setstripe_args *prev,
2872                                 struct lfs_setstripe_args *lsa,
2873                                 bool set_extent)
2874 {
2875         int extension = lsa->lsa_comp_flags & LCME_FL_EXTENSION;
2876         int rc;
2877
2878         if (prev->lsa_stripe_size) {
2879                 if (extension) {
2880                         prev->lsa_comp_end = lsa->lsa_comp_end;
2881                         prev->lsa_extension_size = lsa->lsa_extension_size;
2882                         prev->lsa_extension_comp = true;
2883                 }
2884
2885                 rc = build_component(layout, prev, true);
2886                 if (rc)
2887                         return rc;
2888         }
2889
2890         /*
2891          * Copy lsa to previous lsa;
2892          * if this is an extension component, make the previous invalid;
2893          */
2894         if (extension)
2895                 prev->lsa_stripe_size = 0;
2896         else
2897                 *prev = *lsa;
2898
2899         return 0;
2900 }
2901
2902 #ifndef LCME_TEMPLATE_FLAGS
2903 #define LCME_TEMPLATE_FLAGS     (LCME_FL_PREF_RW | LCME_FL_NOSYNC | \
2904                                  LCME_FL_EXTENSION)
2905 #endif
2906
2907 static int build_layout_from_yaml_node(struct cYAML *node,
2908                                        struct llapi_layout **layout,
2909                                        struct lfs_setstripe_args *lsa,
2910                                        struct lfs_setstripe_args *prevp)
2911 {
2912         struct lfs_setstripe_args prev = { 0 };
2913         __u32 *osts = lsa->lsa_tgts;
2914         char *string;
2915         int rc = 0;
2916
2917         if (!prevp)
2918                 prevp = &prev;
2919
2920         while (node) {
2921                 string = node->cy_string;
2922
2923                 if (node->cy_type == CYAML_TYPE_OBJECT) {
2924                         /* go deep to sub blocks */
2925                         if (string && !strncmp(string, "component", 9) &&
2926                             strncmp(string, "component0", 10) &&
2927                             strncmp(string, "components", 10)) {
2928                                 rc = build_prev_component(layout, prevp, lsa,
2929                                                           true);
2930                                 if (rc)
2931                                         return rc;
2932
2933                                 /* initialize lsa. */
2934                                 setstripe_args_init(lsa);
2935                                 lsa->lsa_first_comp = false;
2936                                 lsa->lsa_tgts = osts;
2937                         }
2938
2939                         rc = build_layout_from_yaml_node(node->cy_child, layout,
2940                                                          lsa, prevp);
2941                         if (rc)
2942                                 return rc;
2943                 } else {
2944                         if (!node->cy_string)
2945                                 return -EINVAL;
2946
2947                         /* skip leading lmm_ if present, to simplify parsing */
2948                         if (strncmp(string, "lmm_", 4) == 0)
2949                                 string += 4;
2950
2951                         if (node->cy_type == CYAML_TYPE_STRING) {
2952                                 if (!strcmp(string, "lcme_extent.e_end")) {
2953                                         if (!strcmp(node->cy_valuestring, "EOF") ||
2954                                             !strcmp(node->cy_valuestring, "eof"))
2955                                                 lsa->lsa_comp_end = LUSTRE_EOF;
2956                                 } else if (!strcmp(string, "pool")) {
2957                                         lsa->lsa_pool_name = node->cy_valuestring;
2958                                 } else if (!strcmp(string, "pattern")) {
2959                                         if (!strcmp(node->cy_valuestring, "mdt"))
2960                                                 lsa->lsa_pattern = LLAPI_LAYOUT_MDT;
2961                                         if (!strcmp(node->cy_valuestring,
2962                                                     "raid0,overstriped"))
2963                                                 lsa->lsa_pattern =
2964                                                         LLAPI_LAYOUT_OVERSTRIPING;
2965                                 } else if (!strcmp(string, "lcme_flags")) {
2966                                         rc = comp_str2flags(node->cy_valuestring,
2967                                                             &lsa->lsa_comp_flags,
2968                                                             &lsa->lsa_comp_neg_flags);
2969                                         if (rc)
2970                                                 return rc;
2971                                         /*
2972                                          * Only template flags have meaning in
2973                                          * the layout for a new file
2974                                          */
2975                                         lsa->lsa_comp_flags &= LCME_TEMPLATE_FLAGS;
2976                                 }
2977                         } else if (node->cy_type == CYAML_TYPE_NUMBER) {
2978                                 if (!strcmp(string, "lcm_mirror_count")) {
2979                                         lsa->lsa_mirror_count = node->cy_valueint;
2980                                 } else if (!strcmp(string, "lcme_extent.e_start")) {
2981                                         if (node->cy_valueint == 0)
2982                                                 lsa->lsa_first_comp = true;
2983                                 } else if (!strcmp(string, "lcme_extent.e_end")) {
2984                                         if (node->cy_valueint == -1)
2985                                                 lsa->lsa_comp_end = LUSTRE_EOF;
2986                                         else
2987                                                 lsa->lsa_comp_end = node->cy_valueint;
2988                                 } else if (!strcmp(string, "stripe_count")) {
2989                                         lsa->lsa_stripe_count = node->cy_valueint;
2990                                 } else if (!strcmp(string, "stripe_size")) {
2991                                         lsa->lsa_stripe_size = node->cy_valueint;
2992                                 } else if (!strcmp(string, "extension_size")) {
2993                                         lsa->lsa_extension_size = node->cy_valueint;
2994                                         lsa->lsa_extension_comp = true;
2995                                 } else if (!strcmp(string, "stripe_offset")) {
2996                                         lsa->lsa_stripe_off = node->cy_valueint;
2997                                 } else if (!strcmp(string, "l_ost_idx")) {
2998                                         osts[lsa->lsa_nr_tgts] = node->cy_valueint;
2999                                         lsa->lsa_nr_tgts++;
3000                                 }
3001                         }
3002                 }
3003                 node = node->cy_next;
3004         }
3005
3006         if (prevp == &prev) {
3007                 rc = build_prev_component(layout, prevp, lsa, true);
3008                 if (rc)
3009                         return rc;
3010
3011                 if (!(lsa->lsa_comp_flags & LCME_FL_EXTENSION))
3012                         rc = build_component(layout, lsa, *layout != NULL);
3013         }
3014
3015         return rc;
3016 }
3017
3018 static int lfs_comp_create_from_yaml(char *template,
3019                                      struct llapi_layout **layout,
3020                                      struct lfs_setstripe_args *lsa,
3021                                      __u32 *osts)
3022 {
3023         struct cYAML *tree = NULL, *err_rc = NULL;
3024         int rc = 0;
3025
3026         tree = cYAML_build_tree(template, NULL, 0, &err_rc, false);
3027         if (!tree) {
3028                 fprintf(stderr, "%s: cannot parse YAML file %s\n",
3029                         progname, template);
3030                 cYAML_build_error(-EINVAL, -1, "yaml", "from comp yaml",
3031                                   "can't parse", &err_rc);
3032                 cYAML_print_tree2file(stderr, err_rc);
3033                 cYAML_free_tree(err_rc);
3034                 rc = -EINVAL;
3035                 goto err;
3036         }
3037
3038         /* initialize lsa for plain file */
3039         setstripe_args_init(lsa);
3040         lsa->lsa_tgts = osts;
3041
3042         rc = build_layout_from_yaml_node(tree, layout, lsa, NULL);
3043         if (rc) {
3044                 fprintf(stderr, "%s: cannot build layout from YAML file %s.\n",
3045                         progname, template);
3046                 goto err;
3047         }
3048         /* clean clean lsa */
3049         setstripe_args_init(lsa);
3050
3051 err:
3052         if (tree)
3053                 cYAML_free_tree(tree);
3054         return rc;
3055 }
3056
3057 /**
3058  * Get the extension size from the next (SEL) component and extend the
3059  * current component on it. The start of the next component is to be
3060  * adjusted as well.
3061  *
3062  * \param[in] layout    the current layout
3063  * \param[in] start     the start of the current component
3064  * \param[in,out] end   the end of the current component
3065  * \param[in] offset    the offset to adjust the end position to instead of
3066  *                      extension size
3067  *
3068  * \retval 0            - extended successfully
3069  * \retval < 0          - error
3070  */
3071 static int layout_extend_comp(struct llapi_layout *layout,
3072                               uint64_t start, uint64_t *end,
3073                               uint64_t offset)
3074 {
3075         uint64_t size, next_start, next_end;
3076         int rc;
3077
3078         rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_NEXT);
3079         if (rc < 0) {
3080                 fprintf(stderr,
3081                         "%s setstripe: cannot move component cursor: %s\n",
3082                         progname, strerror(errno));
3083                 return rc;
3084         }
3085
3086         /*
3087          * Even if the @size will not be used below, this will fail if
3088          * this is not a SEL component - a good confirmation we are
3089          * working on right components.
3090          */
3091         rc = llapi_layout_extension_size_get(layout, &size);
3092         if (rc < 0) {
3093                 fprintf(stderr,
3094                         "%s setstripe: cannot get component ext size: %s\n",
3095                         progname, strerror(errno));
3096                 return rc;
3097         }
3098
3099         rc = llapi_layout_comp_extent_get(layout, &next_start, &next_end);
3100         if (rc) {
3101                 fprintf(stderr, "%s setstripe: cannot get extent: %s\n",
3102                         progname, strerror(errno));
3103                 return rc;
3104         }
3105
3106         next_start += offset ?: size;
3107         rc = llapi_layout_comp_extent_set(layout, next_start, next_end);
3108         if (rc) {
3109                 fprintf(stderr, "%s setstripe: cannot set extent: %s\n",
3110                         progname, strerror(errno));
3111                 return rc;
3112         }
3113
3114         rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_PREV);
3115         if (rc < 0) {
3116                 fprintf(stderr,
3117                         "%s setstripe: cannot move component cursor: %s\n",
3118                         progname, strerror(errno));
3119                 return rc;
3120         }
3121
3122         *end += offset ?: size;
3123         rc = llapi_layout_comp_extent_set(layout, start, *end);
3124         if (rc) {
3125                 fprintf(stderr, "%s setstripe: cannot set extent: %s\n",
3126                         progname, strerror(errno));
3127                 return rc;
3128         }
3129
3130         return 0;
3131 }
3132
3133 /**
3134  * In 'lfs setstripe --component-add' mode, we need to fetch the extent
3135  * end of the last component in the existing file, and adjust the
3136  * first extent start of the components to be added accordingly.
3137  *
3138  * In the create mode, we need to check if the first component is an extendable
3139  * SEL component and extend its length to the extension size (first component
3140  * of the PFL file is initialised at the create time, cannot be 0-lenght.
3141  */
3142 static int layout_adjust_first_extent(char *fname, struct llapi_layout *layout,
3143                                       bool comp_add)
3144 {
3145         struct llapi_layout *head;
3146         uint64_t start = 0, prev_end = 0;
3147         uint64_t end;
3148         int rc, ret = 0;
3149
3150         if (!layout || !(comp_add || llapi_layout_is_composite(layout)))
3151                 return 0;
3152
3153         errno = 0;
3154         while (comp_add) {
3155                 head = llapi_layout_get_by_path(fname, 0);
3156                 if (!head) {
3157                         fprintf(stderr,
3158                                 "%s setstripe: cannot read layout from '%s': %s\n",
3159                                 progname, fname, strerror(errno));
3160                         return -EINVAL;
3161                 } else if (errno == ENODATA) {
3162                         /*
3163                          * file without LOVEA, this component-add will be turned
3164                          * into a component-create.
3165                          */
3166                         llapi_layout_free(head);
3167                         ret = -ENODATA;
3168
3169                         /*
3170                          * the new layout will be added to an empty one, it
3171                          * still needs to be adjusted below
3172                          */
3173                         comp_add = 0;
3174                         break;
3175                 } else if (!llapi_layout_is_composite(head)) {
3176                         fprintf(stderr,
3177                                 "%s setstripe: '%s' not a composite file\n",
3178                                 progname, fname);
3179                         llapi_layout_free(head);
3180                         return -EINVAL;
3181                 }
3182
3183                 rc = llapi_layout_comp_extent_get(head, &start, &prev_end);
3184                 if (rc) {
3185                         fprintf(stderr,
3186                                 "%s setstripe: cannot get prev extent: %s\n",
3187                                 progname, strerror(errno));
3188                         llapi_layout_free(head);
3189                         return rc;
3190                 }
3191
3192                 llapi_layout_free(head);
3193                 break;
3194         }
3195
3196         /* Make sure we use the first component of the layout to be added. */
3197         rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_FIRST);
3198         if (rc < 0) {
3199                 fprintf(stderr,
3200                         "%s setstripe: cannot move component cursor: %s\n",
3201                         progname, strerror(errno));
3202                 return rc;
3203         }
3204
3205         rc = llapi_layout_comp_extent_get(layout, &start, &end);
3206         if (rc) {
3207                 fprintf(stderr, "%s setstripe: cannot get extent: %s\n",
3208                         progname, strerror(errno));
3209                 return rc;
3210         }
3211
3212         if (start == 0 && end == 0) {
3213                 rc = layout_extend_comp(layout, start, &end,
3214                                         comp_add ? prev_end : 0);
3215                 if (rc)
3216                         return rc;
3217         }
3218
3219         if (start > prev_end || end < prev_end) {
3220                 fprintf(stderr,
3221                         "%s setstripe: first extent [%lu, %lu) not adjacent with extent end %lu\n",
3222                         progname, start, end, prev_end);
3223                 return -EINVAL;
3224         }
3225
3226         rc = llapi_layout_comp_extent_set(layout, prev_end, end);
3227         if (rc) {
3228                 fprintf(stderr,
3229                         "%s setstripe: cannot set component extent [%lu, %lu): %s\n",
3230                         progname, prev_end, end, strerror(errno));
3231                 return rc;
3232         }
3233
3234         return ret;
3235 }
3236
3237 static int mirror_adjust_first_extents(struct mirror_args *list)
3238 {
3239         int rc = 0;
3240
3241         if (!list)
3242                 return 0;
3243
3244         while (list) {
3245                 rc = layout_adjust_first_extent(NULL, list->m_layout, false);
3246                 if (rc)
3247                         break;
3248                 list = list->m_next;
3249         }
3250
3251         return rc;
3252 }
3253
3254 static inline bool arg_is_eof(char *arg)
3255 {
3256         return !strncmp(arg, "-1", strlen("-1")) ||
3257                !strncmp(arg, "EOF", strlen("EOF")) ||
3258                !strncmp(arg, "eof", strlen("eof"));
3259 }
3260
3261 /**
3262  * lfs_mirror_alloc() - Allocate a mirror argument structure.
3263  *
3264  * Return: Valid mirror_args pointer on success and
3265  *         NULL if memory allocation fails.
3266  */
3267 static struct mirror_args *lfs_mirror_alloc(void)
3268 {
3269         struct mirror_args *mirror = NULL;
3270
3271         while (1) {
3272                 mirror = calloc(1, sizeof(*mirror));
3273                 if (mirror) {
3274                         mirror->m_inherit = false;
3275                         break;
3276                 }
3277
3278                 sleep(1);
3279         }
3280
3281         return mirror;
3282 }
3283
3284 /**
3285  * lfs_mirror_free() - Free memory allocated for a mirror argument
3286  *                     structure.
3287  * @mirror: Previously allocated mirror argument structure by
3288  *          lfs_mirror_alloc().
3289  *
3290  * Free memory allocated for @mirror.
3291  *
3292  * Return: void.
3293  */
3294 static void lfs_mirror_free(struct mirror_args *mirror)
3295 {
3296         if (mirror->m_layout)
3297                 llapi_layout_free(mirror->m_layout);
3298         free(mirror);
3299 }
3300
3301 /**
3302  * lfs_mirror_list_free() - Free memory allocated for a mirror list.
3303  * @mirror_list: Previously allocated mirror list.
3304  *
3305  * Free memory allocated for @mirror_list.
3306  *
3307  * Return: void.
3308  */
3309 static void lfs_mirror_list_free(struct mirror_args *mirror_list)
3310 {
3311         struct mirror_args *next_mirror = NULL;
3312
3313         while (mirror_list) {
3314                 next_mirror = mirror_list->m_next;
3315                 lfs_mirror_free(mirror_list);
3316                 mirror_list = next_mirror;
3317         }
3318 }
3319
3320 enum {
3321         LFS_POOL_OPT = 3,
3322         LFS_COMP_COUNT_OPT,
3323         LFS_COMP_START_OPT,
3324         LFS_COMP_FLAGS_OPT,
3325         LFS_COMP_DEL_OPT,
3326         LFS_COMP_SET_OPT,
3327         LFS_COMP_ADD_OPT,
3328         LFS_COMP_NO_VERIFY_OPT,
3329         LFS_PROJID_OPT,
3330         LFS_LAYOUT_FLAGS_OPT, /* used for mirror and foreign flags */
3331         LFS_MIRROR_ID_OPT,
3332         LFS_MIRROR_STATE_OPT,
3333         LFS_LAYOUT_COPY,
3334         LFS_MIRROR_INDEX_OPT,
3335         LFS_LAYOUT_FOREIGN_OPT,
3336         LFS_MODE_OPT,
3337         LFS_NEWERXY_OPT,
3338         LFS_INHERIT_RR_OPT,
3339         LFS_FIND_PERM,
3340 };
3341
3342 #ifndef LCME_USER_MIRROR_FLAGS
3343 /* The mirror flags can be set by users at creation time. */
3344 #define LCME_USER_MIRROR_FLAGS  (LCME_FL_PREF_RW)
3345 #endif
3346
3347 /* functions */
3348 static int lfs_setstripe_internal(int argc, char **argv,
3349                                   enum setstripe_origin opc)
3350 {
3351         struct lfs_setstripe_args        lsa = { 0 };
3352         struct llapi_stripe_param       *param = NULL;
3353         struct find_param                migrate_mdt_param = {
3354                 .fp_max_depth = -1,
3355                 .fp_mdt_index = -1,
3356         };
3357         char                            *fname;
3358         int                              result = 0;
3359         int                              result2 = 0;
3360         char                            *end;
3361         int                              c;
3362         int                              delete = 0;
3363         unsigned long long               size_units = 1;
3364         bool                             migrate_mode = false;
3365         bool                             migrate_mdt_mode = false;
3366         bool                             setstripe_mode = false;
3367         bool                             migration_block = false;
3368         __u64                            migration_flags = 0;
3369         __u32                            tgts[LOV_MAX_STRIPE_COUNT] = { 0 };
3370         int                              comp_del = 0, comp_set = 0;
3371         int                              comp_add = 0;
3372         __u32                            comp_id = 0;
3373         struct llapi_layout             *layout = NULL;
3374         struct llapi_layout             **lpp = &layout;
3375         bool                             mirror_mode = false;
3376         bool                             has_m_file = false;
3377         __u32                            mirror_count = 0;
3378         enum mirror_flags                mirror_flags = 0;
3379         struct mirror_args              *mirror_list = NULL;
3380         struct mirror_args              *new_mirror = NULL;
3381         struct mirror_args              *last_mirror = NULL;
3382         __u16                            mirror_id = 0;
3383         char                             cmd[PATH_MAX];
3384         bool from_yaml = false;
3385         bool from_copy = false;
3386         char *template = NULL;
3387         bool foreign_mode = false;
3388         char *xattr = NULL;
3389         uint32_t type = LU_FOREIGN_TYPE_NONE, flags = 0;
3390         char *mode_opt = NULL;
3391         mode_t previous_umask = 0;
3392         mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
3393
3394         struct option long_opts[] = {
3395 /* find { .val = '0',   .name = "null",         .has_arg = no_argument }, */
3396 /* find { .val = 'A',   .name = "atime",        .has_arg = required_argument }*/
3397         /* --block is only valid in migrate mode */
3398         { .val = 'b',   .name = "block",        .has_arg = no_argument },
3399 /* find { .val = 'B',   .name = "btime",        .has_arg = required_argument }*/
3400         { .val = LFS_COMP_ADD_OPT,
3401                         .name = "comp-add",     .has_arg = no_argument },
3402         { .val = LFS_COMP_ADD_OPT,
3403                         .name = "component-add", .has_arg = no_argument },
3404         { .val = LFS_COMP_DEL_OPT,
3405                         .name = "comp-del",     .has_arg = no_argument },
3406         { .val = LFS_COMP_DEL_OPT,
3407                         .name = "component-del", .has_arg = no_argument },
3408         { .val = LFS_COMP_FLAGS_OPT,
3409                         .name = "comp-flags",   .has_arg = required_argument },
3410         { .val = LFS_COMP_FLAGS_OPT,
3411                         .name = "component-flags",
3412                                                 .has_arg = required_argument },
3413         { .val = LFS_COMP_SET_OPT,
3414                         .name = "comp-set",     .has_arg = no_argument },
3415         { .val = LFS_COMP_SET_OPT,
3416                         .name = "component-set",
3417                                                 .has_arg = no_argument},
3418         { .val = LFS_COMP_NO_VERIFY_OPT,
3419                         .name = "no-verify",    .has_arg = no_argument},
3420         { .val = LFS_LAYOUT_FLAGS_OPT,
3421                         .name = "flags",        .has_arg = required_argument},
3422         { .val = LFS_LAYOUT_FOREIGN_OPT,
3423                         .name = "foreign",      .has_arg = optional_argument},
3424         { .val = LFS_MIRROR_ID_OPT,
3425                         .name = "mirror-id",    .has_arg = required_argument},
3426         { .val = LFS_MODE_OPT,
3427                         .name = "mode",         .has_arg = required_argument},
3428         { .val = LFS_LAYOUT_COPY,
3429                         .name = "copy",         .has_arg = required_argument},
3430         { .val = 'c',   .name = "stripe-count", .has_arg = required_argument},
3431         { .val = 'c',   .name = "stripe_count", .has_arg = required_argument},
3432         { .val = 'c',   .name = "mdt-count",    .has_arg = required_argument},
3433         { .val = 'C',   .name = "overstripe-count",
3434                                                 .has_arg = required_argument},
3435         { .val = 'd',   .name = "delete",       .has_arg = no_argument},
3436         { .val = 'd',   .name = "destroy",      .has_arg = no_argument},
3437         /* used with "lfs migrate -m" */
3438         { .val = 'd',   .name = "directory",    .has_arg = no_argument},
3439         /* --non-direct is only valid in migrate mode */
3440         { .val = 'D',   .name = "non-direct",   .has_arg = no_argument },
3441         { .val = 'E',   .name = "comp-end",     .has_arg = required_argument},
3442         { .val = 'E',   .name = "component-end",
3443                                                 .has_arg = required_argument},
3444         { .val = 'f',   .name = "file",         .has_arg = required_argument },
3445 /* find { .val = 'F',   .name = "fid",          .has_arg = no_argument }, */
3446 /* find { .val = 'g',   .name = "gid",          .has_arg = no_argument }, */
3447 /* find { .val = 'G',   .name = "group",        .has_arg = required_argument }*/
3448         { .val = 'h',   .name = "help",         .has_arg = no_argument },
3449         { .val = 'H',   .name = "mdt-hash",     .has_arg = required_argument},
3450         { .val = 'i',   .name = "stripe-index", .has_arg = required_argument},
3451         { .val = 'i',   .name = "stripe_index", .has_arg = required_argument},
3452         { .val = 'I',   .name = "comp-id",      .has_arg = required_argument},
3453         { .val = 'I',   .name = "component-id", .has_arg = required_argument},
3454 /* find { .val = 'l',   .name = "lazy",         .has_arg = no_argument }, */
3455         { .val = 'L',   .name = "layout",       .has_arg = required_argument },
3456         { .val = 'm',   .name = "mdt",          .has_arg = required_argument},
3457         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument},
3458         { .val = 'm',   .name = "mdt_index",    .has_arg = required_argument},
3459         /* --non-block is only valid in migrate mode */
3460         { .val = 'n',   .name = "non-block",    .has_arg = no_argument },
3461         { .val = 'N',   .name = "mirror-count", .has_arg = optional_argument},
3462         { .val = 'o',   .name = "ost",          .has_arg = required_argument },
3463 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
3464         { .val = 'o',   .name = "ost-list",     .has_arg = required_argument },
3465         { .val = 'o',   .name = "ost_list",     .has_arg = required_argument },
3466 #endif
3467         { .val = 'p',   .name = "pool",         .has_arg = required_argument },
3468 /* find { .val = 'P',   .name = "print",        .has_arg = no_argument }, */
3469 /* getstripe { .val = 'q', .name = "quiet",     .has_arg = no_argument }, */
3470 /* getstripe { .val = 'R', .name = "raw",       .has_arg = no_argument }, */
3471         { .val = 'S',   .name = "stripe-size",  .has_arg = required_argument },
3472         { .val = 'S',   .name = "stripe_size",  .has_arg = required_argument },
3473 /* find { .val = 't',   .name = "type",         .has_arg = required_argument }*/
3474 /* dirstripe { .val = 'T', .name = "mdt-count", .has_arg = required_argument }*/
3475 /* find { .val = 'u',   .name = "uid",          .has_arg = required_argument }*/
3476 /* find { .val = 'U',   .name = "user",         .has_arg = required_argument }*/
3477         /* --verbose is only valid in migrate mode */
3478         { .val = 'v',   .name = "verbose",      .has_arg = no_argument},
3479         { .val = 'x',   .name = "xattr",        .has_arg = required_argument },
3480 /* dirstripe { .val = 'X',.name = "max-inherit",.has_arg = required_argument }*/
3481         { .val = 'y',   .name = "yaml",         .has_arg = required_argument },
3482         { .val = 'z',   .name = "ext-size",     .has_arg = required_argument},
3483         { .val = 'z',   .name = "extension-size", .has_arg = required_argument},
3484         { .name = NULL } };
3485
3486         setstripe_args_init(&lsa);
3487
3488         migrate_mode = (opc == SO_MIGRATE);
3489         mirror_mode = (opc == SO_MIRROR_CREATE || opc == SO_MIRROR_EXTEND);
3490         setstripe_mode = (opc == SO_SETSTRIPE);
3491         if (opc == SO_MIRROR_DELETE) {
3492                 delete = 1;
3493                 mirror_flags = MF_DESTROY;
3494         }
3495
3496         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
3497         progname = cmd;
3498         while ((c = getopt_long(argc, argv,
3499                                 "bc:C:dDE:f:hH:i:I:m:N::no:p:L:s:S:vx:y:z:",
3500                                 long_opts, NULL)) >= 0) {
3501                 size_units = 1;
3502                 switch (c) {
3503                 case 0:
3504                         /* Long options. */
3505                         break;
3506                 case LFS_COMP_ADD_OPT:
3507                         comp_add = 1;
3508                         break;
3509                 case LFS_COMP_DEL_OPT:
3510                         comp_del = 1;
3511                         break;
3512                 case LFS_COMP_FLAGS_OPT:
3513                         result = comp_str2flags(optarg, &lsa.lsa_comp_flags,
3514                                                 &lsa.lsa_comp_neg_flags);
3515                         if (result != 0)
3516                                 goto usage_error;
3517                         if (mirror_mode && lsa.lsa_comp_neg_flags) {
3518                                 fprintf(stderr,
3519                                         "%s: inverted flags are not supported\n",
3520                                         progname);
3521                                 goto usage_error;
3522                         }
3523                         break;
3524                 case LFS_COMP_SET_OPT:
3525                         comp_set = 1;
3526                         break;
3527                 case LFS_COMP_NO_VERIFY_OPT:
3528                         mirror_flags |= MF_NO_VERIFY;
3529                         break;
3530                 case LFS_MIRROR_ID_OPT: {
3531                         unsigned long int id;
3532
3533                         errno = 0;
3534                         id = strtoul(optarg, &end, 0);
3535                         if (errno != 0 || *end != '\0' || id == 0 ||
3536                             id > UINT16_MAX) {
3537                                 fprintf(stderr,
3538                                         "%s %s: invalid mirror ID '%s'\n",
3539                                         progname, argv[0], optarg);
3540                                 goto usage_error;
3541                         }
3542
3543                         mirror_id = (__u16)id;
3544                         break;
3545                 }
3546                 case LFS_LAYOUT_FLAGS_OPT: {
3547                         uint32_t neg_flags;
3548
3549                         /* check for numeric flags (foreign and mirror cases) */
3550                         if (setstripe_mode && !mirror_mode && !last_mirror) {
3551                                 errno = 0;
3552                                 flags = strtoul(optarg, &end, 16);
3553                                 if (errno != 0 || *end != '\0' ||
3554                                     flags >= UINT32_MAX) {
3555                                         fprintf(stderr,
3556                                                 "%s %s: invalid hex flags '%s'\n",
3557                                                 progname, argv[0], optarg);
3558                                         return CMD_HELP;
3559                                 }
3560                                 if (!foreign_mode) {
3561                                         fprintf(stderr,
3562                                                 "%s %s: hex flags must be specified with --foreign option\n",
3563                                                 progname, argv[0]);
3564                                         return CMD_HELP;
3565                                 }
3566                                 break;
3567                         }
3568
3569                         if (!mirror_mode || !last_mirror) {
3570                                 fprintf(stderr,
3571                                         "error: %s: --flags must be specified with --mirror-count|-N option\n",
3572                                         progname);
3573                                 goto usage_error;
3574                         }
3575
3576                         result = comp_str2flags(optarg, &last_mirror->m_flags,
3577                                                 &neg_flags);
3578                         if (result != 0)
3579                                 goto usage_error;
3580
3581                         if (neg_flags) {
3582                                 fprintf(stderr,
3583                                         "%s: inverted flags are not supported\n",
3584                                         progname);
3585                                 result = -EINVAL;
3586                                 goto usage_error;
3587                         }
3588                         if (last_mirror->m_flags & ~LCME_USER_MIRROR_FLAGS) {
3589                                 fprintf(stderr,
3590                                         "%s: unsupported mirror flags: %s\n",
3591                                         progname, optarg);
3592                                 result = -EINVAL;
3593                                 goto error;
3594                         }
3595                         break;
3596                 }
3597                 case LFS_LAYOUT_FOREIGN_OPT:
3598                         if (optarg) {
3599                                 /* check pure numeric */
3600                                 type = strtoul(optarg, &end, 0);
3601                                 if (*end) {
3602                                         /* check name */
3603                                         type = check_foreign_type_name(optarg);
3604                                         if (type == LU_FOREIGN_TYPE_UNKNOWN) {
3605                                                 fprintf(stderr,
3606                                                         "%s %s: unrecognized foreign type '%s'\n",
3607                                                         progname, argv[0],
3608                                                         optarg);
3609                                                 return CMD_HELP;
3610                                         }
3611                                 } else if (type >= UINT32_MAX) {
3612                                         fprintf(stderr,
3613                                                 "%s %s: invalid foreign type '%s'\n",
3614                                                 progname, argv[0], optarg);
3615                                         return CMD_HELP;
3616                                 }
3617                         }
3618                         foreign_mode = true;
3619                         break;
3620                 case LFS_MODE_OPT:
3621                         mode_opt = optarg;
3622                         if (mode_opt) {
3623                                 mode = strtoul(mode_opt, &end, 8);
3624                                 if (*end != '\0') {
3625                                         fprintf(stderr,
3626                                                 "%s %s: bad mode '%s'\n",
3627                                                 progname, argv[0], mode_opt);
3628                                         return CMD_HELP;
3629                                 }
3630                                 previous_umask = umask(0);
3631                         }
3632                         break;
3633                 case LFS_LAYOUT_COPY:
3634                         from_copy = true;
3635                         template = optarg;
3636                         break;
3637                 case 'b':
3638                         if (!migrate_mode) {
3639                                 fprintf(stderr,
3640                                         "%s %s: -b|--block valid only for migrate command\n",
3641                                         progname, argv[0]);
3642                                 goto usage_error;
3643                         }
3644                         migration_block = true;
3645                         break;
3646                 case 'C':
3647                         if (lsa.lsa_pattern == LLAPI_LAYOUT_MDT) {
3648                                 fprintf(stderr,
3649                                         "%s %s: -C|--overstripe-count incompatible with DoM layout\n",
3650                                         progname, argv[0]);
3651                                 goto usage_error;
3652                         }
3653                         lsa.lsa_pattern = LLAPI_LAYOUT_OVERSTRIPING;
3654                         /* fall through */
3655                 case 'c':
3656                         errno = 0;
3657                         lsa.lsa_stripe_count = strtoul(optarg, &end, 0);
3658                         if (errno != 0 || *end != '\0'||
3659                             lsa.lsa_stripe_count < -1 ||
3660                             lsa.lsa_stripe_count > LOV_MAX_STRIPE_COUNT) {
3661                                 fprintf(stderr,
3662                                         "%s %s: invalid stripe count '%s'\n",
3663                                         progname, argv[0], optarg);
3664                                 goto usage_error;
3665                         }
3666
3667                         if (lsa.lsa_stripe_count == -1)
3668                                 lsa.lsa_stripe_count = LLAPI_LAYOUT_WIDE;
3669                         break;
3670                 case 'd':
3671                         if (migrate_mode) {
3672                                 migrate_mdt_param.fp_max_depth = 1;
3673                         } else {
3674                                 /* delete the default striping pattern */
3675                                 delete = 1;
3676                                 if (opc == SO_MIRROR_SPLIT) {
3677                                         if (has_m_file) {
3678                                                 fprintf(stderr,
3679                                                       "%s %s: -d cannot used with -f\n",
3680                                                         progname, argv[0]);
3681                                                 goto usage_error;
3682                                         }
3683                                         mirror_flags |= MF_DESTROY;
3684                                 }
3685                         }
3686                         break;
3687                 case 'D':
3688                         if (!migrate_mode) {
3689                                 fprintf(stderr,
3690                                         "%s %s: -D|--non-direct is valid only for migrate command\n",
3691                                         progname, argv[0]);
3692                                 goto usage_error;
3693                         }
3694                         migration_flags |= LLAPI_MIGRATION_NONDIRECT;
3695                         break;
3696                 case 'E':
3697                         if (lsa.lsa_comp_end != 0) {
3698                                 result = comp_args_to_layout(lpp, &lsa, true);
3699                                 if (result) {
3700                                         fprintf(stderr, "%s: invalid layout\n",
3701                                                 progname);
3702                                         goto usage_error;
3703                                 }
3704
3705                                 setstripe_args_init_inherit(&lsa);
3706                         }
3707
3708                         if (arg_is_eof(optarg)) {
3709                                 lsa.lsa_comp_end = LUSTRE_EOF;
3710                         } else {
3711                                 result = llapi_parse_size(optarg,
3712                                                           &lsa.lsa_comp_end,
3713                                                           &size_units, 0);
3714                                 /* assume units of KB if too small */
3715                                 if (lsa.lsa_comp_end < 4096)
3716                                         lsa.lsa_comp_end *= 1024;
3717                                 if (result ||
3718                                     lsa.lsa_comp_end & (LOV_MIN_STRIPE_SIZE - 1)) {
3719                                         fprintf(stderr,
3720                                                 "%s %s: invalid component end '%s'\n",
3721                                                 progname, argv[0], optarg);
3722                                         goto usage_error;
3723                                 }
3724                         }
3725                         break;
3726                 case 'H':
3727                         if (!migrate_mode) {
3728                                 fprintf(stderr,
3729                                         "--mdt-hash is valid only for migrate command\n");
3730                                 return CMD_HELP;
3731                         }
3732
3733                         lsa.lsa_pattern = check_hashtype(optarg);
3734                         if (lsa.lsa_pattern == 0) {
3735                                 fprintf(stderr,
3736                                         "%s %s: bad stripe hash type '%s'\n",
3737                                         progname, argv[0], optarg);
3738                                 return CMD_HELP;
3739                         }
3740                         break;
3741                 case 'i':
3742                         errno = 0;
3743                         lsa.lsa_stripe_off = strtol(optarg, &end, 0);
3744                         if (errno != 0 || *end != '\0' ||
3745                             lsa.lsa_stripe_off < -1 ||
3746                             lsa.lsa_stripe_off > LOV_V1_INSANE_STRIPE_COUNT) {
3747                                 fprintf(stderr,
3748                                         "%s %s: invalid stripe offset '%s'\n",
3749                                         progname, argv[0], optarg);
3750                                 goto usage_error;
3751                         }
3752                         if (lsa.lsa_stripe_off == -1)
3753                                 lsa.lsa_stripe_off = LLAPI_LAYOUT_DEFAULT;
3754                         break;
3755                 case 'I':
3756                         comp_id = strtoul(optarg, &end, 0);
3757                         if (*end != '\0' || comp_id == 0 ||
3758                             comp_id > LCME_ID_MAX) {
3759                                 fprintf(stderr,
3760                                         "%s %s: invalid component ID '%s'\n",
3761                                         progname, argv[0], optarg);
3762                                 goto usage_error;
3763                         }
3764                         break;
3765                 case 'f':
3766                         if (opc != SO_MIRROR_EXTEND && opc != SO_MIRROR_SPLIT) {
3767                                 fprintf(stderr,
3768                                         "error: %s: invalid option: %s\n",
3769                                         progname, argv[optopt + 1]);
3770                                 goto usage_error;
3771                         }
3772                         if (opc == SO_MIRROR_EXTEND) {
3773                                 if (!last_mirror) {
3774                                         fprintf(stderr,
3775                                 "error: %s: '-N' must exist in front of '%s'\n",
3776                                                 progname, argv[optopt + 1]);
3777                                         goto usage_error;
3778                                 }
3779                                 last_mirror->m_file = optarg;
3780                                 last_mirror->m_count = 1;
3781                         } else {
3782                                 /* mirror split */
3783                                 if (!mirror_list)
3784                                         mirror_list = lfs_mirror_alloc();
3785                                 mirror_list->m_file = optarg;
3786                         }
3787                         has_m_file = true;
3788                         break;
3789                 case 'L':
3790                         if (strcmp(argv[optind - 1], "mdt") == 0) {
3791                                 /* Can be only the first component */
3792                                 if (layout) {
3793                                         result = -EINVAL;
3794                                         fprintf(stderr,
3795                                                 "error: 'mdt' layout can be only the first one\n");
3796                                         goto error;
3797                                 }
3798                                 if (lsa.lsa_comp_end > (1ULL << 30)) { /* 1Gb */
3799                                         result = -EFBIG;
3800                                         fprintf(stderr,
3801                                                 "error: 'mdt' layout size is too big\n");
3802                                         goto error;
3803                                 }
3804                                 lsa.lsa_pattern = LLAPI_LAYOUT_MDT;
3805                                 lsa.lsa_stripe_size = LLAPI_LAYOUT_DEFAULT;
3806                         } else if (strcmp(argv[optind - 1], "raid0") != 0) {
3807                                 result = -EINVAL;
3808                                 fprintf(stderr,
3809                                         "error: layout '%s' is unknown, supported layouts are: 'mdt', 'raid0'\n",
3810                                         argv[optind]);
3811                                 goto error;
3812                         }
3813                         break;
3814                 case 'm':
3815                         if (!migrate_mode) {
3816                                 fprintf(stderr,
3817                                         "%s %s: -m|--mdt-index is valid only for migrate command\n",
3818                                         progname, argv[0]);
3819                                 goto usage_error;
3820                         }
3821                         migrate_mdt_mode = true;
3822                         lsa.lsa_nr_tgts = parse_targets(tgts,
3823                                                 sizeof(tgts) / sizeof(__u32),
3824                                                 lsa.lsa_nr_tgts, optarg, NULL);
3825                         if (lsa.lsa_nr_tgts < 0) {
3826                                 fprintf(stderr,
3827                                         "%s: invalid MDT target(s) '%s'\n",
3828                                         progname, optarg);
3829                                 goto usage_error;
3830                         }
3831
3832                         lsa.lsa_tgts = tgts;
3833                         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
3834                                 lsa.lsa_stripe_off = tgts[0];
3835                         break;
3836                 case 'n':
3837                         if (!migrate_mode) {
3838                                 fprintf(stderr,
3839                                         "%s %s: -n|--non-block valid only for migrate command\n",
3840                                         progname, argv[0]);
3841                                 goto usage_error;
3842                         }
3843                         migration_flags |= LLAPI_MIGRATION_NONBLOCK;
3844                         break;
3845                 case 'N':
3846                         if (opc == SO_SETSTRIPE) {
3847                                 opc = SO_MIRROR_CREATE;
3848                                 mirror_mode = true;
3849                         }
3850                         mirror_count = 1;
3851                         if (optarg) {
3852                                 errno = 0;
3853                                 mirror_count = strtoul(optarg, &end, 0);
3854                                 if (errno != 0 || *end != '\0' ||
3855                                     mirror_count == 0 ||
3856                                     mirror_count > LUSTRE_MIRROR_COUNT_MAX) {
3857                                         fprintf(stderr,
3858                                                 "error: %s: bad mirror count: %s\n",
3859                                                 progname, optarg);
3860                                         result = -EINVAL;
3861                                         goto error;
3862                                 }
3863                         }
3864
3865                         new_mirror = lfs_mirror_alloc();
3866                         new_mirror->m_count = mirror_count;
3867
3868                         if (!mirror_list)
3869                                 mirror_list = new_mirror;
3870
3871                         if (last_mirror) {
3872                                 /* wrap up last mirror */
3873                                 if (!setstripe_args_specified(&lsa))
3874                                         last_mirror->m_inherit = true;
3875                                 if (lsa.lsa_comp_end == 0)
3876                                         lsa.lsa_comp_end = LUSTRE_EOF;
3877
3878                                 result = comp_args_to_layout(lpp, &lsa, true);
3879                                 if (result) {
3880                                         lfs_mirror_free(new_mirror);
3881                                         goto error;
3882                                 }
3883
3884                                 setstripe_args_init_inherit(&lsa);
3885
3886                                 last_mirror->m_next = new_mirror;
3887                         }
3888
3889                         last_mirror = new_mirror;
3890                         lpp = &last_mirror->m_layout;
3891                         break;
3892                 case 'o':
3893 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
3894                         if (strcmp(argv[optind - 1], "--ost-list") == 0)
3895                                 fprintf(stderr,
3896                                         "warning: '--ost-list' is deprecated, use '--ost' instead\n");
3897 #endif
3898                         if (lsa.lsa_pattern == LLAPI_LAYOUT_MDT) {
3899                                 fprintf(stderr,
3900                                         "%s %s: -o|--ost incompatible with DoM layout\n",
3901                                         progname, argv[0]);
3902                                 goto usage_error;
3903                         }
3904                         /*
3905                          * -o allows overstriping, and must note it because
3906                          * parse_targets is shared with MDT striping, which
3907                          * does not allow duplicates
3908                          */
3909                         lsa.lsa_pattern = LLAPI_LAYOUT_OVERSTRIPING;
3910                         lsa.lsa_nr_tgts = parse_targets(tgts,
3911                                                 sizeof(tgts) / sizeof(__u32),
3912                                                 lsa.lsa_nr_tgts, optarg,
3913                                                 &lsa.lsa_pattern);
3914                         if (lsa.lsa_nr_tgts < 0) {
3915                                 fprintf(stderr,
3916                                         "%s %s: invalid OST target(s) '%s'\n",
3917                                         progname, argv[0], optarg);
3918                                 goto usage_error;
3919                         }
3920
3921                         lsa.lsa_tgts = tgts;
3922                         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
3923                                 lsa.lsa_stripe_off = tgts[0];
3924                         break;
3925                 case 'p':
3926                         if (!optarg)
3927                                 goto usage_error;
3928                         lsa.lsa_pool_name = optarg;
3929
3930                         if (strlen(lsa.lsa_pool_name) == 0 ||
3931                             strncmp(lsa.lsa_pool_name, "none",
3932                                     LOV_MAXPOOLNAME) == 0)
3933                                 lsa.lsa_pool_name = NULL;
3934                         break;
3935                 case 'S':
3936                         result = llapi_parse_size(optarg, &lsa.lsa_stripe_size,
3937                                                   &size_units, 0);
3938                         /* assume units of KB if too small to be valid */
3939                         if (lsa.lsa_stripe_size < 4096)
3940                                 lsa.lsa_stripe_size *= 1024;
3941                         if (result ||
3942                             lsa.lsa_stripe_size & (LOV_MIN_STRIPE_SIZE - 1)) {
3943                                 fprintf(stderr,
3944                                         "%s %s: invalid stripe size '%s'\n",
3945                                         progname, argv[0], optarg);
3946                                 goto usage_error;
3947                         }
3948                         break;
3949                 case 'v':
3950                         if (!migrate_mode) {
3951                                 fprintf(stderr,
3952                                         "%s %s: -v|--verbose valid only for migrate command\n",
3953                                         progname, argv[0]);
3954                                 goto usage_error;
3955                         }
3956                         migrate_mdt_param.fp_verbose = VERBOSE_DETAIL;
3957                         migration_flags = LLAPI_MIGRATION_VERBOSE;
3958                         break;
3959                 case 'x':
3960                         xattr = optarg;
3961                         break;
3962                 case 'y':
3963                         from_yaml = true;
3964                         template = optarg;
3965                         break;
3966                 case 'z':
3967                         result = llapi_parse_size(optarg,
3968                                                   &lsa.lsa_extension_size,
3969                                                   &size_units, 0);
3970                         if (result) {
3971                                 fprintf(stderr,
3972                                         "%s %s: invalid extension size '%s'\n",
3973                                         progname, argv[0], optarg);
3974                                 goto usage_error;
3975                         }
3976
3977                         lsa.lsa_extension_comp = true;
3978                         break;
3979                 default:
3980                         fprintf(stderr, "%s: unrecognized option '%s'\n",
3981                                 progname, argv[optind - 1]);
3982                 case 'h':
3983                         goto usage_error;
3984                 }
3985         }
3986
3987         fname = argv[optind];
3988
3989         if (optind == argc) {
3990                 fprintf(stderr, "%s %s: FILE must be specified\n",
3991                         progname, argv[0]);
3992                 goto usage_error;
3993         }
3994
3995         /* lfs migrate $filename should keep the file's layout by default */
3996         if (migrate_mode && !layout && !from_yaml &&
3997             !setstripe_args_specified(&lsa) && !lsa.lsa_pool_name)
3998                 from_copy = true;
3999
4000         if (xattr && !foreign_mode) {
4001                 /*
4002                  * only print a warning as this is harmless and will be ignored
4003                  */
4004                 fprintf(stderr,
4005                         "%s %s: xattr has been specified for non-foreign layout\n",
4006                         progname, argv[0]);
4007         } else if (foreign_mode && !xattr) {
4008                 fprintf(stderr,
4009                         "%s %s: xattr must be provided in foreign mode\n",
4010                         progname, argv[0]);
4011                 goto usage_error;
4012         }
4013
4014         if (foreign_mode && (!setstripe_mode || comp_add | comp_del ||
4015             comp_set || comp_id || delete || from_copy ||
4016             setstripe_args_specified(&lsa) || lsa.lsa_nr_tgts ||
4017             lsa.lsa_tgts)) {
4018                 fprintf(stderr,
4019                         "%s %s: only --xattr/--flags/--mode options are valid with --foreign\n",
4020                         progname, argv[0]);
4021                 return CMD_HELP;
4022         }
4023
4024         if (mirror_mode && mirror_count == 0) {
4025                 fprintf(stderr,
4026                         "error: %s: --mirror-count|-N option is required\n",
4027                         progname);
4028                 result = -EINVAL;
4029                 goto error;
4030         }
4031
4032         if (mirror_mode) {
4033                 if (!setstripe_args_specified(&lsa))
4034                         last_mirror->m_inherit = true;
4035                 if (lsa.lsa_comp_end == 0)
4036                         lsa.lsa_comp_end = LUSTRE_EOF;
4037         }
4038
4039         if (lsa.lsa_comp_end != 0) {
4040                 result = comp_args_to_layout(lpp, &lsa, true);
4041                 if (result) {
4042                         fprintf(stderr, "error: %s: invalid layout\n",
4043                                 progname);
4044                         result = -EINVAL;
4045                         goto error;
4046                 }
4047         }
4048
4049         if (mirror_flags & MF_NO_VERIFY) {
4050                 if (opc != SO_MIRROR_EXTEND) {
4051                         fprintf(stderr,
4052                                 "error: %s: --no-verify is valid only for lfs mirror extend command\n",
4053                                 progname);
4054                         result = -EINVAL;
4055                         goto error;
4056                 } else if (!has_m_file) {
4057                         fprintf(stderr,
4058                                 "error: %s: --no-verify must be specified with -f <victim_file> option\n",
4059                                 progname);
4060                         result = -EINVAL;
4061                         goto error;
4062                 }
4063         }
4064
4065         if (comp_set && !comp_id && !lsa.lsa_pool_name) {
4066                 fprintf(stderr,
4067                         "%s %s: --component-set doesn't have component-id set\n",
4068                         progname, argv[0]);
4069                 goto usage_error;
4070         }
4071
4072         if ((delete + comp_set + comp_del + comp_add) > 1) {
4073                 fprintf(stderr,
4074                         "%s %s: options --component-set, --component-del, --component-add and -d are mutually exclusive\n",
4075                         progname, argv[0]);
4076                 goto usage_error;
4077         }
4078
4079         if (delete && (setstripe_args_specified(&lsa) || comp_id != 0 ||
4080                        lsa.lsa_comp_flags != 0 || layout != NULL)) {
4081                 fprintf(stderr,
4082                         "%s %s: option -d is mutually exclusive with -s, -c, -o, -p, -I, -F and -E options\n",
4083                         progname, argv[0]);
4084                 goto usage_error;
4085         }
4086
4087         if ((comp_set || comp_del) &&
4088             (setstripe_args_specified(&lsa) || layout != NULL)) {
4089                 fprintf(stderr,
4090                         "%s %s: options --component-del and --component-set are mutually exclusive when used with -c, -E, -o, -p, or -s\n",
4091                         progname, argv[0]);
4092                 goto usage_error;
4093         }
4094
4095         if (comp_del && comp_id != 0 && lsa.lsa_comp_flags != 0) {
4096                 fprintf(stderr,
4097                         "%s %s: options -I and -F are mutually exclusive when used with --component-del\n",
4098                         progname, argv[0]);
4099                 goto usage_error;
4100         }
4101
4102         if (comp_add || comp_del) {
4103                 struct stat st;
4104
4105                 result = lstat(fname, &st);
4106                 if (result == 0 && S_ISDIR(st.st_mode)) {
4107                         fprintf(stderr,
4108                                 "%s setstripe: cannot use --component-add or --component-del for directory\n",
4109                                 progname);
4110                         goto usage_error;
4111                 }
4112
4113                 if (mirror_mode) {
4114                         fprintf(stderr,
4115                                 "error: %s: can't use --component-add or --component-del for mirror operation\n",
4116                                 progname);
4117                         goto usage_error;
4118                 }
4119         }
4120
4121         if (comp_add) {
4122                 if (!layout) {
4123                         fprintf(stderr,
4124                                 "%s %s: option -E must be specified with --component-add\n",
4125                                 progname, argv[0]);
4126                         goto usage_error;
4127                 }
4128         }
4129
4130         if (from_yaml && from_copy) {
4131                 fprintf(stderr,
4132                         "%s: can't specify --yaml and --copy together\n",
4133                         progname);
4134                 goto error;
4135         }
4136
4137         if ((from_yaml || from_copy) &&
4138             (setstripe_args_specified(&lsa) || layout != NULL)) {
4139                 fprintf(stderr,
4140                         "error: %s: can't specify --yaml or --copy with -c, -S, -i, -o, -p or -E options.\n",
4141                         argv[0]);
4142                 goto error;
4143         }
4144
4145         if ((migration_flags & LLAPI_MIGRATION_NONBLOCK) && migration_block) {
4146                 fprintf(stderr,
4147                         "%s %s: options --non-block and --block are mutually exclusive\n",
4148                         progname, argv[0]);
4149                 goto usage_error;
4150         }
4151
4152         if (!comp_del && !comp_set && opc != SO_MIRROR_SPLIT &&
4153             opc != SO_MIRROR_DELETE && comp_id != 0) {
4154                 fprintf(stderr,
4155                         "%s: option -I can only be used with --component-del or --component-set or lfs mirror split\n",
4156                         progname);
4157                 goto usage_error;
4158         }
4159
4160         if (migrate_mdt_mode) {
4161                 struct lmv_user_md *lmu;
4162
4163                 /* initialize migrate mdt parameters */
4164                 lmu = calloc(1, lmv_user_md_size(lsa.lsa_nr_tgts,
4165                                                  LMV_USER_MAGIC_SPECIFIC));
4166                 if (!lmu) {
4167                         fprintf(stderr,
4168                                 "%s %s: cannot allocate memory for lmv_user_md: %s\n",
4169                                 progname, argv[0], strerror(ENOMEM));
4170                         result = -ENOMEM;
4171                         goto error;
4172                 }
4173                 if (lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT)
4174                         lmu->lum_stripe_count = lsa.lsa_stripe_count;
4175                 if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT) {
4176                         fprintf(stderr,
4177                                 "%s %s: migrate should specify MDT index\n",
4178                                 progname, argv[0]);
4179                         free(lmu);
4180                         goto usage_error;
4181                 }
4182                 lmu->lum_stripe_offset = lsa.lsa_stripe_off;
4183                 if (lsa.lsa_pattern != LLAPI_LAYOUT_RAID0)
4184                         lmu->lum_hash_type = lsa.lsa_pattern;
4185                 else
4186                         lmu->lum_hash_type = LMV_HASH_TYPE_UNKNOWN;
4187                 if (lsa.lsa_pool_name) {
4188                         strncpy(lmu->lum_pool_name, lsa.lsa_pool_name,
4189                                 sizeof(lmu->lum_pool_name) - 1);
4190                         lmu->lum_pool_name[sizeof(lmu->lum_pool_name) - 1] = 0;
4191                 }
4192                 if (lsa.lsa_nr_tgts > 1) {
4193                         int i;
4194
4195                         if (lsa.lsa_stripe_count > 0 &&
4196                             lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT &&
4197                             lsa.lsa_stripe_count != lsa.lsa_nr_tgts) {
4198                                 fprintf(stderr,
4199                                         "error: %s: stripe count %lld doesn't match the number of MDTs: %d\n",
4200                                         progname, lsa.lsa_stripe_count,
4201                                         lsa.lsa_nr_tgts);
4202                                 free(lmu);
4203                                 goto usage_error;
4204                         }
4205
4206                         lmu->lum_magic = LMV_USER_MAGIC_SPECIFIC;
4207                         lmu->lum_stripe_count = lsa.lsa_nr_tgts;
4208                         for (i = 0; i < lsa.lsa_nr_tgts; i++)
4209                                 lmu->lum_objects[i].lum_mds = lsa.lsa_tgts[i];
4210                 } else {
4211                         lmu->lum_magic = LMV_USER_MAGIC;
4212                 }
4213
4214                 migrate_mdt_param.fp_lmv_md = lmu;
4215                 migrate_mdt_param.fp_migrate = 1;
4216         } else if (!layout) {
4217                 if (lsa_args_stripe_count_check(&lsa))
4218                         goto usage_error;
4219
4220                 /* initialize stripe parameters */
4221                 param = calloc(1, offsetof(typeof(*param),
4222                                lsp_osts[lsa.lsa_nr_tgts]));
4223                 if (!param) {
4224                         fprintf(stderr,
4225                                 "%s %s: cannot allocate memory for parameters: %s\n",
4226                                 progname, argv[0], strerror(ENOMEM));
4227                         result = -ENOMEM;
4228                         goto error;
4229                 }
4230
4231                 if (lsa.lsa_stripe_size != LLAPI_LAYOUT_DEFAULT)
4232                         param->lsp_stripe_size = lsa.lsa_stripe_size;
4233                 if (lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT) {
4234                         if (lsa.lsa_stripe_count == LLAPI_LAYOUT_WIDE)
4235                                 param->lsp_stripe_count = -1;
4236                         else
4237                                 param->lsp_stripe_count = lsa.lsa_stripe_count;
4238                 }
4239                 if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
4240                         param->lsp_stripe_offset = -1;
4241                 else
4242                         param->lsp_stripe_offset = lsa.lsa_stripe_off;
4243                 param->lsp_stripe_pattern =
4244                                 llapi_pattern_to_lov(lsa.lsa_pattern);
4245                 if (param->lsp_stripe_pattern == EINVAL) {
4246                         fprintf(stderr, "error: %s: invalid stripe pattern\n",
4247                                 argv[0]);
4248                         free(param);
4249                         goto usage_error;
4250                 }
4251                 param->lsp_pool = lsa.lsa_pool_name;
4252                 param->lsp_is_specific = false;
4253
4254                 if (lsa.lsa_nr_tgts > 0) {
4255                         param->lsp_is_specific = true;
4256                         param->lsp_stripe_count = lsa.lsa_nr_tgts;
4257                         memcpy(param->lsp_osts, tgts,
4258                                sizeof(*tgts) * lsa.lsa_nr_tgts);
4259                 }
4260         }
4261
4262         if (from_yaml) {
4263                 /* generate a layout from a YAML template */
4264                 result = lfs_comp_create_from_yaml(template, &layout,
4265                                                    &lsa, tgts);
4266                 if (result) {
4267                         fprintf(stderr,
4268                                 "error: %s: can't create composite layout from template file %s\n",
4269                                 argv[0], template);
4270                         goto error;
4271                 }
4272         }
4273
4274         if (layout != NULL || mirror_list != NULL) {
4275                 if (mirror_list)
4276                         result = mirror_adjust_first_extents(mirror_list);
4277                 else
4278                         result = layout_adjust_first_extent(fname, layout,
4279                                                             comp_add);
4280                 if (result == -ENODATA)
4281                         comp_add = 0;
4282                 else if (result != 0) {
4283                         fprintf(stderr, "error: %s: invalid layout\n",
4284                                 progname);
4285                         goto error;
4286                 }
4287         }
4288
4289         for (fname = argv[optind]; fname != NULL; fname = argv[++optind]) {
4290                 if (from_copy) {
4291                         layout = llapi_layout_get_by_path(template ?: fname, 0);
4292                         if (!layout) {
4293                                 fprintf(stderr,
4294                                         "%s: can't create composite layout from file %s: %s\n",
4295                                         progname, template ?: fname,
4296                                         strerror(errno));
4297                                 result = -errno;
4298                                 goto error;
4299                         }
4300                 }
4301
4302                 if (migrate_mdt_mode) {
4303                         result = llapi_migrate_mdt(fname, &migrate_mdt_param);
4304                 } else if (migrate_mode) {
4305                         result = lfs_migrate(fname, migration_flags, param,
4306                                              layout);
4307                 } else if (comp_set != 0) {
4308                         result = lfs_component_set(fname, comp_id,
4309                                                    lsa.lsa_pool_name,
4310                                                    lsa.lsa_comp_flags,
4311                                                    lsa.lsa_comp_neg_flags);
4312                 } else if (comp_del != 0) {
4313                         result = lfs_component_del(fname, comp_id,
4314                                                    lsa.lsa_comp_flags,
4315                                                    lsa.lsa_comp_neg_flags);
4316                 } else if (comp_add != 0) {
4317                         result = lfs_component_add(fname, layout);
4318                 } else if (opc == SO_MIRROR_CREATE) {
4319                         result = mirror_create(fname, mirror_list);
4320                 } else if (opc == SO_MIRROR_EXTEND) {
4321                         result = mirror_extend(fname, mirror_list,
4322                                                mirror_flags);
4323                 } else if (opc == SO_MIRROR_SPLIT || opc == SO_MIRROR_DELETE) {
4324                         if (!mirror_id && !comp_id && !lsa.lsa_pool_name) {
4325                                 fprintf(stderr,
4326                                         "%s: no mirror id, component id, or pool name specified to delete from '%s'\n",
4327                                         progname, fname);
4328                                 goto usage_error;
4329                         }
4330                         if (lsa.lsa_pool_name)
4331                                 mirror_flags |= MF_COMP_POOL;
4332                         else if (mirror_id != 0)
4333                                 comp_id = mirror_id;
4334                         else
4335                                 mirror_flags |= MF_COMP_ID;
4336                         if (has_m_file && !strcmp(fname, mirror_list->m_file)) {
4337                                 fprintf(stderr,
4338                                         "%s: the file specified by -f cannot be same as the source file '%s'\n",
4339                                         progname, fname);
4340                                 goto usage_error;
4341                         }
4342                         result = mirror_split(fname, comp_id, lsa.lsa_pool_name,
4343                                               mirror_flags,
4344                                               has_m_file ? mirror_list->m_file :
4345                                               NULL);
4346                 } else if (layout) {
4347                         result = lfs_component_create(fname, O_CREAT | O_WRONLY,
4348                                                       mode, layout);
4349                         if (result >= 0) {
4350                                 close(result);
4351                                 result = 0;
4352                         }
4353                 } else if (foreign_mode) {
4354                         result = llapi_file_create_foreign(fname, mode, type,
4355                                                            flags, xattr);
4356                         if (result >= 0) {
4357                                 close(result);
4358                                 result = 0;
4359                         }
4360                 } else {
4361                         result = llapi_file_open_param(fname,
4362                                                        O_CREAT | O_WRONLY,
4363                                                        mode, param);
4364                         if (result >= 0) {
4365                                 close(result);
4366                                 result = 0;
4367                         }
4368                 }
4369                 if (result) {
4370                         /* Save the first error encountered. */
4371                         if (result2 == 0)
4372                                 result2 = result;
4373                         continue;
4374                 }
4375         }
4376
4377         if (mode_opt)
4378                 umask(previous_umask);
4379
4380         free(param);
4381         free(migrate_mdt_param.fp_lmv_md);
4382         llapi_layout_free(layout);
4383         lfs_mirror_list_free(mirror_list);
4384         return result2;
4385 usage_error:
4386         result = CMD_HELP;
4387 error:
4388         llapi_layout_free(layout);
4389         lfs_mirror_list_free(mirror_list);
4390         return result;
4391 }
4392
4393 static int lfs_poollist(int argc, char **argv)
4394 {
4395         if (argc != 2)
4396                 return CMD_HELP;
4397
4398         return llapi_poollist(argv[1]);
4399 }
4400
4401 #define FP_DEFAULT_TIME_MARGIN (24 * 60 * 60)
4402 static time_t set_time(struct find_param *param, time_t *time, time_t *set,
4403                        char *str)
4404 {
4405         long long t = 0;
4406         int sign = 0;
4407         char *endptr = "AD";
4408         char *timebuf;
4409
4410         if (str[0] == '+')
4411                 sign = 1;
4412         else if (str[0] == '-')
4413                 sign = -1;
4414
4415         if (sign)
4416                 str++;
4417
4418         for (timebuf = str; *endptr && *(endptr + 1); timebuf = endptr + 1) {
4419                 long long val = strtoll(timebuf, &endptr, 0);
4420                 int unit = 1;
4421
4422                 switch (*endptr) {
4423                 case  'y':
4424                         unit *= 52; /* 52 weeks + 1 day below */
4425                 case  'w':      /* fallthrough */
4426                         unit *= 7;
4427                         if (param->fp_time_margin == FP_DEFAULT_TIME_MARGIN)
4428                                 param->fp_time_margin *= (1 + unit / 52);
4429                         unit += (*endptr == 'y'); /* +1 day for 365 days/year */
4430                 case '\0': /* days are default unit if none used */
4431                 case  'd':      /* fallthrough */
4432                         unit *= 24;
4433                 case  'h':      /* fallthrough */
4434                         unit *= 60;
4435                 case  'm':      /* fallthrough */
4436                         unit *= 60;
4437                 case  's':      /* fallthrough */
4438                         break;
4439                         /* don't need to multiply by 1 for seconds */
4440                 default:
4441                         fprintf(stderr,
4442                                 "%s find: bad time string '%s': %s\n",
4443                                 progname, timebuf, strerror(EINVAL));
4444                         return LONG_MAX;
4445                 }
4446
4447                 if (param->fp_time_margin == 0 ||
4448                     (*endptr && unit < param->fp_time_margin))
4449                         param->fp_time_margin = unit;
4450
4451                 t += val * unit;
4452         }
4453         if (*time < t) {
4454                 if (sign != 0)
4455                         str--;
4456                 fprintf(stderr, "%s find: bad time '%s': too large\n",
4457                         progname, str);
4458                 return LONG_MAX;
4459         }
4460
4461         *set = *time - t;
4462
4463         return sign;
4464 }
4465
4466 static int str2quotaid(__u32 *id, const char *arg)
4467 {
4468         unsigned long int projid_tmp = 0;
4469         char *endptr = NULL;
4470
4471         projid_tmp = strtoul(arg, &endptr, 10);
4472         if (*endptr != '\0')
4473                 return -EINVAL;
4474         /* UINT32_MAX is not allowed - see projid_valid()/INVALID_PROJID */
4475         if (projid_tmp >= UINT32_MAX)
4476                 return -ERANGE;
4477
4478         *id = projid_tmp;
4479         return 0;
4480 }
4481
4482 static int name2uid(unsigned int *id, const char *name)
4483 {
4484         struct passwd *passwd;
4485
4486         passwd = getpwnam(name);
4487         if (!passwd)
4488                 return -ENOENT;
4489         *id = passwd->pw_uid;
4490
4491         return 0;
4492 }
4493
4494 static int name2gid(unsigned int *id, const char *name)
4495 {
4496         struct group *group;
4497
4498         group = getgrnam(name);
4499         if (!group)
4500                 return -ENOENT;
4501         *id = group->gr_gid;
4502
4503         return 0;
4504 }
4505
4506 static inline int name2projid(unsigned int *id, const char *name)
4507 {
4508         return -ENOTSUP;
4509 }
4510
4511 static int uid2name(char **name, unsigned int id)
4512 {
4513         struct passwd *passwd;
4514
4515         passwd = getpwuid(id);
4516         if (!passwd)
4517                 return -ENOENT;
4518         *name = passwd->pw_name;
4519
4520         return 0;
4521 }
4522
4523 static inline int gid2name(char **name, unsigned int id)
4524 {
4525         struct group *group;
4526
4527         group = getgrgid(id);
4528         if (!group)
4529                 return -ENOENT;
4530         *name = group->gr_name;
4531
4532         return 0;
4533 }
4534
4535 static int name2layout(__u32 *layout, char *name)
4536 {
4537         char *ptr, *layout_name;
4538
4539         *layout = 0;
4540         for (ptr = name; ; ptr = NULL) {
4541                 layout_name = strtok(ptr, ",");
4542                 if (!layout_name)
4543                         break;
4544                 if (strcmp(layout_name, "released") == 0)
4545                         *layout |= LOV_PATTERN_F_RELEASED;
4546                 else if (strcmp(layout_name, "raid0") == 0)
4547                         *layout |= LOV_PATTERN_RAID0;
4548                 else if (strcmp(layout_name, "mdt") == 0)
4549                         *layout |= LOV_PATTERN_MDT;
4550                 else if (strcmp(layout_name, "overstriping") == 0)
4551                         *layout |= LOV_PATTERN_OVERSTRIPING;
4552                 else
4553                         return -1;
4554         }
4555         return 0;
4556 }
4557
4558 static int parse_symbolic(const char *input, mode_t *outmode, const char **end)
4559 {
4560         int loop;
4561         int user, group, other;
4562         int who, all;
4563         char c, op;
4564         mode_t perm;
4565         mode_t usermask;
4566         mode_t previous_flags;
4567
4568         user = group = other = 0;
4569         all = 0;
4570         loop = 1;
4571         perm = 0;
4572         previous_flags = 0;
4573         *end = input;
4574         usermask = 0;
4575
4576         while (loop) {
4577                 switch (*input) {
4578                 case 'u':
4579                         user = 1;
4580                         break;
4581                 case 'g':
4582                         group = 1;
4583                         break;
4584                 case 'o':
4585                         other = 1;
4586                         break;
4587                 case 'a':
4588                         user = group = other = 1;
4589                         all = 1;
4590                         break;
4591                 default:
4592                         loop = 0;
4593                 }
4594
4595                 if (loop)
4596                         input++;
4597         }
4598
4599         who = user || group || other;
4600         if (!who) {
4601                 /* get the umask */
4602                 usermask = umask(0022);
4603                 umask(usermask);
4604                 usermask &= 07777;
4605         }
4606
4607         if (*input == '-' || *input == '+' || *input == '=')
4608                 op = *input++;
4609         else
4610                 /* operation is required */
4611                 return -1;
4612
4613         /* get the flags in *outmode */
4614         switch (*input) {
4615         case 'u':
4616                 previous_flags = (*outmode & 0700);
4617                 perm |= user  ? previous_flags : 0;
4618                 perm |= group ? (previous_flags >> 3) : 0;
4619                 perm |= other ? (previous_flags >> 6) : 0;
4620                 input++;
4621                 goto write_perm;
4622         case 'g':
4623                 previous_flags = (*outmode & 0070);
4624                 perm |= user  ? (previous_flags << 3) : 0;
4625                 perm |= group ? previous_flags : 0;
4626                 perm |= other ? (previous_flags >> 3) : 0;
4627                 input++;
4628                 goto write_perm;
4629         case 'o':
4630                 previous_flags = (*outmode & 0007);
4631                 perm |= user  ? (previous_flags << 6) : 0;
4632                 perm |= group ? (previous_flags << 3) : 0;
4633                 perm |= other ? previous_flags : 0;
4634                 input++;
4635                 goto write_perm;
4636         default:
4637                 break;
4638         }
4639
4640         /* this part is optional,
4641          * if empty perm = 0 and *outmode is not modified
4642          */
4643         loop = 1;
4644         while (loop) {
4645                 c = *input;
4646                 switch (c) {
4647                 case 'r':
4648                         perm |= user  ? 0400 : 0;
4649                         perm |= group ? 0040 : 0;
4650                         perm |= other ? 0004 : 0;
4651                         /* set read permission for uog except for umask's
4652                          * permissions
4653                          */
4654                         perm |= who   ? 0 : (0444 & ~usermask);
4655                         break;
4656                 case 'w':
4657                         perm |= user  ? 0200 : 0;
4658                         perm |= group ? 0020 : 0;
4659                         perm |= other ? 0002 : 0;
4660                         /* set write permission for uog except for umask'
4661                          * permissions
4662                          */
4663                         perm |= who   ? 0 : (0222 & ~usermask);
4664                         break;
4665                 case 'x':
4666                         perm |= user  ? 0100 : 0;
4667                         perm |= group ? 0010 : 0;
4668                         perm |= other ? 0001 : 0;
4669                         /* set execute permission for uog except for umask'
4670                          * permissions
4671                          */
4672                         perm |= who   ? 0 : (0111 & ~usermask);
4673                         break;
4674                 case 'X':
4675                         /*
4676                          * Adds execute permission to 'u', 'g' and/or 'g' if
4677                          * specified and either 'u', 'g' or 'o' already has
4678                          * execute permissions.
4679                          */
4680                         if ((*outmode & 0111) != 0) {
4681                                 perm |= user  ? 0100 : 0;
4682                                 perm |= group ? 0010 : 0;
4683                                 perm |= other ? 0001 : 0;
4684                                 perm |= !who  ? 0111 : 0;
4685                         }
4686                         break;
4687                 case 's':
4688                         /* s is ignored if o is given, but it's not an error */
4689                         if (other && !group && !user)
4690                                 break;
4691                         perm |= user  ? S_ISUID : 0;
4692                         perm |= group ? S_ISGID : 0;
4693                         break;
4694                 case 't':
4695                         /* 't' should be used when 'a' is given
4696                          * or who is empty
4697                          */
4698                         perm |= (!who || all) ? S_ISVTX : 0;
4699                         /* using ugo with t is not an error */
4700                         break;
4701                 default:
4702                         loop = 0;
4703                         break;
4704                 }
4705                 if (loop)
4706                         input++;
4707         }
4708
4709 write_perm:
4710         /* uog flags should be only one character long */
4711         if (previous_flags && (*input != '\0' && *input != ','))
4712                 return -1;
4713
4714         switch (op) {
4715         case '-':
4716                 /* remove the flags from outmode */
4717                 *outmode &= ~perm;
4718                 break;
4719         case '+':
4720                 /* add the flags to outmode */
4721                 *outmode |= perm;
4722                 break;
4723         case '=':
4724                 /* set the flags of outmode to perm */
4725                 if (perm != 0)
4726                         *outmode = perm;
4727                 break;
4728         }
4729
4730         *end = input;
4731         return 0;
4732 }
4733
4734 static int str2mode_t(const char *input, mode_t *outmode)
4735 {
4736         int ret;
4737         const char *iter;
4738
4739         ret = 0;
4740
4741         if (*input >= '0' && *input <= '7') {
4742                 /* parse octal representation */
4743                 char *end;
4744
4745                 iter = input;
4746
4747                 /* look for invalid digits in octal representation */
4748                 while (isdigit(*iter))
4749                         if (*iter++ > '7')
4750                                 return -1;
4751
4752                 errno = 0;
4753                 *outmode = strtoul(input, &end, 8);
4754
4755                 if (errno != 0 || *outmode > 07777) {
4756                         *outmode = 0;
4757                         ret = -1;
4758                 }
4759
4760         } else if (*input == '8' || *input == '9') {
4761                 /* error: invalid octal number */
4762                 ret = -1;
4763         } else {
4764                 /* parse coma seperated list of symbolic representation */
4765                 int rc;
4766                 const char *end;
4767
4768                 *outmode = 0;
4769                 rc = 0;
4770                 end = NULL;
4771
4772                 do {
4773                         rc = parse_symbolic(input, outmode, &end);
4774                         if (rc)
4775                                 return -1;
4776
4777                         input = end+1;
4778                 } while (*end == ',');
4779
4780                 if (*end != '\0')
4781                         ret = -1;
4782         }
4783         return ret;
4784 }
4785
4786 static int lfs_find(int argc, char **argv)
4787 {
4788         int c, rc;
4789         int ret = 0;
4790         time_t t;
4791         struct find_param param = {
4792                 .fp_max_depth = -1,
4793                 .fp_quiet = 1,
4794                 .fp_time_margin = FP_DEFAULT_TIME_MARGIN,
4795         };
4796         struct option long_opts[] = {
4797         { .val = 'A',   .name = "atime",        .has_arg = required_argument },
4798         { .val = 'b',   .name = "blocks",       .has_arg = required_argument },
4799         { .val = 'B',   .name = "btime",        .has_arg = required_argument },
4800         { .val = 'B',   .name = "Btime",        .has_arg = required_argument },
4801         { .val = LFS_COMP_COUNT_OPT,
4802                         .name = "comp-count",   .has_arg = required_argument },
4803         { .val = LFS_COMP_COUNT_OPT,
4804                         .name = "component-count",
4805                                                 .has_arg = required_argument },
4806         { .val = LFS_COMP_FLAGS_OPT,
4807                         .name = "comp-flags",   .has_arg = required_argument },
4808         { .val = LFS_COMP_FLAGS_OPT,
4809                         .name = "component-flags",
4810                                                 .has_arg = required_argument },
4811         { .val = LFS_COMP_START_OPT,
4812                         .name = "comp-start",   .has_arg = required_argument },
4813         { .val = LFS_COMP_START_OPT,
4814                         .name = "component-start",
4815                                                 .has_arg = required_argument },
4816         { .val = LFS_MIRROR_STATE_OPT,
4817                         .name = "mirror-state", .has_arg = required_argument },
4818         { .val = LFS_NEWERXY_OPT,
4819                         .name = "newer",        .has_arg = required_argument},
4820         { .val = LFS_NEWERXY_OPT,
4821                         .name = "neweraa",      .has_arg = required_argument},
4822         { .val = LFS_NEWERXY_OPT,
4823                         .name = "neweram",      .has_arg = required_argument},
4824         { .val = LFS_NEWERXY_OPT,
4825                         .name = "newerac",      .has_arg = required_argument},
4826         { .val = LFS_NEWERXY_OPT,
4827                         .name = "newerab",      .has_arg = required_argument},
4828         { .val = LFS_NEWERXY_OPT,
4829                         .name = "newerma",      .has_arg = required_argument},
4830         { .val = LFS_NEWERXY_OPT,
4831                         .name = "newermm",      .has_arg = required_argument},
4832         { .val = LFS_NEWERXY_OPT,
4833                         .name = "newermc",      .has_arg = required_argument},
4834         { .val = LFS_NEWERXY_OPT,
4835                         .name = "newermb",      .has_arg = required_argument},
4836         { .val = LFS_NEWERXY_OPT,
4837                         .name = "newerca",      .has_arg = required_argument},
4838         { .val = LFS_NEWERXY_OPT,
4839                         .name = "newercm",      .has_arg = required_argument},
4840         { .val = LFS_NEWERXY_OPT,
4841                         .name = "newercc",      .has_arg = required_argument},
4842         { .val = LFS_NEWERXY_OPT,
4843                         .name = "newercb",      .has_arg = required_argument},
4844         { .val = LFS_NEWERXY_OPT,
4845                         .name = "newerba",      .has_arg = required_argument},
4846         { .val = LFS_NEWERXY_OPT,
4847                         .name = "newerbm",      .has_arg = required_argument},
4848         { .val = LFS_NEWERXY_OPT,
4849                         .name = "newerbc",      .has_arg = required_argument},
4850         { .val = LFS_NEWERXY_OPT,
4851                         .name = "newerbb",      .has_arg = required_argument},
4852         { .val = LFS_NEWERXY_OPT,
4853                         .name = "newerBa",      .has_arg = required_argument},
4854         { .val = LFS_NEWERXY_OPT,
4855                         .name = "newerBm",      .has_arg = required_argument},
4856         { .val = LFS_NEWERXY_OPT,
4857                         .name = "newerBc",      .has_arg = required_argument},
4858         { .val = LFS_NEWERXY_OPT,
4859                         .name = "newerBB",      .has_arg = required_argument},
4860         { .val = LFS_NEWERXY_OPT,
4861                         .name = "newerat",      .has_arg = required_argument},
4862         { .val = LFS_NEWERXY_OPT,
4863                         .name = "newermt",      .has_arg = required_argument},
4864         { .val = LFS_NEWERXY_OPT,
4865                         .name = "newerct",      .has_arg = required_argument},
4866         { .val = LFS_NEWERXY_OPT,
4867                         .name = "newerbt",      .has_arg = required_argument},
4868         { .val = LFS_NEWERXY_OPT,
4869                         .name = "newerBt",      .has_arg = required_argument},
4870         { .val = 'c',   .name = "stripe-count", .has_arg = required_argument },
4871         { .val = 'c',   .name = "stripe_count", .has_arg = required_argument },
4872         { .val = 'C',   .name = "ctime",        .has_arg = required_argument },
4873 /* getstripe { .val = 'd', .name = "directory", .has_arg = no_argument }, */
4874         { .val = 'D',   .name = "maxdepth",     .has_arg = required_argument },
4875         { .val = 'E',   .name = "comp-end",     .has_arg = required_argument },
4876         { .val = 'E',   .name = "component-end",
4877                                                 .has_arg = required_argument },
4878 /* find { .val = 'F',   .name = "fid",          .has_arg = no_argument }, */
4879         { .val = LFS_LAYOUT_FOREIGN_OPT,
4880                         .name = "foreign",      .has_arg = optional_argument},
4881         { .val = 'g',   .name = "gid",          .has_arg = required_argument },
4882         { .val = 'G',   .name = "group",        .has_arg = required_argument },
4883         { .val = 'h',   .name = "help",         .has_arg = no_argument },
4884         { .val = 'H',   .name = "mdt-hash",     .has_arg = required_argument },
4885         { .val = 'i',   .name = "stripe-index", .has_arg = required_argument },
4886         { .val = 'i',   .name = "stripe_index", .has_arg = required_argument },
4887 /* getstripe { .val = 'I', .name = "comp-id",   .has_arg = required_argument }*/
4888         { .val = 'l',   .name = "lazy",         .has_arg = no_argument },
4889         { .val = 'L',   .name = "layout",       .has_arg = required_argument },
4890         { .val = 'm',   .name = "mdt",          .has_arg = required_argument },
4891         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument },
4892         { .val = 'm',   .name = "mdt_index",    .has_arg = required_argument },
4893         { .val = 'M',   .name = "mtime",        .has_arg = required_argument },
4894         { .val = 'n',   .name = "name",         .has_arg = required_argument },
4895         { .val = 'N',   .name = "mirror-count", .has_arg = required_argument },
4896 /* find { .val = 'o'    .name = "or", .has_arg = no_argument }, like find(1) */
4897         { .val = 'O',   .name = "obd",          .has_arg = required_argument },
4898         { .val = 'O',   .name = "ost",          .has_arg = required_argument },
4899         /* no short option for pool yet, can be 'p' after 2.18 */
4900         { .val = LFS_POOL_OPT,
4901                         .name = "pool",         .has_arg = required_argument },
4902         { .val = '0',   .name = "print0",       .has_arg = no_argument },
4903         { .val = 'P',   .name = "print",        .has_arg = no_argument },
4904         { .val = LFS_PROJID_OPT,
4905                         .name = "projid",       .has_arg = required_argument },
4906 /* getstripe { .val = 'q', .name = "quiet",     .has_arg = no_argument }, */
4907 /* getstripe { .val = 'r', .name = "recursive", .has_arg = no_argument }, */
4908 /* getstripe { .val = 'R', .name = "raw",       .has_arg = no_argument }, */
4909         { .val = 's',   .name = "size",         .has_arg = required_argument },
4910         { .val = 'S',   .name = "stripe-size",  .has_arg = required_argument },
4911         { .val = 'S',   .name = "stripe_size",  .has_arg = required_argument },
4912         { .val = 't',   .name = "type",         .has_arg = required_argument },
4913         { .val = LFS_FIND_PERM,
4914                         .name = "perm",         .has_arg = required_argument },
4915         { .val = 'T',   .name = "mdt-count",    .has_arg = required_argument },
4916         { .val = 'u',   .name = "uid",          .has_arg = required_argument },
4917         { .val = 'U',   .name = "user",         .has_arg = required_argument },
4918         { .val = 'z',   .name = "extension-size",
4919                                                 .has_arg = required_argument },
4920         { .val = 'z',   .name = "ext-size",     .has_arg = required_argument },
4921 /* getstripe { .val = 'v', .name = "verbose",   .has_arg = no_argument }, */
4922 /* getstripe { .val = 'y', .name = "yaml",      .has_arg = no_argument }, */
4923         { .name = NULL } };
4924         int optidx = 0;
4925         int pathstart = -1;
4926         int pathend = -1;
4927         int pathbad = -1;
4928         int neg_opt = 0;
4929         time_t *xtime;
4930         int *xsign;
4931         int isoption;
4932         char *endptr;
4933
4934         time(&t);
4935
4936         /* when getopt_long_only() hits '!' it returns 1, puts "!" in optarg */
4937         while ((c = getopt_long_only(argc, argv,
4938                 "-0A:b:B:c:C:D:E:g:G:hH:i:L:m:M:n:N:O:Ppqrs:S:t:T:u:U:vz:",
4939                 long_opts, &optidx)) >= 0) {
4940                 xtime = NULL;
4941                 xsign = NULL;
4942                 if (neg_opt)
4943                         --neg_opt;
4944                 /* '!' is part of option */
4945                 /*
4946                  * when getopt_long_only() finds a string which is not
4947                  * an option nor a known option argument it returns 1
4948                  * in that case if we already have found pathstart and pathend
4949                  * (i.e. we have the list of pathnames),
4950                  * the only supported value is "!"
4951                  */
4952                 isoption = (c != 1) || (strcmp(optarg, "!") == 0);
4953                 if (!isoption && pathend != -1) {
4954                         fprintf(stderr,
4955                                 "err: %s: filename|dirname must either precede options or follow options\n",
4956                                 argv[0]);
4957                         ret = CMD_HELP;
4958                         goto err;
4959                 }
4960                 if (!isoption && pathstart == -1)
4961                         pathstart = optind - 1;
4962                 if (isoption && pathstart != -1 && pathend == -1)
4963                         pathend = optind - 2;
4964                 switch (c) {
4965                 case 0:
4966                         /* Long options. */
4967                         break;
4968                 case 1:
4969                         /*
4970                          * unknown; opt is "!" or path component,
4971                          * checking done above.
4972                          */
4973                         if (strcmp(optarg, "!") == 0)
4974                                 neg_opt = 2;
4975                         break;
4976                 case 'A':
4977                         xtime = &param.fp_atime;
4978                         xsign = &param.fp_asign;
4979                         param.fp_exclude_atime = !!neg_opt;
4980                         /* no break, this falls through to 'B' for btime */
4981                 case 'B':
4982                         if (c == 'B') {
4983                                 xtime = &param.fp_btime;
4984                                 xsign = &param.fp_bsign;
4985                                 param.fp_exclude_btime = !!neg_opt;
4986                         }
4987                         /* no break, this falls through to 'C' for ctime */
4988                 case 'C':
4989                         if (c == 'C') {
4990                                 xtime = &param.fp_ctime;
4991                                 xsign = &param.fp_csign;
4992                                 param.fp_exclude_ctime = !!neg_opt;
4993                         }
4994                         /* no break, this falls through to 'M' for mtime */
4995                 case 'M':
4996                         if (c == 'M') {
4997                                 xtime = &param.fp_mtime;
4998                                 xsign = &param.fp_msign;
4999                                 param.fp_exclude_mtime = !!neg_opt;
5000                         }
5001                         rc = set_time(&param, &t, xtime, optarg);
5002                         if (rc == LONG_MAX) {
5003                                 ret = -1;
5004                                 goto err;
5005                         }
5006                         if (rc)
5007                                 *xsign = rc;
5008                         break;
5009                 case 'b':
5010                         if (optarg[0] == '+') {
5011                                 param.fp_blocks_sign = -1;
5012                                 optarg++;
5013                         } else if (optarg[0] == '-') {
5014                                 param.fp_blocks_sign =  1;
5015                                 optarg++;
5016                         }
5017
5018                         param.fp_blocks_units = 1024;
5019                         ret = llapi_parse_size(optarg, &param.fp_blocks,
5020                                                &param.fp_blocks_units, 0);
5021                         if (ret) {
5022                                 fprintf(stderr, "error: bad blocks '%s'\n",
5023                                         optarg);
5024                                 goto err;
5025                         }
5026                         param.fp_check_blocks = 1;
5027                         param.fp_exclude_blocks = !!neg_opt;
5028                         break;
5029                 case LFS_COMP_COUNT_OPT:
5030                         if (optarg[0] == '+') {
5031                                 param.fp_comp_count_sign = -1;
5032                                 optarg++;
5033                         } else if (optarg[0] == '-') {
5034                                 param.fp_comp_count_sign =  1;
5035                                 optarg++;
5036                         }
5037
5038                         errno = 0;
5039                         param.fp_comp_count = strtoul(optarg, &endptr, 0);
5040                         if (errno != 0 || *endptr != '\0' ||
5041                             param.fp_comp_count > UINT32_MAX) {
5042                                 fprintf(stderr,
5043                                         "error: bad component count '%s'\n",
5044                                         optarg);
5045                                 goto err;
5046                         }
5047                         param.fp_check_comp_count = 1;
5048                         param.fp_exclude_comp_count = !!neg_opt;
5049                         break;
5050                 case LFS_COMP_FLAGS_OPT:
5051                         rc = comp_str2flags(optarg, &param.fp_comp_flags,
5052                                             &param.fp_comp_neg_flags);
5053                         if (rc) {
5054                                 fprintf(stderr,
5055                                         "error: bad component flags '%s'\n",
5056                                         optarg);
5057                                 goto err;
5058                         }
5059                         param.fp_check_comp_flags = 1;
5060                         if (neg_opt) {
5061                                 __u32 flags = param.fp_comp_neg_flags;
5062
5063                                 param.fp_comp_neg_flags = param.fp_comp_flags;
5064                                 param.fp_comp_flags = flags;
5065                         }
5066                         break;
5067                 case LFS_COMP_START_OPT:
5068                         if (optarg[0] == '+') {
5069                                 param.fp_comp_start_sign = -1;
5070                                 optarg++;
5071                         } else if (optarg[0] == '-') {
5072                                 param.fp_comp_start_sign =  1;
5073                                 optarg++;
5074                         }
5075
5076                         rc = llapi_parse_size(optarg, &param.fp_comp_start,
5077                                               &param.fp_comp_start_units, 0);
5078                         if (rc) {
5079                                 fprintf(stderr,
5080                                         "error: bad component start '%s'\n",
5081                                         optarg);
5082                                 goto err;
5083                         }
5084                         param.fp_check_comp_start = 1;
5085                         param.fp_exclude_comp_start = !!neg_opt;
5086                         break;
5087                 case LFS_MIRROR_STATE_OPT:
5088                         rc = mirror_str2state(optarg, &param.fp_mirror_state,
5089                                               &param.fp_mirror_neg_state);
5090                         if (rc) {
5091                                 fprintf(stderr,
5092                                         "error: bad mirrored file state '%s'\n",
5093                                         optarg);
5094                                 goto err;
5095                         }
5096                         param.fp_check_mirror_state = 1;
5097                         if (neg_opt) {
5098                                 __u16 state = param.fp_mirror_neg_state;
5099
5100                                 param.fp_mirror_neg_state =
5101                                         param.fp_mirror_state;
5102                                 param.fp_mirror_state = state;
5103                         }
5104                         break;
5105                 case 'c':
5106                         if (optarg[0] == '+') {
5107                                 param.fp_stripe_count_sign = -1;
5108                                 optarg++;
5109                         } else if (optarg[0] == '-') {
5110                                 param.fp_stripe_count_sign =  1;
5111                                 optarg++;
5112                         }
5113
5114                         errno = 0;
5115                         param.fp_stripe_count = strtoul(optarg, &endptr, 0);
5116                         if (errno != 0 || *endptr != '\0' ||
5117                             param.fp_stripe_count > LOV_MAX_STRIPE_COUNT) {
5118                                 fprintf(stderr,
5119                                         "error: bad stripe_count '%s'\n",
5120                                         optarg);
5121                                 ret = -1;
5122                                 goto err;
5123                         }
5124                         param.fp_check_stripe_count = 1;
5125                         param.fp_exclude_stripe_count = !!neg_opt;
5126                         break;
5127                 case 'D':
5128                         errno = 0;
5129                         param.fp_max_depth = strtol(optarg, 0, 0);
5130                         if (errno != 0 || param.fp_max_depth < 0) {
5131                                 fprintf(stderr,
5132                                         "error: bad maxdepth '%s'\n",
5133                                         optarg);
5134                                 ret = -1;
5135                                 goto err;
5136                         }
5137                         break;
5138                 case 'E':
5139                         if (optarg[0] == '+') {
5140                                 param.fp_comp_end_sign = -1;
5141                                 optarg++;
5142                         } else if (optarg[0] == '-') {
5143                                 param.fp_comp_end_sign =  1;
5144                                 optarg++;
5145                         }
5146
5147                         if (arg_is_eof(optarg)) {
5148                                 param.fp_comp_end = LUSTRE_EOF;
5149                                 param.fp_comp_end_units = 1;
5150                                 rc = 0;
5151                         } else {
5152                                 rc = llapi_parse_size(optarg,
5153                                                 &param.fp_comp_end,
5154                                                 &param.fp_comp_end_units, 0);
5155                                 /* assume units of KB if too small */
5156                                 if (param.fp_comp_end < 4096)
5157                                         param.fp_comp_end *= 1024;
5158                         }
5159                         if (rc) {
5160                                 fprintf(stderr,
5161                                         "error: bad component end '%s'\n",
5162                                         optarg);
5163                                 goto err;
5164                         }
5165                         param.fp_check_comp_end = 1;
5166                         param.fp_exclude_comp_end = !!neg_opt;
5167                         break;
5168                 case LFS_LAYOUT_FOREIGN_OPT: {
5169                         /* all types by default */
5170                         uint32_t type = LU_FOREIGN_TYPE_UNKNOWN;
5171
5172                         if (optarg) {
5173                                 /* check pure numeric */
5174                                 type = strtoul(optarg, &endptr, 0);
5175                                 if (*endptr) {
5176                                         /* check name */
5177                                         type = check_foreign_type_name(optarg);
5178                                         if (type == LU_FOREIGN_TYPE_UNKNOWN) {
5179                                                 fprintf(stderr,
5180                                                         "%s %s: unknown foreign type '%s'\n",
5181                                                         progname, argv[0],
5182                                                         optarg);
5183                                                 return CMD_HELP;
5184                                         }
5185                                 } else if (type >= UINT32_MAX) {
5186                                         fprintf(stderr,
5187                                                 "%s %s: invalid foreign type '%s'\n",
5188                                                 progname, argv[0], optarg);
5189                                         return CMD_HELP;
5190                                 }
5191                         }
5192                         param.fp_foreign_type = type;
5193                         param.fp_check_foreign = 1;
5194                         param.fp_exclude_foreign = !!neg_opt;
5195                         break;
5196                 }
5197                 case LFS_NEWERXY_OPT: {
5198                         char x = 'm';
5199                         char y = 'm';
5200                         int xidx;
5201                         int negidx;
5202                         time_t *newery;
5203                         time_t ref = time(NULL);
5204
5205                         /* no need to check bad options, they won't get here */
5206                         if (strlen(long_opts[optidx].name) == 7) {
5207                                 x = long_opts[optidx].name[5];
5208                                 y = long_opts[optidx].name[6];
5209                         }
5210
5211                         if (y == 't') {
5212                                 static const char *const fmts[] = {
5213                                         "%Y-%m-%d %H:%M:%S",
5214                                         "%Y-%m-%d %H:%M",
5215                                         "%Y-%m-%d",
5216                                         "%H:%M:%S", /* sometime today */
5217                                         "%H:%M",
5218                                         "@%s",
5219                                         "%s",
5220                                         NULL };
5221                                 struct tm tm;
5222                                 bool found = false;
5223                                 int i;
5224
5225                                 for (i = 0; fmts[i] != NULL; i++) {
5226                                         char *ptr;
5227
5228                                         /* Init for times relative to today */
5229                                         if (strncmp(fmts[i], "%H", 2) == 0)
5230                                                 localtime_r(&ref, &tm);
5231                                         else
5232                                                 memset(&tm, 0, sizeof(tm));
5233                                         ptr = strptime(optarg, fmts[i], &tm);
5234                                         /* Skip spaces */
5235                                         while (ptr && isspace(*ptr))
5236                                                 ptr++;
5237                                         if (ptr == optarg + strlen(optarg)) {
5238                                                 found = true;
5239                                                 break;
5240                                         }
5241                                 }
5242
5243                                 if (!found) {
5244                                         fprintf(stderr,
5245                                                 "%s: invalid time '%s'\n",
5246                                                 progname, optarg);
5247                                         fprintf(stderr,
5248                                                 "supported formats are:\n  ");
5249                                         for (i = 0; fmts[i] != NULL; i++)
5250                                                 fprintf(stderr, "'%s', ",
5251                                                         fmts[i]);
5252                                         fprintf(stderr, "\n");
5253                                         ret = -EINVAL;
5254                                         goto err;
5255                                 }
5256
5257                                 ref = mktime(&tm);
5258                         } else if (y == 'b' || y == 'B') {
5259                                 lstatx_t stx;
5260
5261                                 rc = llapi_get_lum_file(optarg, NULL, &stx,
5262                                                         NULL, 0);
5263                                 if (rc || !(stx.stx_mask & STATX_BTIME)) {
5264                                         if (!(stx.stx_mask & STATX_BTIME))
5265                                                 ret = -EOPNOTSUPP;
5266                                         else
5267                                                 ret = -errno;
5268                                         fprintf(stderr,
5269                                                 "%s: get btime failed '%s': %s\n",
5270                                                 progname, optarg,
5271                                                 strerror(-ret));
5272                                         goto err;
5273                                 }
5274
5275                                 ref = stx.stx_btime.tv_sec;
5276                         } else {
5277                                 struct stat statbuf;
5278
5279                                 if (stat(optarg, &statbuf) < 0) {
5280                                         fprintf(stderr,
5281                                                 "%s: cannot stat file '%s': %s\n",
5282                                                 progname, optarg,
5283                                                 strerror(errno));
5284                                         ret = -errno;
5285                                         goto err;
5286                                 }
5287
5288                                 switch (y) {
5289                                 case 'a':
5290                                         ref = statbuf.st_atime;
5291                                         break;
5292                                 case 'm':
5293                                         ref = statbuf.st_mtime;
5294                                         break;
5295                                 case 'c':
5296                                         ref = statbuf.st_ctime;
5297                                         break;
5298                                 default:
5299                                         fprintf(stderr,
5300                                                 "%s: invalid Y argument: '%c'\n",
5301                                                 progname, x);
5302                                         ret = -EINVAL;
5303                                         goto err;
5304                                 }
5305                         }
5306
5307                         switch (x) {
5308                         case 'a':
5309                                 xidx = NEWERXY_ATIME;
5310                                 break;
5311                         case 'm':
5312                                 xidx = NEWERXY_MTIME;
5313                                 break;
5314                         case 'c':
5315                                 xidx = NEWERXY_CTIME;
5316                                 break;
5317                         case 'b':
5318                         case 'B':
5319                                 xidx = NEWERXY_BTIME;
5320                                 break;
5321                         default:
5322                                 fprintf(stderr,
5323                                         "%s: invalid X argument: '%c'\n",
5324                                         progname, x);
5325                                 ret = -EINVAL;
5326                                 goto err;
5327                         }
5328
5329                         negidx = !!neg_opt;
5330                         newery = &param.fp_newery[xidx][negidx];
5331
5332                         if (*newery == 0) {
5333                                 *newery = ref;
5334                         } else {
5335                                 if (negidx)
5336                                         *newery = *newery > ref ? ref : *newery;
5337                                 else
5338                                         *newery = *newery > ref ? *newery : ref;
5339                         }
5340                         param.fp_newerxy = 1;
5341                         break;
5342                 }
5343                 case 'g':
5344                 case 'G':
5345                         rc = name2gid(&param.fp_gid, optarg);
5346                         if (rc) {
5347                                 if (str2quotaid(&param.fp_gid, optarg)) {
5348                                         fprintf(stderr,
5349                                                 "Group/GID: %s cannot be found.\n",
5350                                                 optarg);
5351                                         ret = -1;
5352                                         goto err;
5353                                 }
5354                         }
5355                         param.fp_exclude_gid = !!neg_opt;
5356                         param.fp_check_gid = 1;
5357                         break;
5358                 case 'H':
5359                         rc = mdthash_input(optarg, &param.fp_hash_inflags,
5360                                            &param.fp_hash_exflags,
5361                                            &param.fp_hash_type);
5362                         if (rc) {
5363                                 ret = -1;
5364                                 goto err;
5365                         }
5366                         if (param.fp_hash_inflags || param.fp_hash_exflags)
5367                                 param.fp_check_hash_flag = 1;
5368                         param.fp_exclude_hash_type = !!neg_opt;
5369                         break;
5370                 case 'l':
5371                         param.fp_lazy = 1;
5372                         break;
5373                 case 'L':
5374                         ret = name2layout(&param.fp_layout, optarg);
5375                         if (ret)
5376                                 goto err;
5377                         param.fp_exclude_layout = !!neg_opt;
5378                         param.fp_check_layout = 1;
5379                         break;
5380                 case 'u':
5381                 case 'U':
5382                         rc = name2uid(&param.fp_uid, optarg);
5383                         if (rc) {
5384                                 if (str2quotaid(&param.fp_uid, optarg)) {
5385                                         fprintf(stderr,
5386                                                 "User/UID: %s cannot be found.\n",
5387                                                 optarg);
5388                                         ret = -1;
5389                                         goto err;
5390                                 }
5391                         }
5392                         param.fp_exclude_uid = !!neg_opt;
5393                         param.fp_check_uid = 1;
5394                         break;
5395                 case 'n':
5396                         param.fp_pattern = (char *)optarg;
5397                         param.fp_exclude_pattern = !!neg_opt;
5398                         break;
5399                 case 'N':
5400                         if (optarg[0] == '+') {
5401                                 param.fp_mirror_count_sign = -1;
5402                                 optarg++;
5403                         } else if (optarg[0] == '-') {
5404                                 param.fp_mirror_count_sign =  1;
5405                                 optarg++;
5406                         }
5407
5408                         errno = 0;
5409                         param.fp_mirror_count = strtoul(optarg, &endptr, 0);
5410                         if (errno != 0 || *endptr != '\0' ||
5411                             param.fp_mirror_count > LUSTRE_MIRROR_COUNT_MAX) {
5412                                 fprintf(stderr,
5413                                         "error: bad mirror count '%s'\n",
5414                                         optarg);
5415                                 goto err;
5416                         }
5417                         param.fp_check_mirror_count = 1;
5418                         param.fp_exclude_mirror_count = !!neg_opt;
5419                         break;
5420                 case 'm':
5421                 case 'i':
5422                 case 'O': {
5423                         char *buf, *token, *next, *p;
5424                         int len = 1;
5425                         void *tmp;
5426
5427                         buf = strdup(optarg);
5428                         if (!buf) {
5429                                 ret = -ENOMEM;
5430                                 goto err;
5431                         }
5432
5433                         param.fp_exclude_obd = !!neg_opt;
5434
5435                         token = buf;
5436                         while (token && *token) {
5437                                 token = strchr(token, ',');
5438                                 if (token) {
5439                                         len++;
5440                                         token++;
5441                                 }
5442                         }
5443                         if (c == 'm') {
5444                                 param.fp_exclude_mdt = !!neg_opt;
5445                                 param.fp_num_alloc_mdts += len;
5446                                 tmp = realloc(param.fp_mdt_uuid,
5447                                               param.fp_num_alloc_mdts *
5448                                               sizeof(*param.fp_mdt_uuid));
5449                                 if (!tmp) {
5450                                         ret = -ENOMEM;
5451                                         goto err_free;
5452                                 }
5453
5454                                 param.fp_mdt_uuid = tmp;
5455                         } else {
5456                                 param.fp_exclude_obd = !!neg_opt;
5457                                 param.fp_num_alloc_obds += len;
5458                                 tmp = realloc(param.fp_obd_uuid,
5459                                               param.fp_num_alloc_obds *
5460                                               sizeof(*param.fp_obd_uuid));
5461                                 if (!tmp) {
5462                                         ret = -ENOMEM;
5463                                         goto err_free;
5464                                 }
5465
5466                                 param.fp_obd_uuid = tmp;
5467                         }
5468                         for (token = buf; token && *token; token = next) {
5469                                 struct obd_uuid *puuid;
5470
5471                                 if (c == 'm') {
5472                                         puuid =
5473                                         &param.fp_mdt_uuid[param.fp_num_mdts++];
5474                                 } else {
5475                                         puuid =
5476                                         &param.fp_obd_uuid[param.fp_num_obds++];
5477                                 }
5478                                 p = strchr(token, ',');
5479                                 next = 0;
5480                                 if (p) {
5481                                         *p = 0;
5482                                         next = p+1;
5483                                 }
5484
5485                                 if (strlen(token) > sizeof(puuid->uuid) - 1) {
5486                                         ret = -E2BIG;
5487                                         goto err_free;
5488                                 }
5489
5490                                 strncpy(puuid->uuid, token,
5491                                         sizeof(puuid->uuid));
5492                         }
5493 err_free:
5494                         if (buf)
5495                                 free(buf);
5496                         break;
5497                 }
5498 #if LUSTRE_VERSION_CODE >= OBD_OCD_VERSION(2, 18, 53, 0)
5499                 case 'p':
5500 #endif
5501                 case LFS_POOL_OPT:
5502                         if (strlen(optarg) > LOV_MAXPOOLNAME) {
5503                                 fprintf(stderr,
5504                                         "Pool name %s is too long (max %d)\n",
5505                                         optarg, LOV_MAXPOOLNAME);
5506                                 ret = -1;
5507                                 goto err;
5508                         }
5509                         /*
5510                          * We do check for empty pool because empty pool
5511                          * is used to find V1 LOV attributes
5512                          */
5513                         strncpy(param.fp_poolname, optarg, LOV_MAXPOOLNAME);
5514                         param.fp_poolname[LOV_MAXPOOLNAME] = '\0';
5515                         param.fp_exclude_pool = !!neg_opt;
5516                         param.fp_check_pool = 1;
5517                         break;
5518 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 14, 53, 0)
5519                 case 'p': /* want this for --pool, to match getstripe/find */
5520                         fprintf(stderr,
5521                                 "warning: -p deprecated, use --print0 or -0\n");
5522 #endif
5523                 case '0':
5524                         param.fp_zero_end = 1;
5525                         break;
5526                 case 'P': /* we always print, this option is a no-op */
5527                         break;
5528                 case LFS_PROJID_OPT:
5529                         rc = name2projid(&param.fp_projid, optarg);
5530                         if (rc) {
5531                                 if (str2quotaid(&param.fp_projid, optarg)) {
5532                                         fprintf(stderr,
5533                                                 "Invalid project ID: %s\n",
5534                                                 optarg);
5535                                         ret = -1;
5536                                         goto err;
5537                                 }
5538                         }
5539                         param.fp_exclude_projid = !!neg_opt;
5540                         param.fp_check_projid = 1;
5541                         break;
5542                 case 's':
5543                         if (optarg[0] == '+') {
5544                                 param.fp_size_sign = -1;
5545                                 optarg++;
5546                         } else if (optarg[0] == '-') {
5547                                 param.fp_size_sign =  1;
5548                                 optarg++;
5549                         }
5550
5551                         ret = llapi_parse_size(optarg, &param.fp_size,
5552                                                &param.fp_size_units, 0);
5553                         if (ret) {
5554                                 fprintf(stderr, "error: bad file size '%s'\n",
5555                                         optarg);
5556                                 goto err;
5557                         }
5558                         param.fp_check_size = 1;
5559                         param.fp_exclude_size = !!neg_opt;
5560                         break;
5561                 case 'S':
5562                         if (optarg[0] == '+') {
5563                                 param.fp_stripe_size_sign = -1;
5564                                 optarg++;
5565                         } else if (optarg[0] == '-') {
5566                                 param.fp_stripe_size_sign =  1;
5567                                 optarg++;
5568                         }
5569
5570                         ret = llapi_parse_size(optarg, &param.fp_stripe_size,
5571                                                &param.fp_stripe_size_units, 0);
5572                         /* assume units of KB if too small to be valid */
5573                         if (param.fp_stripe_size < 4096)
5574                                 param.fp_stripe_size *= 1024;
5575                         if (ret) {
5576                                 fprintf(stderr, "error: bad stripe_size '%s'\n",
5577                                         optarg);
5578                                 goto err;
5579                         }
5580                         param.fp_check_stripe_size = 1;
5581                         param.fp_exclude_stripe_size = !!neg_opt;
5582                         break;
5583                 case 't':
5584                         param.fp_exclude_type = !!neg_opt;
5585                         switch (optarg[0]) {
5586                         case 'b':
5587                                 param.fp_type = S_IFBLK;
5588                                 break;
5589                         case 'c':
5590                                 param.fp_type = S_IFCHR;
5591                                 break;
5592                         case 'd':
5593                                 param.fp_type = S_IFDIR;
5594                                 break;
5595                         case 'f':
5596                                 param.fp_type = S_IFREG;
5597                                 break;
5598                         case 'l':
5599                                 param.fp_type = S_IFLNK;
5600                                 break;
5601                         case 'p':
5602                                 param.fp_type = S_IFIFO;
5603                                 break;
5604                         case 's':
5605                                 param.fp_type = S_IFSOCK;
5606                                 break;
5607                         default:
5608                                 fprintf(stderr, "%s: bad type '%s'\n",
5609                                         progname, optarg);
5610                                 ret = CMD_HELP;
5611                                 goto err;
5612                         }
5613                         break;
5614                 case LFS_FIND_PERM:
5615                         param.fp_exclude_perm = !!neg_opt;
5616                         param.fp_perm_sign = LFS_FIND_PERM_EXACT;
5617                         if (*optarg == '/') {
5618                                 param.fp_perm_sign = LFS_FIND_PERM_ANY;
5619                                 optarg++;
5620                         } else if (*optarg == '-') {
5621                                 param.fp_perm_sign = LFS_FIND_PERM_ALL;
5622                                 optarg++;
5623                         }
5624
5625                         if (str2mode_t(optarg, &param.fp_perm)) {
5626                                 fprintf(stderr, "error: invalid mode '%s'\n",
5627                                         optarg);
5628                                 ret = -1;
5629                                 goto err;
5630                         }
5631                         break;
5632                 case 'T':
5633                         if (optarg[0] == '+') {
5634                                 param.fp_mdt_count_sign = -1;
5635                                 optarg++;
5636                         } else if (optarg[0] == '-') {
5637                                 param.fp_mdt_count_sign =  1;
5638                                 optarg++;
5639                         }
5640
5641                         errno = 0;
5642                         param.fp_mdt_count = strtoul(optarg, &endptr, 0);
5643                         if (errno != 0 || *endptr != '\0' ||
5644                             param.fp_mdt_count >= UINT32_MAX) {
5645                                 fprintf(stderr, "error: bad mdt_count '%s'\n",
5646                                         optarg);
5647                                 ret = -1;
5648                                 goto err;
5649                         }
5650                         param.fp_check_mdt_count = 1;
5651                         param.fp_exclude_mdt_count = !!neg_opt;
5652                         break;
5653                 case 'z':
5654                         if (optarg[0] == '+') {
5655                                 param.fp_ext_size_sign = -1;
5656                                 optarg++;
5657                         } else if (optarg[0] == '-') {
5658                                 param.fp_ext_size_sign =  1;
5659                                 optarg++;
5660                         }
5661
5662                         ret = llapi_parse_size(optarg, &param.fp_ext_size,
5663                                                &param.fp_ext_size_units, 0);
5664                         if (ret) {
5665                                 fprintf(stderr, "error: bad ext-size '%s'\n",
5666                                         optarg);
5667                                 goto err;
5668                         }
5669                         param.fp_ext_size /= SEL_UNIT_SIZE;
5670                         param.fp_ext_size_units /= SEL_UNIT_SIZE;
5671                         param.fp_check_ext_size = 1;
5672                         param.fp_exclude_ext_size = !!neg_opt;
5673                         break;
5674                 default:
5675                         fprintf(stderr, "%s: unrecognized option '%s'\n",
5676                                 progname, argv[optind - 1]);
5677                 case 'h':
5678                         ret = CMD_HELP;
5679                         goto err;
5680                 }
5681         }
5682
5683         if (pathstart == -1) {
5684                 fprintf(stderr, "error: %s: no filename|pathname\n",
5685                         argv[0]);
5686                 ret = CMD_HELP;
5687                 goto err;
5688         } else if (pathend == -1) {
5689                 /* no options */
5690                 pathend = argc;
5691         }
5692
5693         do {
5694                 rc = llapi_find(argv[pathstart], &param);
5695                 if (rc && !ret) {
5696                         ret = rc;
5697                         pathbad = pathstart;
5698                 }
5699         } while (++pathstart < pathend);
5700
5701         if (ret)
5702                 fprintf(stderr, "%s: failed for '%s': %s\n",
5703                         progname, argv[pathbad], strerror(-rc));
5704
5705 err:
5706         if (param.fp_obd_uuid && param.fp_num_alloc_obds)
5707                 free(param.fp_obd_uuid);
5708
5709         if (param.fp_mdt_uuid && param.fp_num_alloc_mdts)
5710                 free(param.fp_mdt_uuid);
5711
5712         return ret;
5713 }
5714
5715 static int lfs_getstripe_internal(int argc, char **argv,
5716                                   struct find_param *param)
5717 {
5718         struct option long_opts[] = {
5719 /* find { .val = 'A',   .name = "atime",        .has_arg = required_argument }*/
5720 /* find { .val = 'b',   .name = "blocks",       .has_arg = required_argument }*/
5721 /* find { .val = 'B',   .name = "btime",        .has_arg = required_argument }*/
5722 /* find { .val = 'B',   .name = "Btime",        .has_arg = required_argument }*/
5723         { .val = LFS_COMP_COUNT_OPT,
5724                         .name = "comp-count",   .has_arg = no_argument },
5725         { .val = LFS_COMP_COUNT_OPT,
5726                 .name = "component-count",      .has_arg = no_argument },
5727         { .val = LFS_COMP_FLAGS_OPT,
5728                         .name = "comp-flags",   .has_arg = optional_argument },
5729         { .val = LFS_COMP_FLAGS_OPT,
5730                 .name = "component-flags",      .has_arg = optional_argument },
5731         { .val = LFS_COMP_START_OPT,
5732                         .name = "comp-start",   .has_arg = optional_argument },
5733         { .val = LFS_COMP_START_OPT,
5734                 .name = "component-start",      .has_arg = optional_argument },
5735         { .val = LFS_MIRROR_INDEX_OPT,
5736                 .name = "mirror-index",         .has_arg = required_argument },
5737         { .val = LFS_MIRROR_ID_OPT,
5738                 .name = "mirror-id",            .has_arg = required_argument },
5739         { .val = 'c',   .name = "stripe-count", .has_arg = no_argument },
5740         { .val = 'c',   .name = "stripe_count", .has_arg = no_argument },
5741 /* find { .val = 'C',   .name = "ctime",        .has_arg = required_argument }*/
5742         { .val = 'd',   .name = "directory",    .has_arg = no_argument },
5743         { .val = 'D',   .name = "default",      .has_arg = no_argument },
5744         { .val = 'E',   .name = "comp-end",     .has_arg = optional_argument },
5745         { .val = 'E',   .name = "component-end", .has_arg = optional_argument },
5746         { .val = 'F',   .name = "fid",          .has_arg = no_argument },
5747         { .val = 'g',   .name = "generation",   .has_arg = no_argument },
5748 /* find { .val = 'G',   .name = "group",        .has_arg = required_argument }*/
5749         { .val = 'h',   .name = "help",         .has_arg = no_argument },
5750 /* dirstripe { .val = 'H', .name = "mdt-hash",  .has_arg = required_argument }*/
5751         { .val = 'i',   .name = "stripe-index", .has_arg = no_argument },
5752         { .val = 'i',   .name = "stripe_index", .has_arg = no_argument },
5753         { .val = 'I',   .name = "comp-id",      .has_arg = optional_argument },
5754         { .val = 'I',   .name = "component-id", .has_arg = optional_argument },
5755 /* find { .val = 'l',   .name = "lazy",         .has_arg = no_argument }, */
5756         { .val = 'L',   .name = "layout",       .has_arg = no_argument },
5757         { .val = 'm',   .name = "mdt",          .has_arg = no_argument },
5758         { .val = 'm',   .name = "mdt-index",    .has_arg = no_argument },
5759         { .val = 'm',   .name = "mdt_index",    .has_arg = no_argument },
5760 /* find { .val = 'M',   .name = "mtime",        .has_arg = required_argument }*/
5761 /* find { .val = 'n',   .name = "name",         .has_arg = required_argument }*/
5762         { .val = 'N',   .name = "mirror-count", .has_arg = no_argument },
5763         { .val = 'O',   .name = "obd",          .has_arg = required_argument },
5764         { .val = 'O',   .name = "ost",          .has_arg = required_argument },
5765         { .val = 'p',   .name = "pool",         .has_arg = no_argument },
5766 /* find { .val = 'P',   .name = "print",        .has_arg = no_argument }, */
5767         { .val = 'q',   .name = "quiet",        .has_arg = no_argument },
5768         { .val = 'r',   .name = "recursive",    .has_arg = no_argument },
5769         { .val = 'R',   .name = "raw",          .has_arg = no_argument },
5770         { .val = 'S',   .name = "stripe-size",  .has_arg = no_argument },
5771         { .val = 'S',   .name = "stripe_size",  .has_arg = no_argument },
5772 /* find { .val = 't',   .name = "type",         .has_arg = required_argument }*/
5773 /* dirstripe { .val = 'T', .name = "mdt-count", .has_arg = required_argument }*/
5774 /* find { .val = 'u',   .name = "uid",          .has_arg = required_argument }*/
5775 /* find { .val = 'U',   .name = "user",         .has_arg = required_argument }*/
5776         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
5777 /* dirstripe { .val = 'X',.name = "max-inherit",.has_arg = required_argument }*/
5778         { .val = 'y',   .name = "yaml",         .has_arg = no_argument },
5779         { .val = 'z',   .name = "extension-size", .has_arg = no_argument },
5780         { .val = 'z',   .name = "ext-size",     .has_arg = no_argument },
5781         { .name = NULL } };
5782         int c, rc;
5783         int neg_opt = 0;
5784         int pathstart = -1, pathend = -1;
5785         int isoption;
5786         char *end, *tmp;
5787
5788         while ((c = getopt_long(argc, argv,
5789                         "-cdDE::FghiI::LmMNoO:pqrRsSvyz",
5790                         long_opts, NULL)) != -1) {
5791                 if (neg_opt)
5792                         --neg_opt;
5793
5794                 /* '!' is part of option */
5795                 isoption = (c != 1) || (strcmp(optarg, "!") == 0);
5796                 if (!isoption && pathend != -1) {
5797                         fprintf(stderr,
5798                                 "error: %s: filename|dirname must either precede options or follow options\n",
5799                                 argv[0]);
5800                         return CMD_HELP;
5801                 }
5802                 if (!isoption && pathstart == -1)
5803                         pathstart = optind - 1;
5804                 if (isoption && pathstart != -1 && pathend == -1)
5805                         pathend = optind - 2;
5806
5807                 switch (c) {
5808                 case 1:
5809                         /* unknown: opt is "!" */
5810                         if (strcmp(optarg, "!") == 0)
5811                                 neg_opt = 2;
5812                         break;
5813                 case 'c':
5814                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
5815                                 param->fp_verbose |= VERBOSE_COUNT;
5816                                 param->fp_max_depth = 0;
5817                         }
5818                         break;
5819                 case LFS_COMP_COUNT_OPT:
5820                         param->fp_verbose |= VERBOSE_COMP_COUNT;
5821                         param->fp_max_depth = 0;
5822                         break;
5823                 case LFS_COMP_FLAGS_OPT:
5824                         if (optarg) {
5825                                 rc = comp_str2flags(optarg,
5826                                                     &param->fp_comp_flags,
5827                                                     &param->fp_comp_neg_flags);
5828                                 if (rc != 0) {
5829                                         fprintf(stderr,
5830                                                 "error: %s bad component flags '%s'.\n",
5831                                                 argv[0], optarg);
5832                                         return CMD_HELP;
5833                                 }
5834                                 param->fp_check_comp_flags = 1;
5835                         } else {
5836                                 param->fp_verbose |= VERBOSE_COMP_FLAGS;
5837                                 param->fp_max_depth = 0;
5838                         }
5839                         break;
5840                 case LFS_COMP_START_OPT:
5841                         if (optarg) {
5842                                 tmp = optarg;
5843                                 if (tmp[0] == '+') {
5844                                         param->fp_comp_start_sign = -1;
5845                                         tmp++;
5846                                 } else if (tmp[0] == '-') {
5847                                         param->fp_comp_start_sign = 1;
5848                                         tmp++;
5849                                 }
5850                                 rc = llapi_parse_size(tmp,
5851                                                 &param->fp_comp_start,
5852                                                 &param->fp_comp_start_units, 0);
5853                                 if (rc != 0) {
5854                                         fprintf(stderr,
5855                                                 "error: %s bad component start '%s'.\n",
5856                                                 argv[0], tmp);
5857                                         return CMD_HELP;
5858                                 }
5859                                 param->fp_check_comp_start = 1;
5860                         } else {
5861                                 param->fp_verbose |= VERBOSE_COMP_START;
5862                                 param->fp_max_depth = 0;
5863                         }
5864                         break;
5865                 case LFS_MIRROR_INDEX_OPT: {
5866                         unsigned long int mirror_index;
5867
5868                         if (optarg[0] == '+') {
5869                                 param->fp_mirror_index_sign = -1;
5870                                 optarg++;
5871                         } else if (optarg[0] == '-') {
5872                                 param->fp_mirror_index_sign = 1;
5873                                 optarg++;
5874                         }
5875
5876                         errno = 0;
5877                         mirror_index = strtoul(optarg, &end, 0);
5878                         if (errno != 0 || *end != '\0' ||
5879                             mirror_index > UINT16_MAX || (mirror_index == 0 &&
5880                             param->fp_mirror_index_sign == 0 && neg_opt == 0)) {
5881                                 fprintf(stderr,
5882                                         "%s %s: invalid mirror index '%s'\n",
5883                                         progname, argv[0], optarg);
5884                                 return CMD_HELP;
5885                         }
5886
5887                         param->fp_mirror_index = (__u16)mirror_index;
5888
5889                         if (param->fp_mirror_id != 0) {
5890                                 fprintf(stderr,
5891                                         "%s %s: can't specify both mirror index and mirror ID\n",
5892                                         progname, argv[0]);
5893                                 return CMD_HELP;
5894                         }
5895                         param->fp_check_mirror_index = 1;
5896                         param->fp_exclude_mirror_index = !!neg_opt;
5897                         break;
5898                 }
5899                 case LFS_MIRROR_ID_OPT: {
5900                         unsigned long int mirror_id;
5901
5902                         if (optarg[0] == '+') {
5903                                 param->fp_mirror_id_sign = -1;
5904                                 optarg++;
5905                         } else if (optarg[0] == '-') {
5906                                 param->fp_mirror_id_sign = 1;
5907                                 optarg++;
5908                         }
5909
5910                         errno = 0;
5911                         mirror_id = strtoul(optarg, &end, 0);
5912                         if (errno != 0 || *end != '\0' ||
5913                             mirror_id > UINT16_MAX || (mirror_id == 0 &&
5914                             param->fp_mirror_id_sign == 0 && neg_opt == 0)) {
5915                                 fprintf(stderr,
5916                                         "%s %s: invalid mirror ID '%s'\n",
5917                                         progname, argv[0], optarg);
5918                                 return CMD_HELP;
5919                         }
5920
5921                         param->fp_mirror_id = (__u16)mirror_id;
5922
5923                         if (param->fp_mirror_index != 0) {
5924                                 fprintf(stderr,
5925                                         "%s %s: can't specify both mirror index and mirror ID\n",
5926                                         progname, argv[0]);
5927                                 return CMD_HELP;
5928                         }
5929                         param->fp_check_mirror_id = 1;
5930                         param->fp_exclude_mirror_id = !!neg_opt;
5931                         break;
5932                 }
5933                 case 'd':
5934                         param->fp_max_depth = 0;
5935                         break;
5936                 case 'D':
5937                         param->fp_get_default_lmv = 1;
5938                         break;
5939                 case 'E':
5940                         if (optarg) {
5941                                 tmp = optarg;
5942                                 if (tmp[0] == '+') {
5943                                         param->fp_comp_end_sign = -1;
5944                                         tmp++;
5945                                 } else if (tmp[0] == '-') {
5946                                         param->fp_comp_end_sign = 1;
5947                                         tmp++;
5948                                 }
5949
5950                                 if (arg_is_eof(tmp)) {
5951                                         param->fp_comp_end = LUSTRE_EOF;
5952                                         param->fp_comp_end_units = 1;
5953                                         rc = 0;
5954                                 } else {
5955                                         rc = llapi_parse_size(tmp,
5956                                                 &param->fp_comp_end,
5957                                                 &param->fp_comp_end_units, 0);
5958                                         /* assume units of KB if too small */
5959                                         if (param->fp_comp_end < 4096)
5960                                                 param->fp_comp_end *= 1024;
5961                                 }
5962                                 if (rc != 0) {
5963                                         fprintf(stderr,
5964                                                 "error: %s bad component end '%s'.\n",
5965                                                 argv[0], tmp);
5966                                         return CMD_HELP;
5967                                 }
5968                                 param->fp_check_comp_end = 1;
5969                         } else {
5970                                 param->fp_verbose |= VERBOSE_COMP_END;
5971                                 param->fp_max_depth = 0;
5972                         }
5973                         break;
5974                 case 'F':
5975                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
5976                                 param->fp_verbose |= VERBOSE_DFID;
5977                                 param->fp_max_depth = 0;
5978                         }
5979                         break;
5980                 case 'g':
5981                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
5982                                 param->fp_verbose |= VERBOSE_GENERATION;
5983                                 param->fp_max_depth = 0;
5984                         }
5985                         break;
5986                 case 'i':
5987                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
5988                                 param->fp_verbose |= VERBOSE_STRIPE_OFFSET;
5989                                 param->fp_max_depth = 0;
5990                         }
5991                         break;
5992                 case 'I':
5993                         if (optarg) {
5994                                 param->fp_comp_id = strtoul(optarg, &end, 0);
5995                                 if (*end != '\0' || param->fp_comp_id == 0 ||
5996                                     param->fp_comp_id > LCME_ID_MAX) {
5997                                         fprintf(stderr,
5998                                                 "error: %s bad component id '%s'\n",
5999                                                 argv[0], optarg);
6000                                         return CMD_HELP;
6001                                 }
6002                                 param->fp_check_comp_id = 1;
6003                         } else {
6004                                 param->fp_max_depth = 0;
6005                                 param->fp_verbose |= VERBOSE_COMP_ID;
6006                         }
6007                         break;
6008                 case 'L':
6009                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6010                                 param->fp_verbose |= VERBOSE_PATTERN;
6011                                 param->fp_max_depth = 0;
6012                         }
6013                         break;
6014 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
6015                 case 'M':
6016                         fprintf(stderr,
6017                                 "warning: '-M' deprecated, use '--mdt-index' or '-m' instead\n");
6018 #endif
6019                 case 'm':
6020                         if (!(param->fp_verbose & VERBOSE_DETAIL))
6021                                 param->fp_max_depth = 0;
6022                         param->fp_verbose |= VERBOSE_MDTINDEX;
6023                         break;
6024                 case 'N':
6025                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6026                                 param->fp_verbose |= VERBOSE_MIRROR_COUNT;
6027                                 param->fp_max_depth = 0;
6028                         }
6029                         break;
6030                 case 'O':
6031                         if (param->fp_obd_uuid) {
6032                                 fprintf(stderr,
6033                                         "error: %s: only one obduuid allowed",
6034                                         argv[0]);
6035                                 return CMD_HELP;
6036                         }
6037                         param->fp_obd_uuid = (struct obd_uuid *)optarg;
6038                         break;
6039                 case 'p':
6040                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6041                                 param->fp_verbose |= VERBOSE_POOL;
6042                                 param->fp_max_depth = 0;
6043                         }
6044                         break;
6045                 case 'q':
6046                         param->fp_quiet++;
6047                         break;
6048                 case 'r':
6049                         param->fp_recursive = 1;
6050                         break;
6051                 case 'R':
6052                         param->fp_raw = 1;
6053                         break;
6054                 case 'S':
6055                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6056                                 param->fp_verbose |= VERBOSE_STRIPE_SIZE;
6057                                 param->fp_max_depth = 0;
6058                         }
6059                         break;
6060                 case 'v':
6061                         param->fp_verbose = VERBOSE_DEFAULT | VERBOSE_DETAIL;
6062                         break;
6063                 case 'y':
6064                         param->fp_yaml = 1;
6065                         break;
6066                 case 'z':
6067                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6068                                 param->fp_verbose |= VERBOSE_EXT_SIZE;
6069                                 param->fp_max_depth = 0;
6070                         }
6071                         break;
6072                 default:
6073                         fprintf(stderr, "%s: unrecognized option '%s'\n",
6074                                 progname, argv[optind - 1]);
6075                 case 'h':
6076                         return CMD_HELP;
6077                 }
6078         }
6079
6080         if (pathstart == -1) {
6081                 fprintf(stderr, "error: %s: no filename|pathname\n",
6082                                 argv[0]);
6083                 return CMD_HELP;
6084         } else if (pathend == -1) {
6085                 /* no options */
6086                 pathend = argc;
6087         }
6088
6089         if (pathend > argc)
6090                 return CMD_HELP;
6091
6092         if (param->fp_recursive)
6093                 param->fp_max_depth = -1;
6094         else if (param->fp_verbose & VERBOSE_DETAIL)
6095                 param->fp_max_depth = 1;
6096
6097         if (!param->fp_verbose)
6098                 param->fp_verbose = VERBOSE_DEFAULT;
6099         if (param->fp_quiet)
6100                 param->fp_verbose = VERBOSE_OBJID;
6101
6102         do {
6103                 rc = llapi_getstripe(argv[pathstart], param);
6104         } while (++pathstart < pathend && !rc);
6105
6106         if (rc)
6107                 fprintf(stderr, "error: %s failed for %s.\n",
6108                         argv[0], argv[optind - 1]);
6109         return rc;
6110 }
6111
6112 static int lfs_tgts(int argc, char **argv)
6113 {
6114         char mntdir[PATH_MAX] = {'\0'}, path[PATH_MAX] = {'\0'};
6115         struct find_param param;
6116         int index = 0, rc = 0;
6117
6118         if (argc > 2)
6119                 return CMD_HELP;
6120
6121         if (argc == 2 && !realpath(argv[1], path)) {
6122                 rc = -errno;
6123                 fprintf(stderr, "error: invalid path '%s': %s\n",
6124                         argv[1], strerror(-rc));
6125                 return rc;
6126         }
6127
6128         while (!llapi_search_mounts(path, index++, mntdir, NULL)) {
6129                 /* Check if we have a mount point */
6130                 if (mntdir[0] == '\0')
6131                         continue;
6132
6133                 memset(&param, 0, sizeof(param));
6134                 if (!strcmp(argv[0], "mdts"))
6135                         param.fp_get_lmv = 1;
6136
6137                 rc = llapi_ostlist(mntdir, &param);
6138                 if (rc) {
6139                         fprintf(stderr, "error: %s: failed on %s\n",
6140                                 argv[0], mntdir);
6141                 }
6142                 if (path[0] != '\0')
6143                         break;
6144                 memset(mntdir, 0, PATH_MAX);
6145         }
6146
6147         return rc;
6148 }
6149
6150 static int lfs_getstripe(int argc, char **argv)
6151 {
6152         struct find_param param = { 0 };
6153
6154         param.fp_max_depth = 1;
6155         return lfs_getstripe_internal(argc, argv, &param);
6156 }
6157
6158 /* functions */
6159 static int lfs_getdirstripe(int argc, char **argv)
6160 {
6161         struct find_param param = { 0 };
6162         struct option long_opts[] = {
6163         { .val = 'c',   .name = "mdt-count",     .has_arg = no_argument },
6164         { .val = 'D',   .name = "default",       .has_arg = no_argument },
6165         { .val = 'h',   .name = "help",         .has_arg = no_argument },
6166         { .val = 'H',   .name = "mdt-hash",      .has_arg = no_argument },
6167         { .val = 'i',   .name = "mdt-index",     .has_arg = no_argument },
6168         { .val = 'm',   .name = "mdt-index",     .has_arg = no_argument },
6169         { .val = 'O',   .name = "obd",           .has_arg = required_argument },
6170         { .val = 'r',   .name = "recursive",     .has_arg = no_argument },
6171         { .val = 'T',   .name = "mdt-count",     .has_arg = no_argument },
6172         { .val = 'v',   .name = "verbose",       .has_arg = no_argument },
6173         { .val = 'X',   .name = "max-inherit",   .has_arg = no_argument },
6174         { .val = 'y',   .name = "yaml",          .has_arg = no_argument },
6175         { .val = LFS_INHERIT_RR_OPT,
6176                         .name = "max-inherit-rr", .has_arg = no_argument },
6177         { .name = NULL } };
6178         int c, rc;
6179
6180         param.fp_get_lmv = 1;
6181
6182         while ((c = getopt_long(argc, argv,
6183                                 "cDhHimO:rtTvXy", long_opts, NULL)) != -1) {
6184                 switch (c) {
6185                 case 'c':
6186                 case 'T':
6187                         param.fp_verbose |= VERBOSE_COUNT;
6188                         break;
6189                 case 'D':
6190                         param.fp_get_default_lmv = 1;
6191                         break;
6192 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
6193                 case 't':
6194                         fprintf(stderr,
6195                                 "warning: '-t' deprecated, use '--mdt-hash' or '-H' instead\n");
6196                         /* fallthrough */
6197 #endif
6198                 case 'H':
6199                         param.fp_verbose |= VERBOSE_HASH_TYPE;
6200                         break;
6201                 case 'i': /* fallthrough */
6202                 case 'm':
6203                         param.fp_verbose |= VERBOSE_STRIPE_OFFSET;
6204                         break;
6205                 case 'O':
6206                         if (param.fp_obd_uuid) {
6207                                 fprintf(stderr,
6208                                         "%s: only one obduuid allowed",
6209                                         progname);
6210                                 return CMD_HELP;
6211                         }
6212                         param.fp_obd_uuid = (struct obd_uuid *)optarg;
6213                         break;
6214                 case 'r':
6215                         param.fp_recursive = 1;
6216                         break;
6217                 case 'v':
6218                         param.fp_verbose |= VERBOSE_DETAIL;
6219                         break;
6220                 case 'X':
6221                         param.fp_verbose |= VERBOSE_INHERIT;
6222                         break;
6223                 case LFS_INHERIT_RR_OPT:
6224                         param.fp_verbose |= VERBOSE_INHERIT_RR;
6225                         break;
6226                 case 'y':
6227                         param.fp_yaml = 1;
6228                         break;
6229                 default:
6230                         fprintf(stderr, "%s: unrecognized option '%s'\n",
6231                                 progname, argv[optind - 1]);
6232                         /* fallthrough */
6233                 case 'h':
6234                         return CMD_HELP;
6235                 }
6236         }
6237
6238         if (optind >= argc)
6239                 return CMD_HELP;
6240
6241         if (param.fp_recursive)
6242                 param.fp_max_depth = -1;
6243
6244         if (!param.fp_verbose)
6245                 param.fp_verbose = VERBOSE_DEFAULT;
6246
6247         do {
6248                 rc = llapi_getstripe(argv[optind], &param);
6249         } while (++optind < argc && !rc);
6250
6251         if (rc)
6252                 fprintf(stderr, "error: %s failed for %s.\n",
6253                         argv[0], argv[optind - 1]);
6254         return rc;
6255 }
6256
6257 enum mntdf_flags {
6258         MNTDF_INODES    = 0x0001,
6259         MNTDF_COOKED    = 0x0002,
6260         MNTDF_LAZY      = 0x0004,
6261         MNTDF_VERBOSE   = 0x0008,
6262         MNTDF_SHOW      = 0x0010,
6263         MNTDF_DECIMAL   = 0x0020,
6264 };
6265
6266 #define COOK(value, base)                                       \
6267 ({                                                              \
6268         int radix = 0;                                          \
6269         while (value > base) {                                  \
6270                 value /= base;                                  \
6271                 radix++;                                        \
6272         }                                                       \
6273         radix;                                                  \
6274 })
6275 #define UUF     "%-20s"
6276 #define CSF     "%11s"
6277 #define CDF     "%11llu"
6278 #define HDF     "%8.1f%c"
6279 #define RSF     "%4s"
6280 #define RDF     "%3d%%"
6281
6282 static inline int obd_statfs_ratio(const struct obd_statfs *st, bool inodes)
6283 {
6284         double avail, used, ratio = 0;
6285
6286         if (inodes) {
6287                 avail = st->os_ffree;
6288                 used = st->os_files - st->os_ffree;
6289         } else {
6290                 avail = st->os_bavail;
6291                 used = st->os_blocks - st->os_bfree;
6292         }
6293         if (avail + used > 0)
6294                 ratio = used / (used + avail) * 100;
6295
6296         /* Round up to match df(1) usage percentage */
6297         return (ratio - (int)ratio) > 0 ? (int)(ratio + 1) : (int)ratio;
6298 }
6299
6300 /*
6301  * This is to identify various problem states for "lfs df" if .osn_err = true,
6302  * so only show flags reflecting those states by default. Informational states
6303  * are only shown with "-v" and use lower-case names to distinguish them.
6304  * UNUSED[12] were for "EROFS = 30" until 1.6 but are now available for use.
6305  */
6306 static struct obd_statfs_state_names {
6307         enum obd_statfs_state   osn_state;
6308         const char              osn_name;
6309         bool                    osn_err;
6310 } oss_names[] = {
6311         { .osn_state = OS_STATFS_DEGRADED,   .osn_name = 'D', .osn_err = true },
6312         { .osn_state = OS_STATFS_READONLY,   .osn_name = 'R', .osn_err = true },
6313         { .osn_state = OS_STATFS_NOPRECREATE,.osn_name = 'N', .osn_err = true },
6314         { .osn_state = OS_STATFS_UNUSED1,    .osn_name = '?', .osn_err = true },
6315         { .osn_state = OS_STATFS_UNUSED2,    .osn_name = '?', .osn_err = true },
6316         { .osn_state = OS_STATFS_ENOSPC,     .osn_name = 'S', .osn_err = true },
6317         { .osn_state = OS_STATFS_ENOINO,     .osn_name = 'I', .osn_err = true },
6318         { .osn_state = OS_STATFS_SUM,        .osn_name = 'a', /* aggregate */ },
6319         { .osn_state = OS_STATFS_NONROT,     .osn_name = 'f', /* flash */     },
6320 };
6321
6322 static int showdf(char *mntdir, struct obd_statfs *stat,
6323                   char *uuid, enum mntdf_flags flags,
6324                   char *type, int index, int rc)
6325 {
6326         long long avail, used, total;
6327         int ratio = 0;
6328         char *suffix = flags & MNTDF_DECIMAL ? "kMGTPEZY" : "KMGTPEZY";
6329         /* Note if we have >2^64 bytes/fs these buffers will need to be grown */
6330         char tbuf[3 * sizeof(__u64)];
6331         char ubuf[3 * sizeof(__u64)];
6332         char abuf[3 * sizeof(__u64)];
6333         char rbuf[3 * sizeof(__u64)];
6334
6335         if (!uuid || !stat)
6336                 return -EINVAL;
6337
6338         switch (rc) {
6339         case 0:
6340                 if (flags & MNTDF_INODES) {
6341                         avail = stat->os_ffree;
6342                         used = stat->os_files - stat->os_ffree;
6343                         total = stat->os_files;
6344                 } else {
6345                         int shift = flags & MNTDF_COOKED ? 0 : 10;
6346
6347                         avail = (stat->os_bavail * stat->os_bsize) >> shift;
6348                         used  = ((stat->os_blocks - stat->os_bfree) *
6349                                  stat->os_bsize) >> shift;
6350                         total = (stat->os_blocks * stat->os_bsize) >> shift;
6351                 }
6352
6353                 ratio = obd_statfs_ratio(stat, flags & MNTDF_INODES);
6354
6355                 if (flags & MNTDF_COOKED) {
6356                         int base = flags & MNTDF_DECIMAL ? 1000 : 1024;
6357                         double cook_val;
6358                         int i;
6359
6360                         cook_val = (double)total;
6361                         i = COOK(cook_val, base);
6362                         if (i > 0)
6363                                 snprintf(tbuf, sizeof(tbuf), HDF, cook_val,
6364                                          suffix[i - 1]);
6365                         else
6366                                 snprintf(tbuf, sizeof(tbuf), CDF, total);
6367
6368                         cook_val = (double)used;
6369                         i = COOK(cook_val, base);
6370                         if (i > 0)
6371                                 snprintf(ubuf, sizeof(ubuf), HDF, cook_val,
6372                                          suffix[i - 1]);
6373                         else
6374                                 snprintf(ubuf, sizeof(ubuf), CDF, used);
6375
6376                         cook_val = (double)avail;
6377                         i = COOK(cook_val, base);
6378                         if (i > 0)
6379                                 snprintf(abuf, sizeof(abuf), HDF, cook_val,
6380                                          suffix[i - 1]);
6381                         else
6382                                 snprintf(abuf, sizeof(abuf), CDF, avail);
6383                 } else {
6384                         snprintf(tbuf, sizeof(tbuf), CDF, total);
6385                         snprintf(ubuf, sizeof(tbuf), CDF, used);
6386                         snprintf(abuf, sizeof(tbuf), CDF, avail);
6387                 }
6388
6389                 sprintf(rbuf, RDF, ratio);
6390                 printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s",
6391                        uuid, tbuf, ubuf, abuf, rbuf, mntdir);
6392                 if (type)
6393                         printf("[%s:%d]", type, index);
6394
6395                 if (stat->os_state) {
6396                         uint32_t i;
6397
6398                         printf(" ");
6399                         for (i = 0; i < ARRAY_SIZE(oss_names); i++) {
6400                                 if (oss_names[i].osn_state & stat->os_state &&
6401                                     (oss_names[i].osn_err ||
6402                                      flags & MNTDF_VERBOSE))
6403                                         printf("%c", oss_names[i].osn_name);
6404                         }
6405                 }
6406
6407                 printf("\n");
6408                 break;
6409         case -ENODATA:
6410                 printf(UUF": inactive device\n", uuid);
6411                 break;
6412         default:
6413                 printf(UUF": %s\n", uuid, strerror(-rc));
6414                 break;
6415         }
6416
6417         return 0;
6418 }
6419
6420 struct ll_stat_type {
6421         int   st_op;
6422         char *st_name;
6423 };
6424
6425 #define LL_STATFS_MAX   LOV_MAX_STRIPE_COUNT
6426
6427 struct ll_statfs_data {
6428         int                     sd_index;
6429         struct obd_statfs       sd_st;
6430 };
6431
6432 struct ll_statfs_buf {
6433         int                     sb_count;
6434         struct ll_statfs_data   sb_buf[LL_STATFS_MAX];
6435 };
6436
6437 static int mntdf(char *mntdir, char *fsname, char *pool, enum mntdf_flags flags,
6438                  int ops, struct ll_statfs_buf *lsb)
6439 {
6440         struct obd_statfs stat_buf, sum = { .os_bsize = 1 };
6441         struct obd_uuid uuid_buf;
6442         char *poolname = NULL;
6443         struct ll_stat_type types[] = {
6444                 { .st_op = LL_STATFS_LMV,       .st_name = "MDT" },
6445                 { .st_op = LL_STATFS_LOV,       .st_name = "OST" },
6446                 { .st_name = NULL } };
6447         struct ll_stat_type *tp;
6448         __u64 ost_files = 0;
6449         __u64 ost_ffree = 0;
6450         __u32 index;
6451         __u32 type;
6452         int fd;
6453         int rc = 0;
6454         int rc2;
6455
6456         if (pool) {
6457                 poolname = strchr(pool, '.');
6458                 if (poolname) {
6459                         if (strncmp(fsname, pool, strlen(fsname))) {
6460                                 fprintf(stderr, "filesystem name incorrect\n");
6461                                 return -ENODEV;
6462                         }
6463                         poolname++;
6464                 } else
6465                         poolname = pool;
6466         }
6467
6468         fd = open(mntdir, O_RDONLY);
6469         if (fd < 0) {
6470                 rc = -errno;
6471                 fprintf(stderr, "%s: cannot open '%s': %s\n", progname, mntdir,
6472                         strerror(errno));
6473                 return rc;
6474         }
6475
6476         if (flags & MNTDF_SHOW) {
6477                 if (flags & MNTDF_INODES)
6478                         printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s\n",
6479                                "UUID", "Inodes", "IUsed", "IFree",
6480                                "IUse%", "Mounted on");
6481                 else
6482                         printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s\n",
6483                                "UUID",
6484                                flags & MNTDF_COOKED ? "bytes" : "1K-blocks",
6485                                "Used", "Available", "Use%", "Mounted on");
6486         }
6487
6488         for (tp = types; tp->st_name != NULL; tp++) {
6489                 bool have_ost = false;
6490
6491                 if (!(tp->st_op & ops))
6492                         continue;
6493
6494                 for (index = 0; ; index++) {
6495                         memset(&stat_buf, 0, sizeof(struct obd_statfs));
6496                         memset(&uuid_buf, 0, sizeof(struct obd_uuid));
6497                         type = flags & MNTDF_LAZY ?
6498                                 tp->st_op | LL_STATFS_NODELAY : tp->st_op;
6499                         rc2 = llapi_obd_fstatfs(fd, type, index,
6500                                                &stat_buf, &uuid_buf);
6501                         if (rc2 == -ENODEV)
6502                                 break;
6503                         if (rc2 == -EAGAIN)
6504                                 continue;
6505                         if (rc2 == -ENODATA) { /* Inactive device, OK. */
6506                                 if (!(flags & MNTDF_VERBOSE))
6507                                         continue;
6508                         } else if (rc2 < 0 && rc == 0) {
6509                                 rc = rc2;
6510                         }
6511
6512                         /*
6513                          * If we have OSTs then don't report MDT block counts.
6514                          * For MDT-only filesystems the expectation is that all
6515                          * layouts have a DoM component.  For filesystems with
6516                          * OSTs, files are not necessarily going to store data
6517                          * on MDTs, and MDT space is limited to a fraction of
6518                          * OST space, so don't include it in the summary.
6519                          */
6520                         if (tp->st_op == LL_STATFS_LOV && !have_ost) {
6521                                 have_ost = true;
6522                                 sum.os_blocks = 0;
6523                                 sum.os_bfree = 0;
6524                                 sum.os_bavail = 0;
6525                         }
6526
6527                         if (poolname && tp->st_op == LL_STATFS_LOV &&
6528                             llapi_search_ost(fsname, poolname,
6529                                              obd_uuid2str(&uuid_buf)) != 1)
6530                                 continue;
6531
6532                         /*
6533                          * the llapi_obd_fstatfs() call may have returned with
6534                          * an error, but if it filled in uuid_buf we will at
6535                          * lease use that to print out a message for that OBD.
6536                          * If we didn't get anything in the uuid_buf, then fill
6537                          * it in so that we can print an error message.
6538                          */
6539                         if (uuid_buf.uuid[0] == '\0')
6540                                 snprintf(uuid_buf.uuid, sizeof(uuid_buf.uuid),
6541                                          "%s%04x", tp->st_name, index);
6542                         if (!rc && lsb) {
6543                                 lsb->sb_buf[lsb->sb_count].sd_index = index;
6544                                 lsb->sb_buf[lsb->sb_count].sd_st = stat_buf;
6545                                 lsb->sb_count++;
6546                         }
6547                         if (flags & MNTDF_SHOW)
6548                                 showdf(mntdir, &stat_buf,
6549                                        obd_uuid2str(&uuid_buf), flags,
6550                                        tp->st_name, index, rc2);
6551
6552                         if (rc2)
6553                                 continue;
6554
6555                         if (tp->st_op == LL_STATFS_LMV) {
6556                                 sum.os_ffree += stat_buf.os_ffree;
6557                                 sum.os_files += stat_buf.os_files;
6558                         } else /* if (tp->st_op == LL_STATFS_LOV) */ {
6559                                 ost_files += stat_buf.os_files;
6560                                 ost_ffree += stat_buf.os_ffree;
6561                         }
6562                         sum.os_blocks += stat_buf.os_blocks *
6563                                          stat_buf.os_bsize;
6564                         sum.os_bfree  += stat_buf.os_bfree *
6565                                          stat_buf.os_bsize;
6566                         sum.os_bavail += stat_buf.os_bavail *
6567                                          stat_buf.os_bsize;
6568                 }
6569         }
6570
6571         close(fd);
6572
6573         /*
6574          * If we have _some_ OSTs, but don't have as many free objects on the
6575          * OST as inodes on the MDTs, reduce the reported number of inodes
6576          * to compensate, so that the "inodes in use" number is correct.
6577          * This should be kept in sync with ll_statfs_internal().
6578          */
6579         if (ost_files && ost_ffree < sum.os_ffree) {
6580                 sum.os_files = (sum.os_files - sum.os_ffree) + ost_ffree;
6581                 sum.os_ffree = ost_ffree;
6582         }
6583         if (flags & MNTDF_SHOW) {
6584                 printf("\n");
6585                 showdf(mntdir, &sum, "filesystem_summary:", flags, NULL, 0, 0);
6586                 printf("\n");
6587         }
6588
6589         return rc;
6590 }
6591
6592 enum {
6593         LAYOUT_INHERIT_UNSET    = -2,
6594 };
6595
6596 /* functions */
6597 static int lfs_setdirstripe(int argc, char **argv)
6598 {
6599         char *dname;
6600         struct lfs_setstripe_args lsa = { 0 };
6601         struct llapi_stripe_param *param = NULL;
6602         __u32 mdts[LMV_MAX_STRIPE_COUNT] = { 0 };
6603         char *end;
6604         int c;
6605         char *mode_opt = NULL;
6606         bool default_stripe = false;
6607         bool delete = false;
6608         bool foreign_mode = false;
6609         mode_t mode = S_IRWXU | S_IRWXG | S_IRWXO;
6610         mode_t previous_mode = 0;
6611         char *xattr = NULL;
6612         __u32 type = LU_FOREIGN_TYPE_SYMLINK, flags = 0;
6613         int max_inherit = LAYOUT_INHERIT_UNSET;
6614         int max_inherit_rr = LAYOUT_INHERIT_UNSET;
6615         struct option long_opts[] = {
6616         { .val = 'c',   .name = "count",        .has_arg = required_argument },
6617         { .val = 'c',   .name = "mdt-count",    .has_arg = required_argument },
6618         { .val = 'd',   .name = "delete",       .has_arg = no_argument },
6619         { .val = 'D',   .name = "default",      .has_arg = no_argument },
6620         { .val = 'D',   .name = "default_stripe", .has_arg = no_argument },
6621         { .val = LFS_LAYOUT_FLAGS_OPT,
6622                         .name = "flags",        .has_arg = required_argument },
6623         { .val = LFS_LAYOUT_FOREIGN_OPT,
6624                         .name = "foreign",      .has_arg = optional_argument},
6625         { .val = 'h',   .name = "help",         .has_arg = no_argument },
6626         { .val = 'H',   .name = "mdt-hash",     .has_arg = required_argument },
6627 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 17, 53, 0)
6628         { .val = 'i',   .name = "mdt-index",    .has_arg = required_argument },
6629         { .val = 'i',   .name = "mdt",          .has_arg = required_argument },
6630 #else
6631 /* find { .val = 'l',   .name = "lazy",         .has_arg = no_argument }, */
6632         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument },
6633         { .val = 'm',   .name = "mdt",          .has_arg = required_argument },
6634 #endif
6635 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
6636         { .val = 'i',   .name = "index",        .has_arg = required_argument },
6637 #endif
6638         { .val = 'o',   .name = "mode",         .has_arg = required_argument },
6639 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
6640         { .val = 't',   .name = "hash-type",    .has_arg = required_argument },
6641 #endif
6642         { .val = 'T',   .name = "mdt-count",    .has_arg = required_argument },
6643         { .val = 'x',   .name = "xattr",        .has_arg = required_argument },
6644         { .val = 'X',   .name = "max-inherit",  .has_arg = required_argument },
6645         { .val = LFS_INHERIT_RR_OPT,
6646                         .name = "max-inherit-rr", .has_arg = required_argument},
6647 /* setstripe { .val = 'y', .name = "yaml",      .has_arg = no_argument }, */
6648         { .name = NULL } };
6649         int result = 0;
6650
6651         setstripe_args_init(&lsa);
6652
6653         while ((c = getopt_long(argc, argv, "c:dDi:hH:m:o:t:T:x:X:",
6654                                 long_opts, NULL)) >= 0) {
6655                 switch (c) {
6656                 case 0:
6657                         /* Long options. */
6658                         break;
6659                 case 'c':
6660                 case 'T':
6661                         errno = 0;
6662                         lsa.lsa_stripe_count = strtoul(optarg, &end, 0);
6663                         if (errno != 0 || *end != '\0' ||
6664                             lsa.lsa_stripe_count < -1 ||
6665                             lsa.lsa_stripe_count > LOV_MAX_STRIPE_COUNT) {
6666                                 fprintf(stderr,
6667                                         "%s: invalid stripe count '%s'\n",
6668                                         progname, optarg);
6669                                 return CMD_HELP;
6670                         }
6671                         break;
6672                 case 'd':
6673                         delete = true;
6674                         default_stripe = true;
6675                         break;
6676                 case 'D':
6677                         default_stripe = true;
6678                         break;
6679                 case LFS_LAYOUT_FOREIGN_OPT:
6680                         if (optarg) {
6681                                 /* check pure numeric */
6682                                 type = strtoul(optarg, &end, 0);
6683                                 if (*end) {
6684                                         /* check name */
6685                                         type = check_foreign_type_name(optarg);
6686                                         if (type == LU_FOREIGN_TYPE_UNKNOWN) {
6687                                                 fprintf(stderr,
6688                                                         "%s %s: unknown foreign type '%s'\n",
6689                                                         progname, argv[0],
6690                                                         optarg);
6691                                                 return CMD_HELP;
6692                                         }
6693                                 } else if (type >= UINT32_MAX) {
6694                                         fprintf(stderr,
6695                                                 "%s %s: invalid foreign type '%s'\n",
6696                                                 progname, argv[0], optarg);
6697                                         return CMD_HELP;
6698                                 }
6699                         }
6700                         foreign_mode = true;
6701                         break;
6702                 case LFS_LAYOUT_FLAGS_OPT:
6703                         errno = 0;
6704                         flags = strtoul(optarg, &end, 16);
6705                         if (errno != 0 || *end != '\0' ||
6706                             flags >= UINT32_MAX) {
6707                                 fprintf(stderr,
6708                                         "%s %s: invalid hex flags '%s'\n",
6709                                         progname, argv[0], optarg);
6710                                 return CMD_HELP;
6711                         }
6712                         if (!foreign_mode) {
6713                                 fprintf(stderr,
6714                                         "%s %s: hex flags must be specified with --foreign option\n",
6715                                         progname, argv[0]);
6716                                 return CMD_HELP;
6717                         }
6718                         break;
6719 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
6720                 case 't':
6721                         fprintf(stderr,
6722                                 "warning: '--hash-type' and '-t' deprecated, use '--mdt-hash' or '-H' instead\n");
6723                         /* fallthrough */
6724 #endif
6725                 case 'H':
6726                         lsa.lsa_pattern = check_hashtype(optarg);
6727                         if (lsa.lsa_pattern == 0) {
6728                                 fprintf(stderr,
6729                                         "%s %s: bad stripe hash type '%s'\n",
6730                                         progname, argv[0], optarg);
6731                                 return CMD_HELP;
6732                         }
6733                         break;
6734                 case 'i':
6735 #if LUSTRE_VERSION_CODE >= OBD_OCD_VERSION(2, 17, 53, 0)
6736                 case 'm':
6737 #endif
6738 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
6739                         if (strcmp(argv[optind - 1], "--index") == 0)
6740                                 fprintf(stderr,
6741                                         "%s %s: warning: '--index' deprecated, use '--mdt-index' instead\n",
6742                                         progname, argv[0]);
6743 #endif
6744                         lsa.lsa_nr_tgts = parse_targets(mdts,
6745                                                 sizeof(mdts) / sizeof(__u32),
6746                                                 lsa.lsa_nr_tgts, optarg, NULL);
6747                         if (lsa.lsa_nr_tgts < 0) {
6748                                 fprintf(stderr,
6749                                         "%s %s: invalid MDT target(s) '%s'\n",
6750                                         progname, argv[0], optarg);
6751                                 return CMD_HELP;
6752                         }
6753
6754                         lsa.lsa_tgts = mdts;
6755                         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
6756                                 lsa.lsa_stripe_off = mdts[0];
6757                         break;
6758 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 15, 53, 0)
6759                 case 'm':
6760                         fprintf(stderr,
6761                                 "warning: '-m' is deprecated, use '--mode' or '-o' instead\n");
6762 #endif
6763                 case 'o':
6764                         mode_opt = optarg;
6765                         break;
6766                 case 'x':
6767                         xattr = optarg;
6768                         break;
6769                 case 'X':
6770                         errno = 0;
6771                         max_inherit = strtol(optarg, &end, 10);
6772                         if (errno != 0 || *end != '\0' || max_inherit < -2) {
6773                                 fprintf(stderr,
6774                                         "%s %s: invalid max-inherit '%s'\n",
6775                                         progname, argv[0], optarg);
6776                                 return CMD_HELP;
6777                         }
6778                         if (max_inherit == 0) {
6779                                 max_inherit = LMV_INHERIT_NONE;
6780                         } else if (max_inherit == -1) {
6781                                 max_inherit = LMV_INHERIT_UNLIMITED;
6782                         } else if (max_inherit > LMV_INHERIT_MAX) {
6783                                 fprintf(stderr,
6784                                         "%s %s: max-inherit %d exceeds maximum %u\n",
6785                                         progname, argv[0], max_inherit,
6786                                         LMV_INHERIT_MAX);
6787                                 return CMD_HELP;
6788                         }
6789                         break;
6790                 case LFS_INHERIT_RR_OPT:
6791                         if (!default_stripe) {
6792                                 fprintf(stderr,
6793                                         "%s %s: '--max-inherit-rr' must be specified with '-D'\n",
6794                                         progname, argv[0]);
6795                                 return CMD_HELP;
6796                         }
6797                         errno = 0;
6798                         max_inherit_rr = strtol(optarg, &end, 10);
6799                         if (errno != 0 || *end != '\0' || max_inherit_rr < -2) {
6800                                 fprintf(stderr,
6801                                         "%s %s: invalid max-inherit-rr '%s'\n",
6802                                         progname, argv[0], optarg);
6803                                 return CMD_HELP;
6804                         }
6805                         if (max_inherit_rr == 0) {
6806                                 max_inherit_rr = LMV_INHERIT_RR_NONE;
6807                         } else if (max_inherit_rr == -1) {
6808                                 max_inherit_rr = LMV_INHERIT_RR_UNLIMITED;
6809                         } else if (max_inherit_rr > LMV_INHERIT_RR_MAX) {
6810                                 fprintf(stderr,
6811                                         "%s %s: max-inherit-rr %d exceeds maximum %u\n",
6812                                         progname, argv[0], max_inherit_rr,
6813                                         LMV_INHERIT_RR_MAX);
6814                                 return CMD_HELP;
6815                         }
6816                         break;
6817                 default:
6818                         fprintf(stderr, "%s: unrecognized option '%s'\n",
6819                                 progname, argv[optind - 1]);
6820                         /* fallthrough */
6821                 case 'h':
6822                         return CMD_HELP;
6823                 }
6824         }
6825
6826         if (optind == argc) {
6827                 fprintf(stderr, "%s %s: DIR must be specified\n",
6828                         progname, argv[0]);
6829                 return CMD_HELP;
6830         }
6831
6832         if (xattr && !foreign_mode) {
6833                 /*
6834                  * only print a warning as this is armless and will be
6835                  * ignored
6836                  */
6837                 fprintf(stderr,
6838                         "%s %s: xattr has been specified for non-foreign layout\n",
6839                         progname, argv[0]);
6840         } else if (foreign_mode && !xattr) {
6841                 fprintf(stderr,
6842                         "%s %s: xattr must be provided in foreign mode\n",
6843                         progname, argv[0]);
6844                 return CMD_HELP;
6845         }
6846
6847         if (foreign_mode && (delete || default_stripe || lsa.lsa_nr_tgts ||
6848             lsa.lsa_tgts || setstripe_args_specified(&lsa))) {
6849                 fprintf(stderr,
6850                         "%s %s: only --xattr/--flags/--mode options are valid with --foreign\n",
6851                         progname, argv[0]);
6852                 return CMD_HELP;
6853         }
6854
6855         if (!delete && lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT &&
6856             lsa.lsa_stripe_count == LLAPI_LAYOUT_DEFAULT && !foreign_mode) {
6857                 /* if no parameters set, create directory on least-used MDTs */
6858                 lsa.lsa_stripe_off = LMV_OFFSET_DEFAULT;
6859                 lsa.lsa_stripe_count = 1;
6860         }
6861
6862         if (delete &&
6863             (lsa.lsa_stripe_off != LLAPI_LAYOUT_DEFAULT ||
6864              lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT)) {
6865                 fprintf(stderr,
6866                         "%s %s: cannot specify -d with -c or -i options\n",
6867                         progname, argv[0]);
6868                 return CMD_HELP;
6869         }
6870
6871         if (mode_opt) {
6872                 mode = strtoul(mode_opt, &end, 8);
6873                 if (*end != '\0') {
6874                         fprintf(stderr,
6875                                 "%s %s: bad MODE '%s'\n",
6876                                 progname, argv[0], mode_opt);
6877                         return CMD_HELP;
6878                 }
6879                 previous_mode = umask(0);
6880         }
6881
6882         if (max_inherit_rr != LAYOUT_INHERIT_UNSET &&
6883             lsa.lsa_stripe_off != LLAPI_LAYOUT_DEFAULT &&
6884             lsa.lsa_stripe_off != LMV_OFFSET_DEFAULT) {
6885                 fprintf(stderr,
6886                         "%s %s: max-inherit-rr needs mdt-index=-1, not %lld\n",
6887                         progname, argv[0], lsa.lsa_stripe_off);
6888                 return CMD_HELP;
6889         }
6890
6891         /* foreign LMV/dir case */
6892         if (foreign_mode) {
6893                 if (argc > optind + 1) {
6894                         fprintf(stderr,
6895                                 "%s %s: cannot specify multiple foreign dirs\n",
6896                                 progname, argv[0]);
6897                         return CMD_HELP;
6898                 }
6899
6900                 dname = argv[optind];
6901                 result = llapi_dir_create_foreign(dname, mode, type, flags,
6902                                                   xattr);
6903                 if (result != 0)
6904                         fprintf(stderr,
6905                                 "%s mkdir: can't create foreign dir '%s': %s\n",
6906                                 progname, dname, strerror(-result));
6907                 return result;
6908         }
6909
6910         /*
6911          * initialize stripe parameters, in case param is converted to specific,
6912          * i.e, 'lfs mkdir -i -1 -c N', always allocate space for lsp_tgts.
6913          */
6914         param = calloc(1, offsetof(typeof(*param),
6915                        lsp_tgts[lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT ?
6916                                 lsa.lsa_stripe_count : lsa.lsa_nr_tgts]));
6917         if (!param) {
6918                 fprintf(stderr,
6919                         "%s %s: cannot allocate memory for parameters: %s\n",
6920                         progname, argv[0], strerror(ENOMEM));
6921                 return CMD_HELP;
6922         }
6923
6924         /* if "lfs setdirstripe -D -i -1" is used, assume 1-stripe directory */
6925         if (default_stripe && lsa.lsa_stripe_off == LMV_OFFSET_DEFAULT &&
6926             (lsa.lsa_stripe_count == LLAPI_LAYOUT_DEFAULT ||
6927              lsa.lsa_stripe_count == 0))
6928                 lsa.lsa_stripe_count = 1;
6929         if (lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT)
6930                 param->lsp_stripe_count = lsa.lsa_stripe_count;
6931         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
6932                 param->lsp_stripe_offset = LMV_OFFSET_DEFAULT;
6933         else
6934                 param->lsp_stripe_offset = lsa.lsa_stripe_off;
6935         if (lsa.lsa_pattern != LLAPI_LAYOUT_RAID0)
6936                 param->lsp_stripe_pattern = lsa.lsa_pattern;
6937         else
6938                 param->lsp_stripe_pattern = LMV_HASH_TYPE_UNKNOWN;
6939         param->lsp_pool = lsa.lsa_pool_name;
6940         param->lsp_is_specific = false;
6941         if (max_inherit == LAYOUT_INHERIT_UNSET)
6942                 max_inherit = LMV_INHERIT_DEFAULT;
6943         param->lsp_max_inherit = max_inherit;
6944         if (default_stripe) {
6945                 if (max_inherit_rr == LAYOUT_INHERIT_UNSET)
6946                         max_inherit_rr = LMV_INHERIT_RR_DEFAULT;
6947                 param->lsp_max_inherit_rr = max_inherit_rr;
6948         }
6949         if (strcmp(argv[0], "mkdir") == 0)
6950                 param->lsp_is_create = true;
6951         if (lsa.lsa_nr_tgts > 1) {
6952                 if (lsa.lsa_stripe_count > 0 &&
6953                     lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT &&
6954                     lsa.lsa_stripe_count != lsa.lsa_nr_tgts) {
6955                         fprintf(stderr,
6956                                 "error: %s: stripe count %lld doesn't match the number of MDTs: %d\n",
6957                                 argv[0], lsa.lsa_stripe_count,
6958                                 lsa.lsa_nr_tgts);
6959                         free(param);
6960                         return CMD_HELP;
6961                 }
6962
6963                 param->lsp_is_specific = true;
6964                 param->lsp_stripe_count = lsa.lsa_nr_tgts;
6965                 memcpy(param->lsp_tgts, mdts, sizeof(*mdts) * lsa.lsa_nr_tgts);
6966         }
6967
6968         dname = argv[optind];
6969         do {
6970                 if (default_stripe) {
6971                         result = llapi_dir_set_default_lmv(dname, param);
6972                         if (result)
6973                                 fprintf(stderr,
6974                                         "%s setdirstripe: cannot set default stripe on dir '%s': %s\n",
6975                                         progname, dname, strerror(-result));
6976                         continue;
6977                 }
6978
6979                 result = llapi_dir_create(dname, mode, param);
6980                 if (result)
6981                         fprintf(stderr,
6982                                 "%s setdirstripe: cannot create dir '%s': %s\n",
6983                                 progname, dname, strerror(-result));
6984         } while (!result && (dname = argv[++optind]));
6985
6986         if (mode_opt)
6987                 umask(previous_mode);
6988
6989         free(param);
6990         return result;
6991 }
6992
6993 /* functions */
6994 static int lfs_rmentry(int argc, char **argv)
6995 {
6996         char *dname;
6997         int   index;
6998         int   result = 0;
6999
7000         if (argc <= 1) {
7001                 fprintf(stderr, "error: %s: missing dirname\n",
7002                         argv[0]);
7003                 return CMD_HELP;
7004         }
7005
7006         index = 1;
7007         dname = argv[index];
7008         while (dname) {
7009                 result = llapi_direntry_remove(dname);
7010                 if (result) {
7011                         fprintf(stderr,
7012                                 "error: %s: remove dir entry '%s' failed\n",
7013                                 argv[0], dname);
7014                         break;
7015                 }
7016                 dname = argv[++index];
7017         }
7018         return result;
7019 }
7020
7021 static int lfs_unlink_foreign(int argc, char **argv)
7022 {
7023         char *name;
7024         int   index;
7025         int   result = 0;
7026
7027         if (argc <= 1) {
7028                 fprintf(stderr, "error: %s: missing pathname\n",
7029                         argv[0]);
7030                 return CMD_HELP;
7031         }
7032
7033         index = 1;
7034         name = argv[index];
7035         while (name != NULL) {
7036                 result = llapi_unlink_foreign(name);
7037                 if (result) {
7038                         fprintf(stderr,
7039                                 "error: %s: unlink foreign entry '%s' failed\n",
7040                                 argv[0], name);
7041                         break;
7042                 }
7043                 name = argv[++index];
7044         }
7045         return result;
7046 }
7047
7048 static int lfs_mv(int argc, char **argv)
7049 {
7050         struct lmv_user_md lmu = { LMV_USER_MAGIC };
7051         struct find_param param = {
7052                 .fp_max_depth = -1,
7053                 .fp_mdt_index = -1,
7054         };
7055         char *end;
7056         int c;
7057         int rc = 0;
7058         struct option long_opts[] = {
7059         { .val = 'm',   .name = "mdt",          .has_arg = required_argument },
7060         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument },
7061         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
7062         { .name = NULL } };
7063
7064         while ((c = getopt_long(argc, argv, "m:M:v", long_opts, NULL)) != -1) {
7065                 switch (c) {
7066 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
7067                 case 'M':
7068                         fprintf(stderr,
7069                                 "warning: '-M' deprecated, use '--mdt-index' or '-m' instead\n");
7070 #endif
7071                 case 'm':
7072                         errno = 0;
7073                         lmu.lum_stripe_offset = strtoul(optarg, &end, 0);
7074                         if (errno != 0 || *end != '\0' ||
7075                             lmu.lum_stripe_offset >= UINT32_MAX) {
7076                                 fprintf(stderr, "%s mv: bad MDT index '%s'\n",
7077                                         progname, optarg);
7078                                 return CMD_HELP;
7079                         }
7080                         break;
7081                 case 'v':
7082                         param.fp_verbose = VERBOSE_DETAIL;
7083                         break;
7084                 default:
7085                         fprintf(stderr, "%s mv: unrecognized option '%s'\n",
7086                                 progname, argv[optind - 1]);
7087                         return CMD_HELP;
7088                 }
7089         }
7090
7091         if (lmu.lum_stripe_offset == LMV_OFFSET_DEFAULT) {
7092                 fprintf(stderr, "%s mv: MDT index must be specified\n",
7093                         progname);
7094                 return CMD_HELP;
7095         }
7096
7097         if (optind >= argc) {
7098                 fprintf(stderr, "%s mv: DIR must be specified\n", progname);
7099                 return CMD_HELP;
7100         }
7101
7102         lmu.lum_hash_type = LMV_HASH_TYPE_UNKNOWN;
7103
7104         /* initialize migrate mdt parameters */
7105         param.fp_lmv_md = &lmu;
7106         param.fp_migrate = 1;
7107         rc = llapi_migrate_mdt(argv[optind], &param);
7108         if (rc != 0)
7109                 fprintf(stderr, "%s mv: cannot migrate '%s' to MDT%04x: %s\n",
7110                         progname, argv[optind], lmu.lum_stripe_offset,
7111                         strerror(-rc));
7112         return rc;
7113 }
7114
7115 static int lfs_osts(int argc, char **argv)
7116 {
7117         return lfs_tgts(argc, argv);
7118 }
7119
7120 static int lfs_mdts(int argc, char **argv)
7121 {
7122         return lfs_tgts(argc, argv);
7123 }
7124
7125 static int lfs_df(int argc, char **argv)
7126 {
7127         char mntdir[PATH_MAX] = {'\0'}, path[PATH_MAX] = {'\0'};
7128         enum mntdf_flags flags = MNTDF_SHOW;
7129         int ops = LL_STATFS_LMV | LL_STATFS_LOV;
7130         int c, rc = 0, rc1 = 0, index = 0, arg_idx = 0;
7131         char fsname[PATH_MAX] = "", *pool_name = NULL;
7132         struct option long_opts[] = {
7133         { .val = 'h',   .name = "human-readable", .has_arg = no_argument },
7134         { .val = 'H',   .name = "si",           .has_arg = no_argument },
7135         { .val = 'i',   .name = "inodes",       .has_arg = no_argument },
7136         { .val = 'l',   .name = "lazy",         .has_arg = no_argument },
7137         { .val = 'p',   .name = "pool",         .has_arg = required_argument },
7138         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
7139         { .name = NULL} };
7140
7141         while ((c = getopt_long(argc, argv, "hHilp:v", long_opts, NULL)) != -1) {
7142                 switch (c) {
7143                 case 'h':
7144                         flags = (flags & ~MNTDF_DECIMAL) | MNTDF_COOKED;
7145                         break;
7146                 case 'H':
7147                         flags |= MNTDF_COOKED | MNTDF_DECIMAL;
7148                         break;
7149                 case 'i':
7150                         flags |= MNTDF_INODES;
7151                         break;
7152                 case 'l':
7153                         flags |= MNTDF_LAZY;
7154                         break;
7155                 case 'p':
7156                         pool_name = optarg;
7157                         break;
7158                 case 'v':
7159                         flags |= MNTDF_VERBOSE;
7160                         break;
7161                 default:
7162                         fprintf(stderr, "%s: unrecognized option '%s'\n",
7163                                 progname, argv[optind - 1]);
7164                         return CMD_HELP;
7165                 }
7166         }
7167
7168         /* Handle case where path is not specified */
7169         if (optind == argc) {
7170                 while (!llapi_search_mounts(path, index++, mntdir, fsname)) {
7171                         /* Check if we have a mount point */
7172                         if (mntdir[0] == '\0')
7173                                 continue;
7174
7175                         rc = mntdf(mntdir, fsname, pool_name, flags, ops, NULL);
7176                         if (rc || path[0] != '\0')
7177                                 break;
7178
7179                         fsname[0] = '\0'; /* avoid matching in next loop */
7180                         mntdir[0] = '\0'; /* avoid matching in next loop */
7181                         path[0] = '\0'; /* clean for next loop */
7182                 }
7183                 return rc;
7184         }
7185
7186         /* Loop through all the remaining arguments. These are Lustre FS
7187          * paths.
7188          */
7189         for (arg_idx = optind; arg_idx <= argc - 1; arg_idx++) {
7190                 bool valid = false;
7191
7192                 fsname[0] = '\0'; /* start clean */
7193                 mntdir[0] = '\0'; /* start clean */
7194                 path[0] = '\0';   /* start clean */
7195
7196                 /* path does not exists at all */
7197                 if (!realpath(argv[arg_idx], path)) {
7198                         rc = -errno;
7199                         fprintf(stderr, "error: invalid path '%s': %s\n",
7200                                 argv[arg_idx], strerror(-rc));
7201                         /* save first seen error */
7202                         if (!rc1)
7203                                 rc1 = rc;
7204
7205                         continue;
7206                 }
7207
7208                 /* path exists but may not be a Lustre filesystem */
7209                 while (!llapi_search_mounts(path, index++, mntdir, fsname)) {
7210                         /* Check if we have a mount point */
7211                         if (mntdir[0] == '\0')
7212                                 continue;
7213
7214                         rc = mntdf(mntdir, fsname, pool_name, flags, ops, NULL);
7215                         if (rc || path[0] != '\0') {
7216                                 valid = true;
7217
7218                                 /* save first seen error */
7219                                 if (!rc1)
7220                                         rc1 = rc;
7221                                 break;
7222                         }
7223                 }
7224
7225                 if (!valid) {
7226                         llapi_printf(LLAPI_MSG_ERROR,
7227                                      "%s:%s Not a Lustre filesystem\n",
7228                                      argv[0], argv[arg_idx]);
7229                         /* save first seen error */
7230                         if (!rc1)
7231                                 rc1 = -EOPNOTSUPP;
7232                 }
7233         }
7234
7235         return rc1;
7236 }
7237
7238 static int print_instance(const char *mntdir, char *buf, size_t buflen,
7239                           bool opt_instance, bool opt_fsname, bool opt_mntdir)
7240 {
7241         int rc = 0;
7242
7243         if (opt_fsname == opt_instance) { /* both true or both false */
7244                 rc = llapi_getname(mntdir, buf, buflen);
7245         } else if (opt_fsname) {
7246                 /*
7247                  * llapi_search_mounts() fills @buf with fsname, but that is not
7248                  * called if explicit paths are specified on the command-line
7249                  */
7250                 if (buf[0] == '\0')
7251                         rc = llapi_get_fsname(mntdir, buf, buflen);
7252         } else /* if (opt_instance) */ {
7253                 rc = llapi_get_instance(mntdir, buf, buflen);
7254         }
7255
7256         if (rc < 0) {
7257                 fprintf(stderr, "cannot get instance for '%s': %s\n",
7258                         mntdir, strerror(-rc));
7259                 return rc;
7260         }
7261
7262         if (opt_mntdir)
7263                 printf("%s %s\n", buf, mntdir);
7264         else
7265                 printf("%s\n", buf);
7266
7267         return 0;
7268 }
7269
7270 static int lfs_getname(int argc, char **argv)
7271 {
7272         struct option long_opts[] = {
7273         { .val = 'h',   .name = "help",         .has_arg = no_argument },
7274         { .val = 'i',   .name = "instance",     .has_arg = no_argument },
7275         { .val = 'n',   .name = "fsname",       .has_arg = no_argument },
7276         { .name = NULL} };
7277         bool opt_instance = false, opt_fsname = false;
7278         char fsname[PATH_MAX] = "";
7279         int rc = 0, rc2, c;
7280
7281         while ((c = getopt_long(argc, argv, "hin", long_opts, NULL)) != -1) {
7282                 switch (c) {
7283                 case 'i':
7284                         opt_instance = true;
7285                         break;
7286                 case 'n':
7287                         opt_fsname = true;
7288                         break;
7289                 default:
7290                         fprintf(stderr, "%s: unrecognized option '%s'\n",
7291                                 progname, argv[optind - 1]);
7292                         /* fallthrough */
7293                 case 'h':
7294                         return CMD_HELP;
7295                 }
7296         }
7297
7298         if (optind == argc) { /* no paths specified, get all paths. */
7299                 char mntdir[PATH_MAX] = "", path[PATH_MAX] = "";
7300                 int index = 0;
7301
7302                 while (!llapi_search_mounts(path, index++, mntdir, fsname)) {
7303                         rc2 = print_instance(mntdir, fsname, sizeof(fsname),
7304                                              opt_instance, opt_fsname, true);
7305                         if (!rc)
7306                                 rc = rc2;
7307                         path[0] = fsname[0] = mntdir[0] = '\0';
7308                 }
7309         } else { /* paths specified, only attempt to search these. */
7310                 bool opt_mntdir;
7311
7312                 /* if only one path is given, print only requested info */
7313                 opt_mntdir = argc - optind > 1 || (opt_instance == opt_fsname);
7314
7315                 for (; optind < argc; optind++) {
7316                         rc2 = print_instance(argv[optind], fsname,
7317                                              sizeof(fsname), opt_instance,
7318                                              opt_fsname, opt_mntdir);
7319                         if (!rc)
7320                                 rc = rc2;
7321                         fsname[0] = '\0';
7322                 }
7323         }
7324
7325         return rc;
7326 }
7327
7328 static int lfs_check(int argc, char **argv)
7329 {
7330         char mntdir[PATH_MAX] = {'\0'};
7331         int num_types = 1;
7332         char *obd_types[3];
7333         char obd_type1[4];
7334         char obd_type2[4];
7335         char obd_type3[4];
7336         int rc;
7337
7338         if (argc != 2) {
7339                 fprintf(stderr, "%s check: server type must be specified\n",
7340                         progname);
7341                 return CMD_HELP;
7342         }
7343
7344         obd_types[0] = obd_type1;
7345         obd_types[1] = obd_type2;
7346         obd_types[2] = obd_type3;
7347
7348         if (strcmp(argv[1], "osts") == 0) {
7349                 strcpy(obd_types[0], "osc");
7350         } else if (strcmp(argv[1], "mdts") == 0 ||
7351                    strcmp(argv[1], "mds") == 0) {
7352                 strcpy(obd_types[0], "mdc");
7353         } else if (strcmp(argv[1], "mgts") == 0) {
7354                 strcpy(obd_types[0], "mgc");
7355         } else if (strcmp(argv[1], "all") == 0 ||
7356                    strcmp(argv[1], "servers") == 0) {
7357                 num_types = 3;
7358                 strcpy(obd_types[0], "osc");
7359                 strcpy(obd_types[1], "mdc");
7360                 strcpy(obd_types[2], "mgc");
7361         } else {
7362                 fprintf(stderr, "%s check: unrecognized option '%s'\n",
7363                         progname, argv[1]);
7364                 return CMD_HELP;
7365         }
7366
7367         rc = llapi_search_mounts(NULL, 0, mntdir, NULL);
7368         if (rc < 0 || mntdir[0] == '\0') {
7369                 fprintf(stderr,
7370                         "%s check: cannot find mounted Lustre filesystem: %s\n",
7371                         progname, (rc < 0) ? strerror(-rc) : strerror(ENODEV));
7372                 return rc;
7373         }
7374
7375         rc = llapi_target_check(num_types, obd_types, mntdir);
7376         if (rc)
7377                 fprintf(stderr, "%s check: cannot check target '%s': %s\n",
7378                         progname, argv[1], strerror(-rc));
7379
7380         return rc;
7381 }
7382
7383 #ifdef HAVE_SYS_QUOTA_H
7384 #define ADD_OVERFLOW(a, b) \
7385                      ((((a) + (b)) < (a)) ? \
7386                       ((a) = ULONG_MAX) : ((a) = (a) + (b)))
7387
7388 /* Convert format time string "XXwXXdXXhXXmXXs" into seconds value
7389  * returns the value or ULONG_MAX on integer overflow or incorrect format
7390  * Notes:
7391  *        1. the order of specifiers is arbitrary (may be: 5w3s or 3s5w)
7392  *        2. specifiers may be encountered multiple times (2s3s is 5 seconds)
7393  *        3. empty integer value is interpreted as 0
7394  */
7395 static unsigned long str2sec(const char *timestr)
7396 {
7397         const char spec[] = "smhdw";
7398         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
7399         unsigned long val = 0;
7400         char *tail;
7401
7402         if (strpbrk(timestr, spec) == NULL) {
7403                 /*
7404                  * no specifiers inside the time string,
7405                  * should treat it as an integer value
7406                  */
7407                 val = strtoul(timestr, &tail, 10);
7408                 return *tail ? ULONG_MAX : val;
7409         }
7410
7411         /* format string is XXwXXdXXhXXmXXs */
7412         while (*timestr) {
7413                 unsigned long v;
7414                 int ind;
7415                 char *ptr;
7416
7417                 v = strtoul(timestr, &tail, 10);
7418                 if (v == ULONG_MAX || *tail == '\0')
7419                         /*
7420                          * value too large (ULONG_MAX or more)
7421                          * or missing specifier
7422                          */
7423                         goto error;
7424
7425                 ptr = strchr(spec, *tail);
7426                 if (!ptr)
7427                         /* unknown specifier */
7428                         goto error;
7429
7430                 ind = ptr - spec;
7431
7432                 /* check if product will overflow the type */
7433                 if (!(v < ULONG_MAX / mult[ind]))
7434                         goto error;
7435
7436                 ADD_OVERFLOW(val, mult[ind] * v);
7437                 if (val == ULONG_MAX)
7438                         goto error;
7439
7440                 timestr = tail + 1;
7441         }
7442
7443         return val;
7444
7445 error:
7446         return ULONG_MAX;
7447 }
7448
7449 #define ARG2ULL(nr, str, def_units)                                     \
7450 do {                                                                    \
7451         unsigned long long limit, units = def_units;                    \
7452         int rc;                                                         \
7453                                                                         \
7454         rc = llapi_parse_size(str, &limit, &units, 1);                  \
7455         if (rc < 0) {                                                   \
7456                 fprintf(stderr, "%s: invalid limit '%s'\n",             \
7457                         progname, str);                                 \
7458                 return CMD_HELP;                                        \
7459         }                                                               \
7460         nr = limit;                                                     \
7461 } while (0)
7462
7463 static inline int has_times_option(int argc, char **argv)
7464 {
7465         int i;
7466
7467         for (i = 1; i < argc; i++)
7468                 if (!strcmp(argv[i], "-t"))
7469                         return 1;
7470
7471         return 0;
7472 }
7473
7474 static inline int lfs_verify_poolarg(char *pool)
7475 {
7476         if (strnlen(optarg, LOV_MAXPOOLNAME + 1) > LOV_MAXPOOLNAME) {
7477                 fprintf(stderr,
7478                         "Pool name '%.*s' is longer than %d\n",
7479                         LOV_MAXPOOLNAME, pool, LOV_MAXPOOLNAME);
7480                 return 1;
7481         }
7482         return 0;
7483 }
7484
7485 /* special grace time, only notify the user when its quota is over soft limit
7486  * but doesn't block new writes until the hard limit is reached.
7487  */
7488 #define NOTIFY_GRACE            "notify"
7489 #define NOTIFY_GRACE_TIME       LQUOTA_GRACE_MASK
7490
7491 #ifndef toqb
7492 static inline __u64 lustre_stoqb(size_t space)
7493 {
7494         return (space + QIF_DQBLKSIZE - 1) >> QIF_DQBLKSIZE_BITS;
7495 }
7496 #else
7497 #define lustre_stoqb   toqb
7498 #endif
7499
7500 int lfs_setquota_times(int argc, char **argv, struct if_quotactl *qctl)
7501 {
7502         int c, rc;
7503         char *mnt, *obd_type = (char *)qctl->obd_type;
7504         struct obd_dqblk *dqb = &qctl->qc_dqblk;
7505         struct obd_dqinfo *dqi = &qctl->qc_dqinfo;
7506         struct option long_opts[] = {
7507         { .val = 'b',   .name = "block-grace",  .has_arg = required_argument },
7508         { .val = 'g',   .name = "group",        .has_arg = no_argument },
7509         { .val = 'h',   .name = "help",         .has_arg = no_argument },
7510         { .val = 'i',   .name = "inode-grace",  .has_arg = required_argument },
7511         { .val = 'p',   .name = "projid",       .has_arg = no_argument },
7512         { .val = 't',   .name = "times",        .has_arg = no_argument },
7513         { .val = 'u',   .name = "user",         .has_arg = no_argument },
7514         { .val = LFS_POOL_OPT,
7515                         .name = "pool",         .has_arg = required_argument },
7516         { .name = NULL } };
7517         int qtype;
7518
7519         qctl->qc_cmd  = LUSTRE_Q_SETINFO;
7520         qctl->qc_type = ALLQUOTA;
7521
7522         while ((c = getopt_long(argc, argv, "b:ghi:ptu",
7523                                 long_opts, NULL)) != -1) {
7524                 switch (c) {
7525                 case 'u':
7526                         qtype = USRQUOTA;
7527                         goto quota_type;
7528                 case 'g':
7529                         qtype = GRPQUOTA;
7530                         goto quota_type;
7531                 case 'p':
7532                         qtype = PRJQUOTA;
7533 quota_type:
7534                         if (qctl->qc_type != ALLQUOTA) {
7535                                 fprintf(stderr,
7536                                         "%s: -u/g/p cannot be used more than once\n",
7537                                         progname);
7538                                 return CMD_HELP;
7539                         }
7540                         qctl->qc_type = qtype;
7541                         break;
7542                 case 'b':
7543                         if (strncmp(optarg, NOTIFY_GRACE,
7544                                     strlen(NOTIFY_GRACE)) == 0) {
7545                                 dqi->dqi_bgrace = NOTIFY_GRACE_TIME;
7546                         } else {
7547                                 dqi->dqi_bgrace = str2sec(optarg);
7548                                 if (dqi->dqi_bgrace >= NOTIFY_GRACE_TIME) {
7549                                         fprintf(stderr,
7550                                                 "%s: bad block-grace: %s\n",
7551                                                 progname, optarg);
7552                                         return CMD_HELP;
7553                                 }
7554                         }
7555                         dqb->dqb_valid |= QIF_BTIME;
7556                         break;
7557                 case 'i':
7558                         if (strncmp(optarg, NOTIFY_GRACE,
7559                                     strlen(NOTIFY_GRACE)) == 0) {
7560                                 dqi->dqi_igrace = NOTIFY_GRACE_TIME;
7561                         } else {
7562                                 dqi->dqi_igrace = str2sec(optarg);
7563                                 if (dqi->dqi_igrace >= NOTIFY_GRACE_TIME) {
7564                                         fprintf(stderr,
7565                                                 "%s: bad inode-grace: %s\n",
7566                                                 progname, optarg);
7567                                         return CMD_HELP;
7568                                 }
7569                         }
7570                         dqb->dqb_valid |= QIF_ITIME;
7571                         break;
7572                 case 't': /* Yes, of course! */
7573                         break;
7574                 case LFS_POOL_OPT:
7575                         if (lfs_verify_poolarg(optarg))
7576                                 return -1;
7577                         strncpy(qctl->qc_poolname, optarg, LOV_MAXPOOLNAME);
7578                         qctl->qc_cmd  = LUSTRE_Q_SETINFOPOOL;
7579                         break;
7580                 /* getopt prints error message for us when opterr != 0 */
7581                 default:
7582                         fprintf(stderr, "%s: unrecognized option '%s'\n",
7583                                 progname, argv[optind - 1]);
7584                         /* fallthrough */
7585                 case 'h':
7586                         return CMD_HELP;
7587                 }
7588         }
7589
7590         if (qctl->qc_type == ALLQUOTA) {
7591                 fprintf(stderr, "%s: neither -u, -g nor -p specified\n",
7592                         progname);
7593                 return CMD_HELP;
7594         }
7595
7596         if (optind != argc - 1) {
7597                 fprintf(stderr, "%s: unexpected parameter '%s'\n",
7598                         progname, argv[optind + 1]);
7599                 return CMD_HELP;
7600         }
7601
7602         mnt = argv[optind];
7603         rc = llapi_quotactl(mnt, qctl);
7604         if (rc) {
7605                 if (*obd_type)
7606                         fprintf(stderr, "%s %s ", obd_type,
7607                                 obd_uuid2str(&qctl->obd_uuid));
7608                 fprintf(stderr, "setquota failed: %s\n", strerror(-rc));
7609                 return rc;
7610         }
7611
7612         return 0;
7613 }
7614
7615 #define BSLIMIT (1 << 0)
7616 #define BHLIMIT (1 << 1)
7617 #define ISLIMIT (1 << 2)
7618 #define IHLIMIT (1 << 3)
7619
7620 int lfs_setquota(int argc, char **argv)
7621 {
7622         int c, rc = 0;
7623         struct if_quotactl *qctl;
7624         char *mnt, *obd_type;
7625         struct obd_dqblk *dqb;
7626         struct option long_opts[] = {
7627         { .val = 'b',   .name = "block-softlimit",
7628                                                 .has_arg = required_argument },
7629         { .val = 'B',   .name = "block-hardlimit",
7630                                                 .has_arg = required_argument },
7631         { .val = 'd',   .name = "default",      .has_arg = no_argument },
7632         { .val = 'g',   .name = "group",        .has_arg = required_argument },
7633         { .val = 'G',   .name = "default-grp",  .has_arg = no_argument },
7634         { .val = 'h',   .name = "help",         .has_arg = no_argument },
7635         { .val = 'i',   .name = "inode-softlimit",
7636                                                 .has_arg = required_argument },
7637         { .val = 'I',   .name = "inode-hardlimit",
7638                                                 .has_arg = required_argument },
7639         { .val = 'p',   .name = "projid",       .has_arg = required_argument },
7640         { .val = 'P',   .name = "default-prj",  .has_arg = no_argument },
7641         { .val = 'u',   .name = "user",         .has_arg = required_argument },
7642         { .val = 'U',   .name = "default-usr",  .has_arg = no_argument },
7643         { .val = LFS_POOL_OPT,
7644                         .name = "pool",         .has_arg = required_argument },
7645         { .name = NULL } };
7646         unsigned int limit_mask = 0;
7647         bool use_default = false;
7648         int qtype, qctl_len;
7649
7650         qctl_len = sizeof(*qctl) + LOV_MAXPOOLNAME + 1;
7651         qctl = malloc(qctl_len);
7652         if (!qctl)
7653                 return -ENOMEM;
7654
7655         memset(qctl, 0, qctl_len);
7656         obd_type = (char *)qctl->obd_type;
7657         dqb = &qctl->qc_dqblk;
7658
7659         if (has_times_option(argc, argv)) {
7660                 rc = lfs_setquota_times(argc, argv, qctl);
7661                 goto out;
7662         }
7663
7664         qctl->qc_cmd  = LUSTRE_Q_SETQUOTA;
7665         qctl->qc_type = ALLQUOTA; /* ALLQUOTA makes no sense for setquota,
7666                                    * so it can be used as a marker that qc_type
7667                                    * isn't reinitialized from command line
7668                                    */
7669
7670         while ((c = getopt_long(argc, argv, "b:B:dg:Ghi:I:p:Pu:U",
7671                 long_opts, NULL)) != -1) {
7672                 switch (c) {
7673                 case 'U':
7674                         qctl->qc_cmd = LUSTRE_Q_SETDEFAULT;
7675                         qtype = USRQUOTA;
7676                         qctl->qc_id = 0;
7677                         goto quota_type_def;
7678                 case 'u':
7679                         qtype = USRQUOTA;
7680                         rc = name2uid(&qctl->qc_id, optarg);
7681                         goto quota_type;
7682                 case 'G':
7683                         qctl->qc_cmd = LUSTRE_Q_SETDEFAULT;
7684                         qtype = GRPQUOTA;
7685                         qctl->qc_id = 0;
7686                         goto quota_type_def;
7687                 case 'g':
7688                         qtype = GRPQUOTA;
7689                         rc = name2gid(&qctl->qc_id, optarg);
7690                         goto quota_type;
7691                 case 'P':
7692                         qctl->qc_cmd = LUSTRE_Q_SETDEFAULT;
7693                         qtype = PRJQUOTA;
7694                         qctl->qc_id = 0;
7695                         goto quota_type_def;
7696                 case 'p':
7697                         qtype = PRJQUOTA;
7698                         rc = name2projid(&qctl->qc_id, optarg);
7699 quota_type:
7700                         if (rc) {
7701                                 if (str2quotaid(&qctl->qc_id, optarg)) {
7702                                         fprintf(stderr,
7703                                                 "%s setquota: invalid id '%s'\n",
7704                                                 progname, optarg);
7705                                         rc = -1;
7706                                         goto out;
7707                                 }
7708                         }
7709
7710                         if (qctl->qc_id == 0) {
7711                                 fprintf(stderr,
7712                                         "%s setquota: can't set quota for root usr/group/project.\n",
7713                                         progname);
7714                                 rc = -1;
7715                                 goto out;
7716                         }
7717
7718 quota_type_def:
7719                         if (qctl->qc_type != ALLQUOTA) {
7720                                 fprintf(stderr,
7721                                         "%s setquota: only one of -u, -U, -g, -G, -p or -P may be specified\n",
7722                                         progname);
7723                                 rc = CMD_HELP;
7724                                 goto out;
7725                         }
7726                         qctl->qc_type = qtype;
7727                         break;
7728                 case 'd':
7729                         qctl->qc_cmd = LUSTRE_Q_SETDEFAULT;
7730                         use_default = true;
7731                         break;
7732                 case 'b':
7733                         ARG2ULL(dqb->dqb_bsoftlimit, optarg, 1024);
7734                         dqb->dqb_bsoftlimit >>= 10;
7735                         limit_mask |= BSLIMIT;
7736                         if (dqb->dqb_bsoftlimit &&
7737                             dqb->dqb_bsoftlimit <= 1024) /* <= 1M? */
7738                                 fprintf(stderr,
7739                                         "%s setquota: warning: block softlimit '%llu' smaller than minimum qunit size\nSee '%s help setquota' or Lustre manual for details\n",
7740                                         progname,
7741                                         (unsigned long long)dqb->dqb_bsoftlimit,
7742                                         progname);
7743                         break;
7744                 case 'B':
7745                         ARG2ULL(dqb->dqb_bhardlimit, optarg, 1024);
7746                         dqb->dqb_bhardlimit >>= 10;
7747                         limit_mask |= BHLIMIT;
7748                         if (dqb->dqb_bhardlimit &&
7749                             dqb->dqb_bhardlimit <= 1024) /* <= 1M? */
7750                                 fprintf(stderr,
7751                                         "%s setquota: warning: block hardlimit '%llu' smaller than minimum qunit size\n"
7752                                         "See '%s help setquota' or Lustre manual for details\n",
7753                                         progname,
7754                                         (unsigned long long)dqb->dqb_bhardlimit,
7755                                         progname);
7756                         break;
7757                 case 'i':
7758                         ARG2ULL(dqb->dqb_isoftlimit, optarg, 1);
7759                         limit_mask |= ISLIMIT;
7760                         if (dqb->dqb_isoftlimit &&
7761                             dqb->dqb_isoftlimit <= 1024) /* <= 1K inodes? */
7762                                 fprintf(stderr,
7763                                         "%s setquota: warning: inode softlimit '%llu' smaller than minimum qunit size\nSee '%s help setquota' or Lustre manual for details\n",
7764                                         progname,
7765                                         (unsigned long long)dqb->dqb_isoftlimit,
7766                                         progname);
7767                         break;
7768                 case 'I':
7769                         ARG2ULL(dqb->dqb_ihardlimit, optarg, 1);
7770                         limit_mask |= IHLIMIT;
7771                         if (dqb->dqb_ihardlimit &&
7772                             dqb->dqb_ihardlimit <= 1024) /* <= 1K inodes? */
7773                                 fprintf(stderr,
7774                                         "%s setquota: warning: inode hardlimit '%llu' smaller than minimum qunit size\nSee '%s help setquota' or Lustre manual for details\n",
7775                                         progname,
7776                                         (unsigned long long)dqb->dqb_ihardlimit,
7777                                         progname);
7778                         break;
7779                 case LFS_POOL_OPT:
7780                         if (lfs_verify_poolarg(optarg)) {
7781                                 rc = -1;
7782                                 goto out;
7783                         }
7784                         strncpy(qctl->qc_poolname, optarg, LOV_MAXPOOLNAME);
7785                         qctl->qc_cmd = qctl->qc_cmd == LUSTRE_Q_SETDEFAULT ?
7786                                                 LUSTRE_Q_SETDEFAULT_POOL :
7787                                                 LUSTRE_Q_SETQUOTAPOOL;
7788                         break;
7789                 default:
7790                         fprintf(stderr,
7791                                 "%s setquota: unrecognized option '%s'\n",
7792                                 progname, argv[optind - 1]);
7793                         /* fallthrough */
7794                 case 'h':
7795                         rc = CMD_HELP;
7796                         goto out;
7797                 }
7798         }
7799
7800         if (qctl->qc_type == ALLQUOTA) {
7801                 fprintf(stderr,
7802                         "%s setquota: either -u or -g must be specified\n",
7803                         progname);
7804                 rc = CMD_HELP;
7805                 goto out;
7806         }
7807
7808         if (!use_default && limit_mask == 0) {
7809                 fprintf(stderr,
7810                         "%s setquota: at least one limit must be specified\n",
7811                         progname);
7812                 rc = CMD_HELP;
7813                 goto out;
7814         }
7815
7816         if (use_default && limit_mask != 0) {
7817                 fprintf(stderr,
7818                         "%s setquota: limits should not be specified when using default quota\n",
7819                         progname);
7820                 rc = CMD_HELP;
7821                 goto out;
7822         }
7823
7824         if (use_default && qctl->qc_id == 0) {
7825                 fprintf(stderr,
7826                         "%s setquota: can not set default quota for root user/group/project\n",
7827                         progname);
7828                 rc = CMD_HELP;
7829                 goto out;
7830         }
7831
7832         if (optind != argc - 1) {
7833                 fprintf(stderr,
7834                         "%s setquota: filesystem not specified or unexpected argument '%s'\n",
7835                         progname, argv[optind]);
7836                 rc = CMD_HELP;
7837                 goto out;
7838         }
7839
7840         mnt = argv[optind];
7841
7842         if (use_default) {
7843                 dqb->dqb_bhardlimit = 0;
7844                 dqb->dqb_bsoftlimit = 0;
7845                 dqb->dqb_ihardlimit = 0;
7846                 dqb->dqb_isoftlimit = 0;
7847                 dqb->dqb_itime = 0;
7848                 dqb->dqb_btime = 0;
7849                 dqb->dqb_valid |= QIF_LIMITS | QIF_TIMES;
7850                 /* do not set inode limits for Pool Quotas */
7851                 if (qctl->qc_cmd  == LUSTRE_Q_SETDEFAULT_POOL)
7852                         dqb->dqb_valid ^= QIF_ILIMITS | QIF_ITIME;
7853         } else if ((!(limit_mask & BHLIMIT) ^ !(limit_mask & BSLIMIT)) ||
7854                    (!(limit_mask & IHLIMIT) ^ !(limit_mask & ISLIMIT))) {
7855                 /* sigh, we can't just set blimits/ilimits */
7856                 struct if_quotactl tmp_qctl = {.qc_cmd  = LUSTRE_Q_GETQUOTA,
7857                                                .qc_type = qctl->qc_type,
7858                                                .qc_id   = qctl->qc_id};
7859
7860                 rc = llapi_quotactl(mnt, &tmp_qctl);
7861                 if (rc < 0)
7862                         goto out;
7863
7864                 if (!(limit_mask & BHLIMIT))
7865                         dqb->dqb_bhardlimit = tmp_qctl.qc_dqblk.dqb_bhardlimit;
7866                 if (!(limit_mask & BSLIMIT))
7867                         dqb->dqb_bsoftlimit = tmp_qctl.qc_dqblk.dqb_bsoftlimit;
7868                 if (!(limit_mask & IHLIMIT))
7869                         dqb->dqb_ihardlimit = tmp_qctl.qc_dqblk.dqb_ihardlimit;
7870                 if (!(limit_mask & ISLIMIT))
7871                         dqb->dqb_isoftlimit = tmp_qctl.qc_dqblk.dqb_isoftlimit;
7872
7873                 /* Keep grace times if we have got no softlimit arguments */
7874                 if ((limit_mask & BHLIMIT) && !(limit_mask & BSLIMIT)) {
7875                         dqb->dqb_valid |= QIF_BTIME;
7876                         dqb->dqb_btime = tmp_qctl.qc_dqblk.dqb_btime;
7877                 }
7878
7879                 if ((limit_mask & IHLIMIT) && !(limit_mask & ISLIMIT)) {
7880                         dqb->dqb_valid |= QIF_ITIME;
7881                         dqb->dqb_itime = tmp_qctl.qc_dqblk.dqb_itime;
7882                 }
7883         }
7884
7885         dqb->dqb_valid |= (limit_mask & (BHLIMIT | BSLIMIT)) ? QIF_BLIMITS : 0;
7886         dqb->dqb_valid |= (limit_mask & (IHLIMIT | ISLIMIT)) ? QIF_ILIMITS : 0;
7887
7888         rc = llapi_quotactl(mnt, qctl);
7889         if (rc) {
7890                 if (*obd_type)
7891                         fprintf(stderr,
7892                                 "%s setquota: cannot quotactl '%s' '%s': %s\n",
7893                                 progname, obd_type,
7894                                 obd_uuid2str(&qctl->obd_uuid), strerror(-rc));
7895                 else
7896                         fprintf(stderr,
7897                                 "%s setquota: quotactl failed: %s\n",
7898                                 progname, strerror(-rc));
7899         }
7900 out:
7901         if (rc)
7902                 fprintf(stderr, "setquota failed: %s\n", strerror(-rc));
7903
7904         free(qctl);
7905         return rc;
7906 }
7907
7908 /* Converts seconds value into format string
7909  * result is returned in buf
7910  * Notes:
7911  *        1. result is in descenting order: 1w2d3h4m5s
7912  *        2. zero fields are not filled (except for p. 3): 5d1s
7913  *        3. zero seconds value is presented as "0s"
7914  */
7915 static char *__sec2str(time_t seconds, char *buf)
7916 {
7917         const char spec[] = "smhdw";
7918         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
7919         unsigned long c;
7920         char *tail = buf;
7921         int i;
7922
7923         for (i = ARRAY_SIZE(mult) - 1 ; i >= 0; i--) {
7924                 c = seconds / mult[i];
7925
7926                 if (c > 0 || (i == 0 && buf == tail))
7927                         tail += scnprintf(tail, 40-(tail-buf), "%lu%c", c,
7928                                           spec[i]);
7929
7930                 seconds %= mult[i];
7931         }
7932
7933         return tail;
7934 }
7935
7936 static void sec2str(time_t seconds, char *buf, int rc)
7937 {
7938         char *tail = buf;
7939
7940         if (rc)
7941                 *tail++ = '[';
7942
7943         tail = __sec2str(seconds, tail);
7944
7945         if (rc && tail - buf < 39) {
7946                 *tail++ = ']';
7947                 *tail++ = 0;
7948         }
7949 }
7950
7951 static void diff2str(time_t seconds, char *buf, time_t now)
7952 {
7953         buf[0] = 0;
7954         if (!seconds)
7955                 return;
7956         if (seconds <= now) {
7957                 strcpy(buf, "none");
7958                 return;
7959         }
7960         __sec2str(seconds - now, buf);
7961 }
7962
7963 static void print_quota_title(char *name, struct if_quotactl *qctl,
7964                               bool human_readable, bool show_default)
7965 {
7966         if (show_default) {
7967                 printf("Disk default %s quota:\n", qtype_name(qctl->qc_type));
7968                 printf("%15s %8s%8s%8s %8s%8s%8s\n",
7969                        "Filesystem", "bquota", "blimit", "bgrace",
7970                        "iquota", "ilimit", "igrace");
7971         } else {
7972                 printf("Disk quotas for %s %s (%cid %u):\n",
7973                        qtype_name(qctl->qc_type), name,
7974                        *qtype_name(qctl->qc_type), qctl->qc_id);
7975                 printf("%15s%8s %7s%8s%8s%8s %7s%8s%8s\n",
7976                        "Filesystem", human_readable ? "used" : "kbytes",
7977                        "quota", "limit", "grace",
7978                        "files", "quota", "limit", "grace");
7979         }
7980 }
7981
7982 static void kbytes2str(__u64 num, char *buf, int buflen, bool h)
7983 {
7984         if (!h) {
7985                 snprintf(buf, buflen, "%ju", (uintmax_t)num);
7986         } else {
7987                 if (num >> 40)
7988                         snprintf(buf, buflen, "%5.4gP",
7989                                  (double)num / ((__u64)1 << 40));
7990                 else if (num >> 30)
7991                         snprintf(buf, buflen, "%5.4gT",
7992                                  (double)num / (1 << 30));
7993                 else if (num >> 20)
7994                         snprintf(buf, buflen, "%5.4gG",
7995                                  (double)num / (1 << 20));
7996                 else if (num >> 10)
7997                         snprintf(buf, buflen, "%5.4gM",
7998                                  (double)num / (1 << 10));
7999                 else
8000                         snprintf(buf, buflen, "%ju%s", (uintmax_t)num, "k");
8001         }
8002 }
8003
8004 #ifdef HAVE_NATIVE_CLIENT
8005 /* In the current Lustre implementation, the grace time is either the time
8006  * or the timestamp to be used after some quota ID exceeds the soft limt,
8007  * 48 bits should be enough, its high 16 bits can be used as quota flags.
8008  */
8009 #define LQUOTA_GRACE_BITS       48
8010 #define LQUOTA_GRACE_MASK       ((1ULL << LQUOTA_GRACE_BITS) - 1)
8011 #define LQUOTA_GRACE_MAX        LQUOTA_GRACE_MASK
8012 #define LQUOTA_GRACE(t)         (t & LQUOTA_GRACE_MASK)
8013 #define LQUOTA_FLAG(t)          (t >> LQUOTA_GRACE_BITS)
8014 #define LQUOTA_GRACE_FLAG(t, f) ((__u64)t | (__u64)f << LQUOTA_GRACE_BITS)
8015 #endif
8016
8017 #define STRBUF_LEN      24
8018 static void print_quota(char *mnt, struct if_quotactl *qctl, int type,
8019                         int rc, bool h, bool show_default)
8020 {
8021         time_t now;
8022
8023         time(&now);
8024
8025         if (qctl->qc_cmd == LUSTRE_Q_GETQUOTA || qctl->qc_cmd == Q_GETOQUOTA ||
8026             qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL ||
8027             qctl->qc_cmd == LUSTRE_Q_GETDEFAULT ||
8028             qctl->qc_cmd == LUSTRE_Q_GETDEFAULT_POOL) {
8029                 int bover = 0, iover = 0;
8030                 struct obd_dqblk *dqb = &qctl->qc_dqblk;
8031                 char numbuf[3][STRBUF_LEN + 2]; /* 2 for brackets or wildcard */
8032                 char timebuf[40];
8033                 char strbuf[STRBUF_LEN];
8034
8035                 if (dqb->dqb_bhardlimit &&
8036                     lustre_stoqb(dqb->dqb_curspace) >= dqb->dqb_bhardlimit) {
8037                         bover = 1;
8038                 } else if (dqb->dqb_bsoftlimit && dqb->dqb_btime) {
8039                         if (dqb->dqb_btime > now)
8040                                 bover = 2;
8041                         else
8042                                 bover = 3;
8043                 }
8044
8045                 if (dqb->dqb_ihardlimit &&
8046                     dqb->dqb_curinodes >= dqb->dqb_ihardlimit) {
8047                         iover = 1;
8048                 } else if (dqb->dqb_isoftlimit && dqb->dqb_itime) {
8049                         if (dqb->dqb_itime > now)
8050                                 iover = 2;
8051                         else
8052                                 iover = 3;
8053                 }
8054
8055                 if (strlen(mnt) > 15)
8056                         printf("%s\n%15s", mnt, "");
8057                 else
8058                         printf("%15s", mnt);
8059
8060                 if (bover)
8061                         diff2str(dqb->dqb_btime, timebuf, now);
8062                 else if (show_default)
8063                         snprintf(timebuf, sizeof(timebuf), "%llu",
8064                                  (unsigned long long)dqb->dqb_btime);
8065
8066                 kbytes2str(lustre_stoqb(dqb->dqb_curspace),
8067                            strbuf, sizeof(strbuf), h);
8068                 if (rc == -EREMOTEIO)
8069                         sprintf(numbuf[0], "%s*", strbuf);
8070                 else
8071                         sprintf(numbuf[0], (dqb->dqb_valid & QIF_SPACE) ?
8072                                 "%s" : "[%s]", strbuf);
8073
8074                 kbytes2str(dqb->dqb_bsoftlimit, strbuf, sizeof(strbuf), h);
8075                 if (type == QC_GENERAL)
8076                         sprintf(numbuf[1], (dqb->dqb_valid & QIF_BLIMITS) ?
8077                                 "%s" : "[%s]", strbuf);
8078                 else
8079                         sprintf(numbuf[1], "%s", "-");
8080
8081                 kbytes2str(dqb->dqb_bhardlimit, strbuf, sizeof(strbuf), h);
8082                 sprintf(numbuf[2], (dqb->dqb_valid & QIF_BLIMITS) ?
8083                         "%s" : "[%s]", strbuf);
8084
8085                 if (show_default)
8086                         printf(" %6s %7s %7s", numbuf[1], numbuf[2], timebuf);
8087                 else
8088                         printf(" %7s%c %6s %7s %7s",
8089                                numbuf[0], bover ? '*' : ' ', numbuf[1],
8090                                numbuf[2], bover > 1 ? timebuf : "-");
8091
8092                 if (iover)
8093                         diff2str(dqb->dqb_itime, timebuf, now);
8094                 else if (show_default)
8095                         snprintf(timebuf, sizeof(timebuf), "%llu",
8096                                  (unsigned long long)dqb->dqb_itime);
8097
8098                 snprintf(numbuf[0], sizeof(numbuf),
8099                          (dqb->dqb_valid & QIF_INODES) ? "%ju" : "[%ju]",
8100                          (uintmax_t)dqb->dqb_curinodes);
8101
8102                 if (type == QC_GENERAL)
8103                         sprintf(numbuf[1], (dqb->dqb_valid & QIF_ILIMITS) ?
8104                                 "%ju" : "[%ju]",
8105                                 (uintmax_t)dqb->dqb_isoftlimit);
8106                 else
8107                         sprintf(numbuf[1], "%s", "-");
8108
8109                 sprintf(numbuf[2], (dqb->dqb_valid & QIF_ILIMITS) ?
8110                         "%ju" : "[%ju]", (uintmax_t)dqb->dqb_ihardlimit);
8111
8112                 if (show_default)
8113                         printf(" %6s %7s %7s", numbuf[1], numbuf[2], timebuf);
8114                 else if (type != QC_OSTIDX)
8115                         printf(" %7s%c %6s %7s %7s",
8116                                numbuf[0], iover ? '*' : ' ', numbuf[1],
8117                                numbuf[2], iover > 1 ? timebuf : "-");
8118                 else
8119                         printf(" %7s %7s %7s %7s", "-", "-", "-", "-");
8120                 printf("\n");
8121         } else if (qctl->qc_cmd == LUSTRE_Q_GETINFO || LUSTRE_Q_GETINFOPOOL ||
8122                    qctl->qc_cmd == Q_GETOINFO) {
8123                 char bgtimebuf[40];
8124                 char igtimebuf[40];
8125
8126                 if (qctl->qc_dqinfo.dqi_bgrace == NOTIFY_GRACE_TIME)
8127                         strncpy(bgtimebuf, NOTIFY_GRACE, 40);
8128                 else
8129                         sec2str(qctl->qc_dqinfo.dqi_bgrace, bgtimebuf, rc);
8130                 if (qctl->qc_dqinfo.dqi_igrace == NOTIFY_GRACE_TIME)
8131                         strncpy(igtimebuf, NOTIFY_GRACE, 40);
8132                 else
8133                         sec2str(qctl->qc_dqinfo.dqi_igrace, igtimebuf, rc);
8134
8135                 printf("Block grace time: %s; Inode grace time: %s\n",
8136                        bgtimebuf, igtimebuf);
8137         }
8138 }
8139
8140 static int tgt_name2index(const char *tgtname, unsigned int *idx)
8141 {
8142         char *dash, *endp;
8143
8144         /* format is "lustre-OST0001" */
8145         dash = memchr(tgtname, '-', LUSTRE_MAXFSNAME + 1);
8146         if (!dash) {
8147                 fprintf(stderr, "wrong tgtname format '%s'\n", tgtname);
8148                 return -EINVAL;
8149         }
8150         dash += 4;
8151
8152         *idx = strtoul(dash, &endp, 16);
8153         if (*idx > 0xffff) {
8154                 fprintf(stderr, "wrong index %s\n", tgtname);
8155                 return -ERANGE;
8156         }
8157
8158         return 0;
8159 }
8160
8161 static int print_obd_quota(char *mnt, struct if_quotactl *qctl, int is_mdt,
8162                            bool h, __u64 *total)
8163 {
8164         int rc = 0, rc1 = 0, count = 0, i = 0;
8165         char **list = NULL, *buffer = NULL;
8166         __u32 valid = qctl->qc_valid;
8167
8168         if (qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL && is_mdt)
8169                 return 0;
8170
8171         /* Is it correct for the case OST0000, OST0002, OST0003 -
8172          * we will ask OST0001 that is absent and won't ask OST0003? */
8173         rc = llapi_get_obd_count(mnt, &count, is_mdt);
8174         if (rc) {
8175                 fprintf(stderr, "can not get %s count: %s\n",
8176                         is_mdt ? "mdt" : "ost", strerror(-rc));
8177                 return rc;
8178         }
8179
8180         if (qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL) {
8181                 char fname[PATH_MAX];
8182                 char fsname[LUSTRE_MAXFSNAME + 1];
8183                 int bufsize = sizeof(struct obd_uuid) * count;
8184
8185                 rc = llapi_search_fsname(mnt, fsname);
8186                 if (rc) {
8187                         fprintf(stderr, "cannot get fsname for mountpoint %s\n",
8188                                 mnt);
8189                         goto out;
8190                 }
8191                 buffer = malloc(bufsize + sizeof(*list) * count);
8192                 if (!buffer)
8193                         return -ENOMEM;
8194                 list = (char **)(buffer + bufsize);
8195                 snprintf(fname, PATH_MAX, "%s.%s", fsname, qctl->qc_poolname);
8196                 count = llapi_get_poolmembers(fname, list, count,
8197                                               buffer, bufsize);
8198                 if (count <= 0)
8199                         goto out;
8200         }
8201
8202         for (i = 0; i < count; i++) {
8203                 if (qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL) {
8204                         unsigned int index;
8205
8206                         if (tgt_name2index(list[i], &index))
8207                                 continue;
8208                         qctl->qc_idx = index;
8209                 } else {
8210                         qctl->qc_idx = i;
8211                 }
8212
8213                 qctl->qc_valid = is_mdt ? QC_MDTIDX : QC_OSTIDX;
8214                 rc = llapi_quotactl(mnt, qctl);
8215                 if (rc) {
8216                         /* It is remote client case. */
8217                         if (rc == -EOPNOTSUPP) {
8218                                 rc = 0;
8219                                 goto out;
8220                         }
8221
8222                         if (!rc1)
8223                                 rc1 = rc;
8224                         fprintf(stderr, "quotactl %s%d failed.\n",
8225                                 is_mdt ? "mdt" : "ost", qctl->qc_idx);
8226                         continue;
8227                 }
8228
8229                 print_quota(obd_uuid2str(&qctl->obd_uuid), qctl,
8230                             qctl->qc_valid, 0, h, false);
8231                 *total += is_mdt ? qctl->qc_dqblk.dqb_ihardlimit :
8232                                    qctl->qc_dqblk.dqb_bhardlimit;
8233         }
8234 out:
8235         if (buffer)
8236                 free(buffer);
8237         qctl->qc_valid = valid;
8238         return rc ? : rc1;
8239 }
8240
8241 static int get_print_quota(char *mnt, char *name, struct if_quotactl *qctl,
8242                            int verbose, int quiet, bool human_readable,
8243                            bool show_default)
8244 {
8245         int rc1 = 0, rc2 = 0, rc3 = 0;
8246         char *obd_type = (char *)qctl->obd_type;
8247         char *obd_uuid = (char *)qctl->obd_uuid.uuid;
8248         __u64 total_ialloc = 0, total_balloc = 0;
8249         bool use_default_for_blk = false;
8250         bool use_default_for_file = false;
8251         int inacc;
8252
8253         rc1 = llapi_quotactl(mnt, qctl);
8254         if (rc1 < 0) {
8255                 switch (rc1) {
8256                 case -ESRCH:
8257                         fprintf(stderr, "%s quotas are not enabled.\n",
8258                                 qtype_name(qctl->qc_type));
8259                         goto out;
8260                 case -EPERM:
8261                         fprintf(stderr, "Permission denied.\n");
8262                 case -ENODEV:
8263                 case -ENOENT:
8264                         /* We already got error message. */
8265                         goto out;
8266                 default:
8267                         fprintf(stderr, "Unexpected quotactl error: %s\n",
8268                                 strerror(-rc1));
8269                 }
8270         }
8271
8272         if (!show_default && qctl->qc_id == 0) {
8273                 qctl->qc_dqblk.dqb_bhardlimit = 0;
8274                 qctl->qc_dqblk.dqb_bsoftlimit = 0;
8275                 qctl->qc_dqblk.dqb_ihardlimit = 0;
8276                 qctl->qc_dqblk.dqb_isoftlimit = 0;
8277                 qctl->qc_dqblk.dqb_btime = 0;
8278                 qctl->qc_dqblk.dqb_itime = 0;
8279                 qctl->qc_dqblk.dqb_valid |= QIF_LIMITS | QIF_TIMES;
8280         }
8281
8282         if (qctl->qc_dqblk.dqb_valid & QIF_BTIME &&
8283             LQUOTA_FLAG(qctl->qc_dqblk.dqb_btime) & LQUOTA_FLAG_DEFAULT) {
8284                 use_default_for_blk = true;
8285                 qctl->qc_dqblk.dqb_btime &= LQUOTA_GRACE_MASK;
8286         }
8287
8288         if (qctl->qc_dqblk.dqb_valid & QIF_ITIME &&
8289             LQUOTA_FLAG(qctl->qc_dqblk.dqb_itime) & LQUOTA_FLAG_DEFAULT) {
8290                 use_default_for_file = true;
8291                 qctl->qc_dqblk.dqb_itime &= LQUOTA_GRACE_MASK;
8292         }
8293
8294         if ((qctl->qc_cmd == LUSTRE_Q_GETQUOTA ||
8295              qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL ||
8296              qctl->qc_cmd == LUSTRE_Q_GETDEFAULT_POOL ||
8297              qctl->qc_cmd == LUSTRE_Q_GETDEFAULT) && !quiet)
8298                 print_quota_title(name, qctl, human_readable, show_default);
8299
8300         if (rc1 && *obd_type)
8301                 fprintf(stderr, "%s %s ", obd_type, obd_uuid);
8302
8303         if (qctl->qc_valid != QC_GENERAL)
8304                 mnt = "";
8305
8306         inacc = (qctl->qc_cmd == LUSTRE_Q_GETQUOTA ||
8307                  qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL) &&
8308                 ((qctl->qc_dqblk.dqb_valid & (QIF_LIMITS|QIF_USAGE)) !=
8309                  (QIF_LIMITS|QIF_USAGE));
8310
8311         print_quota(mnt, qctl, QC_GENERAL, rc1, human_readable, show_default);
8312
8313         if (!show_default && verbose &&
8314             qctl->qc_valid == QC_GENERAL && qctl->qc_cmd != LUSTRE_Q_GETINFO &&
8315             qctl->qc_cmd != LUSTRE_Q_GETINFOPOOL) {
8316                 char strbuf[STRBUF_LEN];
8317
8318                 rc2 = print_obd_quota(mnt, qctl, 1, human_readable,
8319                                       &total_ialloc);
8320                 rc3 = print_obd_quota(mnt, qctl, 0, human_readable,
8321                                       &total_balloc);
8322                 kbytes2str(total_balloc, strbuf, sizeof(strbuf),
8323                            human_readable);
8324                 printf("Total allocated inode limit: %ju, total allocated block limit: %s\n",
8325                        (uintmax_t)total_ialloc, strbuf);
8326         }
8327
8328         if (use_default_for_blk)
8329                 printf("%cid %u is using default block quota setting\n",
8330                        *qtype_name(qctl->qc_type), qctl->qc_id);
8331
8332         if (use_default_for_file)
8333                 printf("%cid %u is using default file quota setting\n",
8334                        *qtype_name(qctl->qc_type), qctl->qc_id);
8335
8336         if (rc1 || rc2 || rc3 || inacc)
8337                 printf("Some errors happened when getting quota info. Some devices may be not working or deactivated. The data in \"[]\" is inaccurate.\n");
8338 out:
8339         if (rc1)
8340                 return rc1;
8341         if (rc2)
8342                 return rc2;
8343         if (rc3)
8344                 return rc3;
8345         if (inacc)
8346                 return -EIO;
8347
8348         return 0;
8349 }
8350
8351 static int lfs_project(int argc, char **argv)
8352 {
8353         int ret = 0, err = 0, c, i;
8354         struct project_handle_control phc = { 0 };
8355         enum lfs_project_ops_t op;
8356
8357         phc.newline = true;
8358         phc.assign_projid = false;
8359         /* default action */
8360         op = LFS_PROJECT_LIST;
8361
8362         while ((c = getopt(argc, argv, "p:cCsdkr0")) != -1) {
8363                 switch (c) {
8364                 case 'c':
8365                         if (op != LFS_PROJECT_LIST) {
8366                                 fprintf(stderr,
8367                                         "%s: cannot specify '-c' '-C' '-s' together\n",
8368                                         progname);
8369                                 return CMD_HELP;
8370                         }
8371
8372                         op = LFS_PROJECT_CHECK;
8373                         break;
8374                 case 'C':
8375                         if (op != LFS_PROJECT_LIST) {
8376                                 fprintf(stderr,
8377                                         "%s: cannot specify '-c' '-C' '-s' together\n",
8378                                         progname);
8379                                 return CMD_HELP;
8380                         }
8381
8382                         op = LFS_PROJECT_CLEAR;
8383                         break;
8384                 case 's':
8385                         if (op != LFS_PROJECT_LIST) {
8386                                 fprintf(stderr,
8387                                         "%s: cannot specify '-c' '-C' '-s' together\n",
8388                                         progname);
8389                                 return CMD_HELP;
8390                         }
8391
8392                         phc.set_inherit = true;
8393                         op = LFS_PROJECT_SET;
8394                         break;
8395                 case 'd':
8396                         phc.dironly = true;
8397                         break;
8398                 case 'k':
8399                         phc.keep_projid = true;
8400                         break;
8401                 case 'r':
8402                         phc.recursive = true;
8403                         break;
8404                 case 'p':
8405                         if (str2quotaid(&phc.projid, optarg)) {
8406                                 fprintf(stderr,
8407                                         "Invalid project ID: %s\n",
8408                                         optarg);
8409                                 return CMD_HELP;
8410                         }
8411
8412                         phc.assign_projid = true;
8413
8414                         break;
8415                 case '0':
8416                         phc.newline = false;
8417                         break;
8418                 default:
8419                         fprintf(stderr, "%s: invalid option '%c'\n",
8420                                 progname, optopt);
8421                         return CMD_HELP;
8422                 }
8423         }
8424
8425         if (phc.assign_projid && op == LFS_PROJECT_LIST) {
8426                 op = LFS_PROJECT_SET;
8427                 phc.set_projid = true;
8428         } else if (phc.assign_projid && op == LFS_PROJECT_SET) {
8429                 phc.set_projid = true;
8430         }
8431
8432         switch (op) {
8433         case LFS_PROJECT_CHECK:
8434                 if (phc.keep_projid) {
8435                         fprintf(stderr,
8436                                 "%s: '-k' is useless together with '-c'\n",
8437                                 progname);
8438                         return CMD_HELP;
8439                 }
8440                 break;
8441         case LFS_PROJECT_CLEAR:
8442                 if (!phc.newline) {
8443                         fprintf(stderr,
8444                                 "%s: '-0' is useless together with '-C'\n",
8445                                 progname);
8446                         return CMD_HELP;
8447                 }
8448                 if (phc.assign_projid) {
8449                         fprintf(stderr,
8450                                 "%s: '-p' is useless together with '-C'\n",
8451                                 progname);
8452                         return CMD_HELP;
8453                 }
8454                 break;
8455         case LFS_PROJECT_SET:
8456                 if (!phc.newline) {
8457                         fprintf(stderr,
8458                                 "%s: '-0' is useless together with '-s'\n",
8459                                 progname);
8460                         return CMD_HELP;
8461                 }
8462                 if (phc.keep_projid) {
8463                         fprintf(stderr,
8464                                 "%s: '-k' is useless together with '-s'\n",
8465                                 progname);
8466                         return CMD_HELP;
8467                 }
8468                 break;
8469         default:
8470                 if (!phc.newline) {
8471                         fprintf(stderr,
8472                                 "%s: '-0' is useless for list operations\n",
8473                                 progname);
8474                         return CMD_HELP;
8475                 }
8476                 break;
8477         }
8478
8479         argv += optind;
8480         argc -= optind;
8481         if (argc == 0) {
8482                 fprintf(stderr, "%s: missing file or directory target(s)\n",
8483                         progname);
8484                 return CMD_HELP;
8485         }
8486
8487         for (i = 0; i < argc; i++) {
8488                 switch (op) {
8489                 case LFS_PROJECT_CHECK:
8490                         err = lfs_project_check(argv[i], &phc);
8491                         break;
8492                 case LFS_PROJECT_LIST:
8493                         err = lfs_project_list(argv[i], &phc);
8494                         break;
8495                 case LFS_PROJECT_CLEAR:
8496                         err = lfs_project_clear(argv[i], &phc);
8497                         break;
8498                 case LFS_PROJECT_SET:
8499                         err = lfs_project_set(argv[i], &phc);
8500                         break;
8501                 default:
8502                         break;
8503                 }
8504                 if (err && !ret)
8505                         ret = err;
8506         }
8507
8508         return ret;
8509 }
8510
8511 static int lfs_quota(int argc, char **argv)
8512 {
8513         int c;
8514         char *mnt, *name = NULL;
8515         struct if_quotactl *qctl;
8516         char *obd_uuid;
8517         int rc = 0, rc1 = 0, verbose = 0, quiet = 0;
8518         __u32 valid = QC_GENERAL, idx = 0;
8519         bool human_readable = false;
8520         bool show_default = false;
8521         int qtype;
8522         bool show_pools = false;
8523         struct option long_opts[] = {
8524         { .val = LFS_POOL_OPT, .name = "pool", .has_arg = optional_argument },
8525         { .name = NULL } };
8526         char **poollist = NULL;
8527         char *buf = NULL;
8528         int poolcount, i;
8529
8530         qctl = calloc(1, sizeof(*qctl) + LOV_MAXPOOLNAME + 1);
8531         if (!qctl)
8532                 return -ENOMEM;
8533
8534         qctl->qc_cmd = LUSTRE_Q_GETQUOTA;
8535         qctl->qc_type = ALLQUOTA;
8536         obd_uuid = (char *)qctl->obd_uuid.uuid;
8537
8538         while ((c = getopt_long(argc, argv, "gGi:I:o:pPqtuUvh",
8539                 long_opts, NULL)) != -1) {
8540                 switch (c) {
8541                 case 'U':
8542                         show_default = true;
8543                 case 'u':
8544                         qtype = USRQUOTA;
8545                         goto quota_type;
8546                 case 'G':
8547                         show_default = true;
8548                 case 'g':
8549                         qtype = GRPQUOTA;
8550                         goto quota_type;
8551                 case 'P':
8552                         show_default = true;
8553                 case 'p':
8554                         qtype = PRJQUOTA;
8555 quota_type:
8556                         if (qctl->qc_type != ALLQUOTA) {
8557                                 fprintf(stderr,
8558                                         "%s quota: only one of -u, -g, or -p may be specified\n",
8559                                         progname);
8560                                 rc = CMD_HELP;
8561                                 goto out;
8562                         }
8563                         qctl->qc_type = qtype;
8564                         break;
8565                 case 't':
8566                         qctl->qc_cmd = LUSTRE_Q_GETINFO;
8567                         break;
8568                 case 'o':
8569                         valid = qctl->qc_valid = QC_UUID;
8570                         snprintf(obd_uuid, sizeof(*obd_uuid), "%s", optarg);
8571                         break;
8572                 case 'i':
8573                         valid = qctl->qc_valid = QC_MDTIDX;
8574                         idx = qctl->qc_idx = atoi(optarg);
8575                         if (idx == 0 && *optarg != '0') {
8576                                 fprintf(stderr,
8577                                         "%s quota: invalid MDT index '%s'\n",
8578                                         progname, optarg);
8579                                 rc = CMD_HELP;
8580                                 goto out;
8581                         }
8582                         break;
8583                 case 'I':
8584                         valid = qctl->qc_valid = QC_OSTIDX;
8585                         idx = qctl->qc_idx = atoi(optarg);
8586                         if (idx == 0 && *optarg != '0') {
8587                                 fprintf(stderr,
8588                                         "%s quota: invalid OST index '%s'\n",
8589                                         progname, optarg);
8590                                 rc = CMD_HELP;
8591                                 goto out;
8592                         }
8593                         break;
8594                 case 'v':
8595                         verbose = 1;
8596                         break;
8597                 case 'q':
8598                         quiet = 1;
8599                         break;
8600                 case 'h':
8601                         human_readable = true;
8602                         break;
8603                 case LFS_POOL_OPT:
8604                         if ((!optarg) && (argv[optind] != NULL) &&
8605                                 (argv[optind][0] != '-') &&
8606                                 (argv[optind][0] != '/')) {
8607                                 optarg = argv[optind++];
8608                                 if (lfs_verify_poolarg(optarg)) {
8609                                         rc = -EINVAL;
8610                                         goto out;
8611                                 }
8612                                 strncpy(qctl->qc_poolname, optarg,
8613                                         LOV_MAXPOOLNAME);
8614                                 if (qctl->qc_cmd == LUSTRE_Q_GETINFO)
8615                                         qctl->qc_cmd = LUSTRE_Q_GETINFOPOOL;
8616                                 else
8617                                         qctl->qc_cmd = LUSTRE_Q_GETQUOTAPOOL;
8618                                 break;
8619                         }
8620
8621                         /* optarg is NULL */
8622                         show_pools = true;
8623                         qctl->qc_cmd = LUSTRE_Q_GETQUOTAPOOL;
8624                         break;
8625                 default:
8626                         fprintf(stderr, "%s quota: unrecognized option '%s'\n",
8627                                 progname, argv[optind - 1]);
8628                         rc = CMD_HELP;
8629                         goto out;
8630                 }
8631         }
8632
8633         /* current uid/gid info for "lfs quota /path/to/lustre/mount" */
8634         if ((qctl->qc_cmd == LUSTRE_Q_GETQUOTA ||
8635              qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL) &&
8636              qctl->qc_type == ALLQUOTA &&
8637              optind == argc - 1 && !show_default) {
8638                 qctl->qc_idx = idx;
8639
8640                 for (qtype = USRQUOTA; qtype <= GRPQUOTA; qtype++) {
8641                         qctl->qc_type = qtype;
8642                         qctl->qc_valid = valid;
8643                         if (qtype == USRQUOTA) {
8644                                 qctl->qc_id = geteuid();
8645                                 rc = uid2name(&name, qctl->qc_id);
8646                         } else {
8647                                 qctl->qc_id = getegid();
8648                                 rc = gid2name(&name, qctl->qc_id);
8649                                 memset(&qctl->qc_dqblk, 0,
8650                                        sizeof(qctl->qc_dqblk));
8651                         }
8652                         if (rc)
8653                                 name = "<unknown>";
8654                         mnt = argv[optind];
8655                         rc1 = get_print_quota(mnt, name, qctl, verbose, quiet,
8656                                               human_readable, show_default);
8657                         if (rc1 && !rc)
8658                                 rc = rc1;
8659                 }
8660                 goto out;
8661         /* lfs quota -u username /path/to/lustre/mount */
8662         } else if (qctl->qc_cmd == LUSTRE_Q_GETQUOTA ||
8663                    qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL) {
8664                 /* options should be followed by u/g-name and mntpoint */
8665                 if ((!show_default && optind + 2 != argc) ||
8666                     (show_default && optind + 1 != argc) ||
8667                     qctl->qc_type == ALLQUOTA) {
8668                         fprintf(stderr,
8669                                 "%s quota: name and mount point must be specified\n",
8670                                 progname);
8671                         rc = CMD_HELP;
8672                         goto out;
8673                 }
8674
8675                 if (!show_default) {
8676                         name = argv[optind++];
8677                         switch (qctl->qc_type) {
8678                         case USRQUOTA:
8679                                 rc = name2uid(&qctl->qc_id, name);
8680                                 break;
8681                         case GRPQUOTA:
8682                                 rc = name2gid(&qctl->qc_id, name);
8683                                 break;
8684                         case PRJQUOTA:
8685                                 rc = name2projid(&qctl->qc_id, name);
8686                                 break;
8687                         default:
8688                                 rc = -ENOTSUP;
8689                                 break;
8690                         }
8691                 } else {
8692                         qctl->qc_valid = QC_GENERAL;
8693                         qctl->qc_cmd = qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL ?
8694                                         LUSTRE_Q_GETDEFAULT_POOL :
8695                                         LUSTRE_Q_GETDEFAULT;
8696                         qctl->qc_id = 0;
8697                 }
8698
8699                 if (rc) {
8700                         if (str2quotaid(&qctl->qc_id, name)) {
8701                                 fprintf(stderr, "%s quota: invalid id '%s'\n",
8702                                         progname, name);
8703                                 rc = CMD_HELP;
8704                                 goto out;
8705                         }
8706                 }
8707         } else if (optind + 1 != argc || qctl->qc_type == ALLQUOTA) {
8708                 fprintf(stderr, "%s quota: missing quota info argument(s)\n",
8709                         progname);
8710                 rc = CMD_HELP;
8711                 goto out;
8712         }
8713
8714         mnt = argv[optind];
8715         if (show_pools) {
8716                 char *p;
8717
8718                 i = 0;
8719                 rc = llapi_get_poolbuf(mnt, &buf, &poollist, &poolcount);
8720                 if (rc)
8721                         goto out;
8722
8723                 for (i = 0; i < poolcount; i++) {
8724                         p = memchr(poollist[i], '.', MAXNAMLEN);
8725                         if (!p) {
8726                                 fprintf(stderr, "bad string format %.*s\n",
8727                                         MAXNAMLEN, poollist[i]);
8728                                 rc = -EINVAL;
8729                                 goto out;
8730                         }
8731                         p++;
8732                         printf("Quotas for pool: %s\n", p);
8733                         strncpy(qctl->qc_poolname, p, LOV_MAXPOOLNAME);
8734                         rc = get_print_quota(mnt, name, qctl, verbose, quiet,
8735                                              human_readable, show_default);
8736                         if (rc)
8737                                 break;
8738                 }
8739                 goto out;
8740         }
8741
8742         rc = get_print_quota(mnt, name, qctl, verbose, quiet,
8743                              human_readable, show_default);
8744 out:
8745         free(buf);
8746         free(qctl);
8747         return rc;
8748 }
8749 #endif /* HAVE_SYS_QUOTA_H! */
8750
8751 static int flushctx_ioctl(char *mp)
8752 {
8753         int fd, rc;
8754
8755         fd = open(mp, O_RDONLY);
8756         if (fd == -1) {
8757                 fprintf(stderr, "flushctx: error open %s: %s\n",
8758                         mp, strerror(errno));
8759                 return -1;
8760         }
8761
8762         rc = ioctl(fd, LL_IOC_FLUSHCTX);
8763         if (rc == -1)
8764                 fprintf(stderr, "flushctx: error ioctl %s: %s\n",
8765                         mp, strerror(errno));
8766
8767         close(fd);
8768         return rc;
8769 }
8770
8771 static int lfs_flushctx(int argc, char **argv)
8772 {
8773         int     kdestroy = 0, reap = 0, c;
8774         char    mntdir[PATH_MAX] = {'\0'};
8775         int     index = 0;
8776         int     rc = 0;
8777
8778         while ((c = getopt(argc, argv, "kr")) != -1) {
8779                 switch (c) {
8780                 case 'k':
8781                         kdestroy = 1;
8782                         break;
8783                 case 'r':
8784                         reap = 1;
8785                         break;
8786                 default:
8787                         fprintf(stderr,
8788                                 "error: %s: option '-%c' unrecognized\n",
8789                                 argv[0], c);
8790                         return CMD_HELP;
8791                 }
8792         }
8793
8794         if (kdestroy) {
8795                 rc = system("kdestroy > /dev/null");
8796                 if (rc) {
8797                         rc = WEXITSTATUS(rc);
8798                         fprintf(stderr,
8799                                 "error destroying tickets: %d, continuing\n",
8800                                 rc);
8801                 }
8802         }
8803
8804         if (optind >= argc) {
8805                 /* flush for all mounted lustre fs. */
8806                 while (!llapi_search_mounts(NULL, index++, mntdir, NULL)) {
8807                         /* Check if we have a mount point */
8808                         if (mntdir[0] == '\0')
8809                                 continue;
8810
8811                         if (flushctx_ioctl(mntdir))
8812                                 rc = -1;
8813
8814                         mntdir[0] = '\0'; /* avoid matching in next loop */
8815                 }
8816         } else {
8817                 /* flush fs as specified */
8818                 while (optind < argc) {
8819                         if (flushctx_ioctl(argv[optind++]))
8820                                 rc = -1;
8821                 }
8822         }
8823
8824         if (reap) {
8825                 rc = system("keyctl reap > /dev/null");
8826                 if (rc != 0) {
8827                         rc = WEXITSTATUS(rc);
8828                         fprintf(stderr, "error reaping keyring: %d\n", rc);
8829                 }
8830         }
8831
8832         return rc;
8833 }
8834
8835 static int lfs_changelog(int argc, char **argv)
8836 {
8837         void *changelog_priv;
8838         struct changelog_rec *rec;
8839         long long startrec = 0, endrec = 0;
8840         char *mdd;
8841         struct option long_opts[] = {
8842                 { .val = 'f', .name = "follow", .has_arg = no_argument },
8843                 { .name = NULL } };
8844         char short_opts[] = "f";
8845         int rc, follow = 0;
8846
8847         while ((rc = getopt_long(argc, argv, short_opts,
8848                 long_opts, NULL)) != -1) {
8849                 switch (rc) {
8850                 case 'f':
8851                         follow++;
8852                         break;
8853                 default:
8854                         fprintf(stderr,
8855                                 "%s changelog: unrecognized option '%s'\n",
8856                                 progname, argv[optind - 1]);
8857                         return CMD_HELP;
8858                 }
8859         }
8860         if (optind >= argc) {
8861                 fprintf(stderr, "%s changelog: mdtname must be specified\n",
8862                         progname);
8863                 return CMD_HELP;
8864         }
8865
8866         mdd = argv[optind++];
8867         if (argc > optind) {
8868                 errno = 0;
8869                 startrec = strtoll(argv[optind++], NULL, 10);
8870                 if (errno != 0 || startrec < 0) {
8871                         fprintf(stderr,
8872                                 "%s changelog: bad startrec\n",
8873                                 progname);
8874                         return CMD_HELP;
8875                 }
8876         }
8877
8878         if (argc > optind) {
8879                 errno = 0;
8880                 endrec = strtoll(argv[optind++], NULL, 10);
8881                 if (errno != 0 || endrec < 0) {
8882                         fprintf(stderr,
8883                                 "%s changelog: bad endrec\n",
8884                                 progname);
8885                         return CMD_HELP;
8886                 }
8887         }
8888
8889         rc = llapi_changelog_start(&changelog_priv,
8890                                    CHANGELOG_FLAG_BLOCK |
8891                                    CHANGELOG_FLAG_JOBID |
8892                                    CHANGELOG_FLAG_EXTRA_FLAGS |
8893                                    (follow ? CHANGELOG_FLAG_FOLLOW : 0),
8894                                    mdd, startrec);
8895         if (rc < 0) {
8896                 fprintf(stderr, "%s changelog: cannot start changelog: %s\n",
8897                         progname, strerror(errno = -rc));
8898                 return rc;
8899         }
8900
8901         rc = llapi_changelog_set_xflags(changelog_priv,
8902                                         CHANGELOG_EXTRA_FLAG_UIDGID |
8903                                         CHANGELOG_EXTRA_FLAG_NID |
8904                                         CHANGELOG_EXTRA_FLAG_OMODE |
8905                                         CHANGELOG_EXTRA_FLAG_XATTR);
8906         if (rc < 0) {
8907                 fprintf(stderr,
8908                         "%s changelog: cannot set xflags for changelog: %s\n",
8909                         progname, strerror(errno = -rc));
8910                 return rc;
8911         }
8912
8913         while ((rc = llapi_changelog_recv(changelog_priv, &rec)) == 0) {
8914                 time_t secs;
8915                 struct tm ts;
8916
8917                 if (endrec && rec->cr_index > endrec) {
8918                         llapi_changelog_free(&rec);
8919                         break;
8920                 }
8921                 if (rec->cr_index < startrec) {
8922                         llapi_changelog_free(&rec);
8923                         continue;
8924                 }
8925
8926                 secs = rec->cr_time >> 30;
8927                 gmtime_r(&secs, &ts);
8928                 printf("%ju %02d%-5s %02d:%02d:%02d.%09d %04d.%02d.%02d "
8929                        "0x%x t="DFID, (uintmax_t)rec->cr_index, rec->cr_type,
8930                        changelog_type2str(rec->cr_type),
8931                        ts.tm_hour, ts.tm_min, ts.tm_sec,
8932                        (int)(rec->cr_time & ((1 << 30) - 1)),
8933                        ts.tm_year + 1900, ts.tm_mon + 1, ts.tm_mday,
8934                        rec->cr_flags & CLF_FLAGMASK, PFID(&rec->cr_tfid));
8935
8936                 if (rec->cr_flags & CLF_JOBID) {
8937                         struct changelog_ext_jobid *jid =
8938                                 changelog_rec_jobid(rec);
8939
8940                         if (jid->cr_jobid[0] != '\0')
8941                                 printf(" j=%s", jid->cr_jobid);
8942                 }
8943
8944                 if (rec->cr_flags & CLF_EXTRA_FLAGS) {
8945                         struct changelog_ext_extra_flags *ef =
8946                                 changelog_rec_extra_flags(rec);
8947
8948                         printf(" ef=0x%llx",
8949                                (unsigned long long)ef->cr_extra_flags);
8950
8951                         if (ef->cr_extra_flags & CLFE_UIDGID) {
8952                                 struct changelog_ext_uidgid *uidgid =
8953                                         changelog_rec_uidgid(rec);
8954
8955                                 printf(" u=%llu:%llu",
8956                                        (unsigned long long)uidgid->cr_uid,
8957                                        (unsigned long long)uidgid->cr_gid);
8958                         }
8959                         if (ef->cr_extra_flags & CLFE_NID) {
8960                                 struct changelog_ext_nid *nid =
8961                                         changelog_rec_nid(rec);
8962
8963                                 printf(" nid=%s",
8964                                        libcfs_nid2str(nid->cr_nid));
8965                         }
8966
8967                         if (ef->cr_extra_flags & CLFE_OPEN) {
8968                                 struct changelog_ext_openmode *omd =
8969                                         changelog_rec_openmode(rec);
8970                                 char mode[] = "---";
8971
8972                                 /* exec mode must be exclusive */
8973                                 if (omd->cr_openflags & MDS_FMODE_EXEC) {
8974                                         mode[2] = 'x';
8975                                 } else {
8976                                         if (omd->cr_openflags & MDS_FMODE_READ)
8977                                                 mode[0] = 'r';
8978                                         if (omd->cr_openflags &
8979                                             (MDS_FMODE_WRITE |
8980                                              MDS_OPEN_TRUNC |
8981                                              MDS_OPEN_APPEND))
8982                                                 mode[1] = 'w';
8983                                 }
8984
8985                                 if (strcmp(mode, "---") != 0)
8986                                         printf(" m=%s", mode);
8987                         }
8988
8989                         if (ef->cr_extra_flags & CLFE_XATTR) {
8990                                 struct changelog_ext_xattr *xattr =
8991                                         changelog_rec_xattr(rec);
8992
8993                                 if (xattr->cr_xattr[0] != '\0')
8994                                         printf(" x=%s", xattr->cr_xattr);
8995                         }
8996                 }
8997
8998                 if (!fid_is_zero(&rec->cr_pfid))
8999                         printf(" p="DFID, PFID(&rec->cr_pfid));
9000                 if (rec->cr_namelen)
9001                         printf(" %.*s", rec->cr_namelen,
9002                                changelog_rec_name(rec));
9003
9004                 if (rec->cr_flags & CLF_RENAME) {
9005                         struct changelog_ext_rename *rnm =
9006                                 changelog_rec_rename(rec);
9007
9008                         if (!fid_is_zero(&rnm->cr_sfid))
9009                                 printf(" s="DFID" sp="DFID" %.*s",
9010                                        PFID(&rnm->cr_sfid),
9011                                        PFID(&rnm->cr_spfid),
9012                                        (int)changelog_rec_snamelen(rec),
9013                                        changelog_rec_sname(rec));
9014                 }
9015                 printf("\n");
9016
9017                 llapi_changelog_free(&rec);
9018         }
9019
9020         llapi_changelog_fini(&changelog_priv);
9021
9022         if (rc < 0)
9023                 fprintf(stderr, "%s changelog: cannot access changelog: %s\n",
9024                         progname, strerror(errno = -rc));
9025
9026         return (rc == 1 ? 0 : rc);
9027 }
9028
9029 static int lfs_changelog_clear(int argc, char **argv)
9030 {
9031         long long endrec;
9032         int rc;
9033
9034         if (argc != 4)
9035                 return CMD_HELP;
9036
9037         errno = 0;
9038         endrec = strtoll(argv[3], NULL, 10);
9039         if (errno != 0 || endrec < 0) {
9040                 fprintf(stderr,
9041                         "%s: bad endrec '%s'\n",
9042                         argv[0], argv[3]);
9043                 return CMD_HELP;
9044         }
9045
9046         rc = llapi_changelog_clear(argv[1], argv[2], endrec);
9047
9048         if (rc == -EINVAL)
9049                 fprintf(stderr, "%s: record out of range: %llu\n",
9050                         argv[0], endrec);
9051         else if (rc == -ENOENT)
9052                 fprintf(stderr, "%s: no changelog user: %s\n",
9053                         argv[0], argv[2]);
9054         else if (rc)
9055                 fprintf(stderr, "%s error: %s\n", argv[0],
9056                         strerror(-rc));
9057
9058         if (rc)
9059                 errno = -rc;
9060
9061         return rc;
9062 }
9063
9064 static void rstripc(char *str, int c)
9065 {
9066         char *end = str + strlen(str);
9067
9068         for (; str < end && end[-1] == c; --end)
9069                 end[-1] = '\0';
9070 }
9071
9072 static int lfs_fid2path(int argc, char **argv)
9073 {
9074         struct option long_opts[] = {
9075                 { .val = 'c',   .name = "cur",  .has_arg = no_argument },
9076                 { .val = 'c',   .name = "current",      .has_arg = no_argument },
9077                 { .val = 'c',   .name = "print-link",   .has_arg = no_argument },
9078                 { .val = 'f',   .name = "print-fid",    .has_arg = no_argument },
9079                 { .val = 'l',   .name = "link", .has_arg = required_argument },
9080                 { .name = NULL } };
9081         char short_opts[] = "cfl:pr:";
9082         bool print_link = false;
9083         bool print_fid = false;
9084         bool print_mnt_dir;
9085         char mnt_dir[PATH_MAX] = "";
9086         int mnt_fd = -1;
9087         char *path_or_fsname;
9088         long long recno = -1;
9089         int linkno = -1;
9090         char *endptr = NULL;
9091         int rc = 0;
9092         int c;
9093         int i;
9094
9095         while ((c = getopt_long(argc, argv, short_opts, long_opts, NULL)) != -1) {
9096                 switch (c) {
9097                 case 'c':
9098                         print_link = true;
9099                         break;
9100                 case 'f':
9101                         print_fid = true;
9102                         break;
9103                 case 'l':
9104                         errno = 0;
9105                         linkno = strtol(optarg, &endptr, 10);
9106                         if (errno != 0 || *endptr != '\0' || linkno < 0) {
9107                                 fprintf(stderr,
9108                                         "%s fid2path: invalid linkno '%s'\n",
9109                                         progname, optarg);
9110                                 return CMD_HELP;
9111                         }
9112                         break;
9113                 case 'r':
9114                         /* recno is something to do with changelogs
9115                          * that was never implemented. We just pass it
9116                          * through for the MDT to ignore.
9117                          */
9118                         errno = 0;
9119                         recno = strtoll(optarg, &endptr, 10);
9120                         if (errno != 0 || *endptr != '\0' || recno < 0) {
9121                                 fprintf(stderr,
9122                                         "%s fid2path: invalid recno '%s'\n",
9123                                         progname, optarg);
9124                                 return CMD_HELP;
9125                         }
9126                         break;
9127                 default:
9128                         fprintf(stderr,
9129                                 "%s fid2path: unrecognized option '%s'\n",
9130                                 progname, argv[optind - 1]);
9131                         return CMD_HELP;
9132                 }
9133         }
9134
9135         if (argc - optind < 2) {
9136                 fprintf(stderr,
9137                         "Usage: %s fid2path FSNAME|ROOT FID...\n",
9138                         progname);
9139                 return CMD_HELP;
9140         }
9141
9142         path_or_fsname = argv[optind];
9143
9144         if (*path_or_fsname == '/') {
9145                 print_mnt_dir = true;
9146                 rc = llapi_search_mounts(path_or_fsname, 0, mnt_dir, NULL);
9147         } else {
9148                 print_mnt_dir = false;
9149                 rc = llapi_search_rootpath(mnt_dir, path_or_fsname);
9150         }
9151
9152         if (rc < 0) {
9153                 fprintf(stderr,
9154                         "%s fid2path: cannot resolve mount point for '%s': %s\n",
9155                         progname, path_or_fsname, strerror(-rc));
9156                 goto out;
9157         }
9158
9159         mnt_fd = open(mnt_dir, O_RDONLY | O_DIRECTORY);
9160         if (mnt_fd < 0) {
9161                 fprintf(stderr,
9162                         "%s fid2path: cannot open mount point for '%s': %s\n",
9163                         progname, path_or_fsname, strerror(-rc));
9164                 goto out;
9165         }
9166
9167         /* Strip trailing slashes from mnt_dir. */
9168         rstripc(mnt_dir + 1, '/');
9169
9170         for (i = optind + 1; i < argc; i++) {
9171                 const char *fid_str = argv[i];
9172                 struct lu_fid fid;
9173                 int rc2;
9174
9175                 rc2 = llapi_fid_parse(fid_str, &fid, NULL);
9176                 if (rc2 < 0) {
9177                         fprintf(stderr,
9178                                 "%s fid2path: invalid FID '%s'\n",
9179                                 progname, fid_str);
9180                         if (rc == 0)
9181                                 rc = rc2;
9182
9183                         continue;
9184                 }
9185
9186                 int linktmp = (linkno >= 0) ? linkno : 0;
9187                 while (1) {
9188                         int oldtmp = linktmp;
9189                         long long rectmp = recno;
9190                         char path_buf[PATH_MAX];
9191
9192                         rc2 = llapi_fid2path_at(mnt_fd, &fid,
9193                                 path_buf, sizeof(path_buf), &rectmp, &linktmp);
9194                         if (rc2 < 0) {
9195                                 fprintf(stderr,
9196                                         "%s fid2path: cannot find %s %s: %s\n",
9197                                         progname, path_or_fsname, fid_str,
9198                                         strerror(-rc2));
9199                                 if (rc == 0)
9200                                         rc = rc2;
9201                                 break;
9202                         }
9203
9204                         if (print_fid)
9205                                 printf("%s ", fid_str);
9206
9207                         if (print_link)
9208                                 printf("%d ", linktmp);
9209
9210                         /* You may think this looks wrong or weird (and it is!)
9211                          * but we are actually trying to preserve the old quirky
9212                          * behaviors (enforced by our old quirky tests!) that
9213                          * make lfs so much fun to work on:
9214                          *
9215                          *   lustre 0x200000007:0x1:0x0 => "/"
9216                          *   /mnt/lustre 0x200000007:0x1:0x0 => "/mnt/lustre//"
9217                          *
9218                          * Note that llapi_fid2path() returns "" for the root
9219                          * FID. */
9220
9221                         printf("%s%s%s\n",
9222                                print_mnt_dir ? mnt_dir : "",
9223                                (print_mnt_dir || *path_buf == '\0') ? "/" : "",
9224                                path_buf);
9225
9226                         if (linkno >= 0)
9227                                 /* specified linkno */
9228                                 break;
9229
9230                         if (oldtmp == linktmp)
9231                                 /* no more links */
9232                                 break;
9233                 }
9234         }
9235 out:
9236         if (!(mnt_fd < 0))
9237                 close(mnt_fd);
9238
9239         return rc;
9240 }
9241
9242 static int lfs_path2fid(int argc, char **argv)
9243 {
9244         struct option long_opts[] = {
9245                 { .val = 'p', .name = "parents", .has_arg = no_argument },
9246                 { .name = NULL } };
9247         char            **path;
9248         const char        short_opts[] = "p";
9249         const char       *sep = "";
9250         struct lu_fid     fid;
9251         int               rc = 0;
9252         bool              show_parents = false;
9253
9254         while ((rc = getopt_long(argc, argv, short_opts,
9255                                  long_opts, NULL)) != -1) {
9256                 switch (rc) {
9257                 case 'p':
9258                         show_parents = true;
9259                         break;
9260                 default:
9261                         fprintf(stderr,
9262                                 "%s path2fid: unrecognized option '%s'\n",
9263                                 progname, argv[optind - 1]);
9264                         return CMD_HELP;
9265                 }
9266         }
9267
9268         if (optind > argc - 1) {
9269                 fprintf(stderr, "%s path2fid: FILE... must be specified\n",
9270                         progname);
9271                 return CMD_HELP;
9272         } else if (optind < argc - 1) {
9273                 sep = ": ";
9274         }
9275
9276         rc = 0;
9277         for (path = argv + optind; *path != NULL; path++) {
9278                 int err = 0;
9279
9280                 if (!show_parents) {
9281                         err = llapi_path2fid(*path, &fid);
9282                         if (!err)
9283                                 printf("%s%s"DFID"\n",
9284                                        *sep != '\0' ? *path : "", sep,
9285                                        PFID(&fid));
9286                 } else {
9287                         char            name[NAME_MAX + 1];
9288                         unsigned int    linkno = 0;
9289
9290                         while ((err = llapi_path2parent(*path, linkno, &fid,
9291                                                 name, sizeof(name))) == 0) {
9292                                 if (*sep != '\0' && linkno == 0)
9293                                         printf("%s%s", *path, sep);
9294
9295                                 printf("%s"DFID"/%s", linkno != 0 ? "\t" : "",
9296                                        PFID(&fid), name);
9297                                 linkno++;
9298                         }
9299
9300                         /* err == -ENODATA is end-of-loop */
9301                         if (linkno > 0 && err == -ENODATA) {
9302                                 printf("\n");
9303                                 err = 0;
9304                         }
9305                 }
9306
9307                 if (err) {
9308                         fprintf(stderr,
9309                                 "%s path2fid: cannot get %sfid for '%s': %s\n",
9310                                 progname, show_parents ? "parent " : "", *path,
9311                                 strerror(-err));
9312                         if (rc == 0) {
9313                                 rc = err;
9314                                 errno = -err;
9315                         }
9316                 }
9317         }
9318
9319         return rc;
9320 }
9321
9322 #define MAX_ERRNO       4095
9323 #define IS_ERR_VALUE(x) ((unsigned long)(x) >= (unsigned long)-MAX_ERRNO)
9324
9325 static int lfs_rmfid_and_show_errors(const char *device, struct fid_array *fa)
9326 {
9327         int rc, rc2, k;
9328
9329         rc = llapi_rmfid(device, fa);
9330         if (rc < 0) {
9331                 fprintf(stderr, "%s rmfid: cannot remove FIDs: %s\n",
9332                         progname, strerror(-rc));
9333                 return rc;
9334         }
9335
9336         for (k = 0; k < fa->fa_nr; k++) {
9337                 rc2 = (__s32)fa->fa_fids[k].f_ver;
9338                 if (!IS_ERR_VALUE(rc2))
9339                         continue;
9340
9341                 if (rc == 0)
9342                         rc = rc2;
9343
9344                 fa->fa_fids[k].f_ver = 0;
9345                 fprintf(stderr, "%s rmfid: cannot remove "DFID": %s\n",
9346                         progname, PFID(&fa->fa_fids[k]), strerror(-rc2));
9347         }
9348
9349         return rc;
9350 }
9351
9352 static int lfs_rmfid(int argc, char **argv)
9353 {
9354         char *fidstr, *device;
9355         int rc = 0, rc2, nr;
9356         struct fid_array *fa;
9357
9358         if (optind > argc - 1) {
9359                 fprintf(stderr, "%s rmfid: missing dirname\n", progname);
9360                 return CMD_HELP;
9361         }
9362
9363         device = argv[optind++];
9364
9365         nr = argc - optind;
9366         fa = malloc(offsetof(struct fid_array, fa_fids[nr + 1]));
9367         if (!fa)
9368                 return -ENOMEM;
9369
9370         fa->fa_nr = 0;
9371         rc = 0;
9372         while (optind < argc) {
9373                 int found;
9374
9375                 fidstr = argv[optind++];
9376                 while (*fidstr == '[')
9377                         fidstr++;
9378                 found = sscanf(fidstr, SFID, RFID(&fa->fa_fids[fa->fa_nr]));
9379                 if (found != 3) {
9380                         fprintf(stderr, "unrecognized FID: %s\n",
9381                                 argv[optind - 1]);
9382                         exit(1);
9383                 }
9384                 fa->fa_nr++;
9385                 if (fa->fa_nr == OBD_MAX_FIDS_IN_ARRAY) {
9386                         /* start another batch */
9387                         rc2 = lfs_rmfid_and_show_errors(device, fa);
9388                         if (rc2 && !rc)
9389                                 rc = rc2;
9390                         fa->fa_nr = 0;
9391                 }
9392         }
9393         if (fa->fa_nr) {
9394                 rc2 = lfs_rmfid_and_show_errors(device, fa);
9395                 if (rc2 && !rc)
9396                         rc = rc2;
9397         }
9398
9399         return rc;
9400 }
9401
9402 static int lfs_data_version(int argc, char **argv)
9403 {
9404         int data_version_flags = LL_DV_RD_FLUSH; /* Read by default */
9405         __u64 data_version;
9406         char *path;
9407         int fd;
9408         int rc;
9409         int c;
9410
9411         if (argc < 2) {
9412                 fprintf(stderr, "%s: FILE must be specified\n",
9413                         progname);
9414                 return CMD_HELP;
9415         }
9416
9417         while ((c = getopt(argc, argv, "hnrw")) != -1) {
9418                 switch (c) {
9419                 case 'n':
9420                         data_version_flags = 0;
9421                         break;
9422                 case 'r':
9423                         data_version_flags |= LL_DV_RD_FLUSH;
9424                         break;
9425                 case 'w':
9426                         data_version_flags |= LL_DV_WR_FLUSH;
9427                         break;
9428                 default:
9429                         fprintf(stderr,
9430                                 "%s data_version: unrecognized option '%s'\n",
9431                                 progname, argv[optind - 1]);
9432                         /* fallthrough */
9433                 case 'h':
9434                         return CMD_HELP;
9435                 }
9436         }
9437         if (optind == argc) {
9438                 fprintf(stderr, "%s data_version: FILE must be specified\n",
9439                         progname);
9440                 return CMD_HELP;
9441         }
9442
9443         path = argv[optind];
9444         fd = open(path, O_RDONLY);
9445         if (fd < 0) {
9446                 rc = -errno;
9447                 fprintf(stderr, "%s data_version: cannot open file '%s': %s\n",
9448                         progname, path, strerror(-rc));
9449                 return rc;
9450         }
9451
9452         rc = llapi_get_data_version(fd, &data_version, data_version_flags);
9453         if (rc < 0)
9454                 fprintf(stderr,
9455                         "%s data_version: cannot get version for '%s': %s\n",
9456                         progname, path, strerror(-rc));
9457         else
9458                 printf("%ju" "\n", (uintmax_t)data_version);
9459
9460         close(fd);
9461         return rc;
9462 }
9463
9464 static int lfs_hsm_state(int argc, char **argv)
9465 {
9466         int rc;
9467         int i = 1;
9468         char *path;
9469         struct hsm_user_state hus;
9470
9471         if (argc < 2)
9472                 return CMD_HELP;
9473
9474         do {
9475                 path = argv[i];
9476
9477                 rc = llapi_hsm_state_get(path, &hus);
9478                 if (rc) {
9479                         fprintf(stderr, "can't get hsm state for %s: %s\n",
9480                                 path, strerror(errno = -rc));
9481                         return rc;
9482                 }
9483
9484                 /* Display path name and status flags */
9485                 printf("%s: (0x%08x)", path, hus.hus_states);
9486
9487                 if (hus.hus_states & HS_RELEASED)
9488                         printf(" released");
9489                 if (hus.hus_states & HS_EXISTS)
9490                         printf(" exists");
9491                 if (hus.hus_states & HS_DIRTY)
9492                         printf(" dirty");
9493                 if (hus.hus_states & HS_ARCHIVED)
9494                         printf(" archived");
9495                 /* Display user-settable flags */
9496                 if (hus.hus_states & HS_NORELEASE)
9497                         printf(" never_release");
9498                 if (hus.hus_states & HS_NOARCHIVE)
9499                         printf(" never_archive");
9500                 if (hus.hus_states & HS_LOST)
9501                         printf(" lost_from_hsm");
9502
9503                 if (hus.hus_archive_id != 0)
9504                         printf(", archive_id:%d", hus.hus_archive_id);
9505                 printf("\n");
9506
9507         } while (++i < argc);
9508
9509         return 0;
9510 }
9511
9512 #define LFS_HSM_SET   0
9513 #define LFS_HSM_CLEAR 1
9514
9515 /**
9516  * Generic function to set or clear HSM flags.
9517  * Used by hsm_set and hsm_clear.
9518  *
9519  * @mode  if LFS_HSM_SET, set the flags, if LFS_HSM_CLEAR, clear the flags.
9520  */
9521 static int lfs_hsm_change_flags(int argc, char **argv, int mode)
9522 {
9523         struct option long_opts[] = {
9524         { .val = 'A',   .name = "archived",     .has_arg = no_argument },
9525         { .val = 'a',   .name = "noarchive",    .has_arg = no_argument },
9526         { .val = 'd',   .name = "dirty",        .has_arg = no_argument },
9527         { .val = 'e',   .name = "exists",       .has_arg = no_argument },
9528         { .val = 'h',   .name = "help",         .has_arg = no_argument },
9529         { .val = 'i',   .name = "archive-id",   .has_arg = required_argument },
9530         { .val = 'l',   .name = "lost",         .has_arg = no_argument },
9531         { .val = 'r',   .name = "norelease",    .has_arg = no_argument },
9532         { .name = NULL } };
9533         __u64 mask = 0;
9534         int c, rc;
9535         char *path;
9536         __u32 archive_id = 0;
9537         char *end = NULL;
9538
9539         if (argc < 3)
9540                 return CMD_HELP;
9541
9542         while ((c = getopt_long(argc, argv, "aAdehi:lr",
9543                                 long_opts, NULL)) != -1) {
9544                 switch (c) {
9545                 case 'l':
9546                         mask |= HS_LOST;
9547                         break;
9548                 case 'a':
9549                         mask |= HS_NOARCHIVE;
9550                         break;
9551                 case 'A':
9552                         mask |= HS_ARCHIVED;
9553                         break;
9554                 case 'r':
9555                         mask |= HS_NORELEASE;
9556                         break;
9557                 case 'd':
9558                         mask |= HS_DIRTY;
9559                         break;
9560                 case 'e':
9561                         mask |= HS_EXISTS;
9562                         break;
9563                 case 'i':
9564                         errno = 0;
9565                         archive_id = strtol(optarg, &end, 10);
9566                         if (errno != 0 || *end != '\0' || archive_id < 0) {
9567                                 fprintf(stderr,
9568                                         "%s: invalid archive_id: '%s'\n",
9569                                         progname, end);
9570                                 return CMD_HELP;
9571                         }
9572                         break;
9573                 default:
9574                         fprintf(stderr, "%s: unrecognized option '%s'\n",
9575                                 progname, argv[optind - 1]);
9576                         /* fallthrough */
9577                 case 'h':
9578                         return CMD_HELP;
9579                 }
9580         }
9581
9582         /* User should have specified a flag */
9583         if (mask == 0)
9584                 return CMD_HELP;
9585
9586         while (optind < argc) {
9587                 path = argv[optind];
9588
9589                 /* If mode == 0, this means we apply the mask. */
9590                 if (mode == LFS_HSM_SET)
9591                         rc = llapi_hsm_state_set(path, mask, 0, archive_id);
9592                 else
9593                         rc = llapi_hsm_state_set(path, 0, mask, 0);
9594
9595                 if (rc != 0) {
9596                         fprintf(stderr, "Can't change hsm flags for %s: %s\n",
9597                                 path, strerror(errno = -rc));
9598                         return rc;
9599                 }
9600                 optind++;
9601         }
9602
9603         return 0;
9604 }
9605
9606 static int lfs_hsm_action(int argc, char **argv)
9607 {
9608         int                              rc;
9609         int                              i = 1;
9610         char                            *path;
9611         struct hsm_current_action        hca;
9612         struct hsm_extent                he;
9613         enum hsm_user_action             hua;
9614         enum hsm_progress_states         hps;
9615
9616         if (argc < 2)
9617                 return CMD_HELP;
9618
9619         do {
9620                 path = argv[i];
9621
9622                 rc = llapi_hsm_current_action(path, &hca);
9623                 if (rc) {
9624                         fprintf(stderr, "can't get hsm action for %s: %s\n",
9625                                 path, strerror(errno = -rc));
9626                         return rc;
9627                 }
9628                 he = hca.hca_location;
9629                 hua = hca.hca_action;
9630                 hps = hca.hca_state;
9631
9632                 printf("%s: %s", path, hsm_user_action2name(hua));
9633
9634                 /* Skip file without action */
9635                 if (hca.hca_action == HUA_NONE) {
9636                         printf("\n");
9637                         continue;
9638                 }
9639
9640                 printf(" %s ", hsm_progress_state2name(hps));
9641
9642                 if ((hps == HPS_RUNNING) &&
9643                     (hua == HUA_ARCHIVE || hua == HUA_RESTORE))
9644                         printf("(%llu bytes moved)\n",
9645                                (unsigned long long)he.length);
9646                 else if ((he.offset + he.length) == LUSTRE_EOF)
9647                         printf("(from %llu to EOF)\n",
9648                                (unsigned long long)he.offset);
9649                 else
9650                         printf("(from %llu to %llu)\n",
9651                                (unsigned long long)he.offset,
9652                                (unsigned long long)(he.offset + he.length));
9653
9654         } while (++i < argc);
9655
9656         return 0;
9657 }
9658
9659 static int lfs_hsm_set(int argc, char **argv)
9660 {
9661         return lfs_hsm_change_flags(argc, argv, LFS_HSM_SET);
9662 }
9663
9664 static int lfs_hsm_clear(int argc, char **argv)
9665 {
9666         return lfs_hsm_change_flags(argc, argv, LFS_HSM_CLEAR);
9667 }
9668
9669 /**
9670  * Check file state and return its fid, to be used by lfs_hsm_request().
9671  *
9672  * \param[in]     file      Path to file to check
9673  * \param[in,out] fid       Pointer to allocated lu_fid struct.
9674  * \param[in,out] last_dev  Pointer to last device id used.
9675  *
9676  * \return 0 on success.
9677  */
9678 static int lfs_hsm_prepare_file(const char *file, struct lu_fid *fid,
9679                                 dev_t *last_dev)
9680 {
9681         struct stat     st;
9682         int             rc;
9683
9684         rc = lstat(file, &st);
9685         if (rc) {
9686                 fprintf(stderr, "Cannot stat %s: %s\n", file, strerror(errno));
9687                 return -errno;
9688         }
9689         /*
9690          * Checking for regular file as archiving as posix copytool
9691          * rejects archiving files other than regular files
9692          */
9693         if (!S_ISREG(st.st_mode)) {
9694                 fprintf(stderr, "error: \"%s\" is not a regular file\n", file);
9695                 return CMD_HELP;
9696         }
9697         /* A request should be ... */
9698         if (*last_dev != st.st_dev && *last_dev != 0) {
9699                 fprintf(stderr,
9700                         "All files should be on the same filesystem: %s\n",
9701                         file);
9702                 return -EINVAL;
9703         }
9704         *last_dev = st.st_dev;
9705
9706         rc = llapi_path2fid(file, fid);
9707         if (rc) {
9708                 fprintf(stderr, "Cannot read FID of %s: %s\n",
9709                         file, strerror(-rc));
9710                 return rc;
9711         }
9712         return 0;
9713 }
9714
9715 /* Fill an HSM HUR item with a given file name.
9716  *
9717  * If mntpath is set, then the filename is actually a FID, and no
9718  * lookup on the filesystem will be performed.
9719  *
9720  * \param[in]  hur         the user request to fill
9721  * \param[in]  idx         index of the item inside the HUR to fill
9722  * \param[in]  mntpath     mountpoint of Lustre
9723  * \param[in]  fname       filename (if mtnpath is NULL)
9724  *                         or FID (if mntpath is set)
9725  * \param[in]  last_dev    pointer to last device id used
9726  *
9727  * \retval 0 on success
9728  * \retval CMD_HELP or a negative errno on error
9729  */
9730 static int fill_hur_item(struct hsm_user_request *hur, unsigned int idx,
9731                          const char *mntpath, const char *fname,
9732                          dev_t *last_dev)
9733 {
9734         struct hsm_user_item *hui = &hur->hur_user_item[idx];
9735         int rc;
9736
9737         hui->hui_extent.length = -1;
9738
9739         if (mntpath) {
9740                 rc = llapi_fid_parse(fname, &hui->hui_fid, NULL);
9741                 if (rc)
9742                         fprintf(stderr, "hsm: '%s' is not a valid FID\n",
9743                                 fname);
9744         } else {
9745                 rc = lfs_hsm_prepare_file(fname, &hui->hui_fid, last_dev);
9746         }
9747
9748         if (rc == 0)
9749                 hur->hur_request.hr_itemcount++;
9750
9751         return rc;
9752 }
9753
9754 static int lfs_hsm_request(int argc, char **argv, int action)
9755 {
9756         struct option long_opts[] = {
9757         { .val = 'a',   .name = "archive",      .has_arg = required_argument },
9758         { .val = 'D',   .name = "data",         .has_arg = required_argument },
9759         { .val = 'h',   .name = "help",         .has_arg = no_argument },
9760         { .val = 'l',   .name = "filelist",     .has_arg = required_argument },
9761         { .val = 'm',   .name = "mntpath",      .has_arg = required_argument },
9762         { .name = NULL } };
9763         dev_t last_dev = 0;
9764         struct hsm_user_request *hur, *oldhur;
9765         int c, i;
9766         size_t len;
9767         int nbfile;
9768         char *line = NULL;
9769         char *filelist = NULL;
9770         char fullpath[PATH_MAX];
9771         char *opaque = NULL;
9772         int opaque_len = 0;
9773         int archive_id = 0;
9774         FILE *fp;
9775         int nbfile_alloc = 0;
9776         char *some_file = NULL;
9777         char *mntpath = NULL;
9778         int rc;
9779
9780         if (argc < 2)
9781                 return CMD_HELP;
9782
9783         while ((c = getopt_long(argc, argv, "a:D:hl:m:",
9784                                 long_opts, NULL)) != -1) {
9785                 switch (c) {
9786                 case 'l':
9787                         filelist = optarg;
9788                         break;
9789                 case 'D':
9790                         opaque = optarg;
9791                         break;
9792                 case 'a':
9793                         if (action != HUA_ARCHIVE &&
9794                             action != HUA_REMOVE) {
9795                                 fprintf(stderr,
9796                                         "error: -a is supported only when archiving or removing\n");
9797                                 return CMD_HELP;
9798                         }
9799                         archive_id = atoi(optarg);
9800                         break;
9801                 case 'm':
9802                         if (!some_file) {
9803                                 mntpath = optarg;
9804                                 some_file = strdup(optarg);
9805                         }
9806                         break;
9807                 default:
9808                         fprintf(stderr, "%s: unrecognized option '%s'\n",
9809                                 progname, argv[optind - 1]);
9810                         /* fallthrough */
9811                 case 'h':
9812                         return CMD_HELP;
9813                 }
9814         }
9815
9816         /* All remaining args are files, so we have at least nbfile */
9817         nbfile = argc - optind;
9818
9819         if ((nbfile == 0) && (!filelist))
9820                 return CMD_HELP;
9821
9822         if (opaque)
9823                 opaque_len = strlen(opaque);
9824
9825         /*
9826          * Alloc the request structure with enough place to store all files
9827          * from command line.
9828          */
9829         hur = llapi_hsm_user_request_alloc(nbfile, opaque_len);
9830         if (!hur) {
9831                 fprintf(stderr, "Cannot create the request: %s\n",
9832                         strerror(errno));
9833                 return errno;
9834         }
9835         nbfile_alloc = nbfile;
9836
9837         hur->hur_request.hr_action = action;
9838         hur->hur_request.hr_archive_id = archive_id;
9839         hur->hur_request.hr_flags = 0;
9840
9841         /* All remaining args are files, add them */
9842         if (nbfile != 0 && some_file == NULL)
9843                 some_file = strdup(argv[optind]);
9844
9845         for (i = 0; i < nbfile; i++) {
9846                 rc = fill_hur_item(hur, i, mntpath, argv[optind + i],
9847                                    &last_dev);
9848                 if (rc)
9849                         goto out_free;
9850         }
9851
9852         /* from here stop using nb_file, use hur->hur_request.hr_itemcount */
9853
9854         /* If a filelist was specified, read the filelist from it. */
9855         if (filelist) {
9856                 fp = fopen(filelist, "r");
9857                 if (!fp) {
9858                         fprintf(stderr, "Cannot read the file list %s: %s\n",
9859                                 filelist, strerror(errno));
9860                         rc = -errno;
9861                         goto out_free;
9862                 }
9863
9864                 while ((rc = getline(&line, &len, fp)) != -1) {
9865                         /*
9866                          * If allocated buffer was too small, get something
9867                          * larger
9868                          */
9869                         if (nbfile_alloc <= hur->hur_request.hr_itemcount) {
9870                                 ssize_t size;
9871
9872                                 nbfile_alloc = nbfile_alloc * 2 + 1;
9873                                 oldhur = hur;
9874                                 hur = llapi_hsm_user_request_alloc(nbfile_alloc,
9875                                                                    opaque_len);
9876                                 if (!hur) {
9877                                         fprintf(stderr,
9878                                                 "hsm: cannot allocate the request: %s\n",
9879                                                 strerror(errno));
9880                                         hur = oldhur;
9881                                         rc = -errno;
9882                                         fclose(fp);
9883                                         goto out_free;
9884                                 }
9885                                 size = hur_len(oldhur);
9886                                 if (size < 0) {
9887                                         fprintf(stderr,
9888                                                 "hsm: cannot allocate %u files + %u bytes data\n",
9889                                                 oldhur->hur_request.hr_itemcount,
9890                                                 oldhur->hur_request.hr_data_len);
9891                                         free(hur);
9892                                         hur = oldhur;
9893                                         rc = -E2BIG;
9894                                         fclose(fp);
9895                                         goto out_free;
9896                                 }
9897                                 memcpy(hur, oldhur, size);
9898                                 free(oldhur);
9899                         }
9900
9901                         /* Chop CR */
9902                         if (line[strlen(line) - 1] == '\n')
9903                                 line[strlen(line) - 1] = '\0';
9904
9905                         rc = fill_hur_item(hur, hur->hur_request.hr_itemcount,
9906                                            mntpath, line, &last_dev);
9907                         if (rc) {
9908                                 fclose(fp);
9909                                 goto out_free;
9910                         }
9911
9912                         if (!some_file) {
9913                                 some_file = line;
9914                                 line = NULL;
9915                         }
9916                 }
9917
9918                 rc = fclose(fp);
9919                 free(line);
9920         }
9921
9922         /* If a --data was used, add it to the request */
9923         hur->hur_request.hr_data_len = opaque_len;
9924         if (opaque)
9925                 memcpy(hur_data(hur), opaque, opaque_len);
9926
9927         /* Send the HSM request */
9928         if (realpath(some_file, fullpath) == NULL) {
9929                 fprintf(stderr, "Could not find path '%s': %s\n",
9930                         some_file, strerror(errno));
9931         }
9932         rc = llapi_hsm_request(fullpath, hur);
9933         if (rc) {
9934                 fprintf(stderr, "Cannot send HSM request (use of %s): %s\n",
9935                         some_file, strerror(-rc));
9936                 goto out_free;
9937         }
9938
9939 out_free:
9940         free(some_file);
9941         free(hur);
9942         return rc;
9943 }
9944
9945 static int lfs_hsm_archive(int argc, char **argv)
9946 {
9947         return lfs_hsm_request(argc, argv, HUA_ARCHIVE);
9948 }
9949
9950 static int lfs_hsm_restore(int argc, char **argv)
9951 {
9952         return lfs_hsm_request(argc, argv, HUA_RESTORE);
9953 }
9954
9955 static int lfs_hsm_release(int argc, char **argv)
9956 {
9957         return lfs_hsm_request(argc, argv, HUA_RELEASE);
9958 }
9959
9960 static int lfs_hsm_remove(int argc, char **argv)
9961 {
9962         return lfs_hsm_request(argc, argv, HUA_REMOVE);
9963 }
9964
9965 static int lfs_hsm_cancel(int argc, char **argv)
9966 {
9967         return lfs_hsm_request(argc, argv, HUA_CANCEL);
9968 }
9969
9970 static int lfs_swap_layouts(int argc, char **argv)
9971 {
9972         if (argc != 3)
9973                 return CMD_HELP;
9974
9975         return llapi_swap_layouts(argv[1], argv[2], 0, 0,
9976                                   SWAP_LAYOUTS_KEEP_MTIME |
9977                                   SWAP_LAYOUTS_KEEP_ATIME);
9978 }
9979
9980 static const char *const ladvise_names[] = LU_LADVISE_NAMES;
9981
9982 static const char *const lock_mode_names[] = LOCK_MODE_NAMES;
9983
9984 int lfs_get_mode(const char *string)
9985 {
9986         enum lock_mode_user mode;
9987
9988         for (mode = 0; mode < ARRAY_SIZE(lock_mode_names); mode++) {
9989                 if (lock_mode_names[mode] == NULL)
9990                         continue;
9991                 if (strcasecmp(string, lock_mode_names[mode]) == 0)
9992                         return mode;
9993         }
9994
9995         return -EINVAL;
9996 }
9997
9998 static enum lu_ladvise_type lfs_get_ladvice(const char *string)
9999 {
10000         enum lu_ladvise_type advice;
10001
10002         for (advice = 0;
10003              advice < ARRAY_SIZE(ladvise_names); advice++) {
10004                 if (ladvise_names[advice] == NULL)
10005                         continue;
10006                 if (strcmp(string, ladvise_names[advice]) == 0)
10007                         return advice;
10008         }
10009
10010         return LU_LADVISE_INVALID;
10011 }
10012
10013 static int lfs_ladvise(int argc, char **argv)
10014 {
10015         struct option long_opts[] = {
10016         { .val = 'a',   .name = "advice",       .has_arg = required_argument },
10017         { .val = 'b',   .name = "background",   .has_arg = no_argument },
10018         { .val = 'e',   .name = "end",          .has_arg = required_argument },
10019         { .val = 'h',   .name = "help",         .has_arg = no_argument },
10020         { .val = 'l',   .name = "length",       .has_arg = required_argument },
10021         { .val = 'm',   .name = "mode",         .has_arg = required_argument },
10022         { .val = 's',   .name = "start",        .has_arg = required_argument },
10023         { .val = 'u',   .name = "unset",        .has_arg = no_argument },
10024         { .name = NULL } };
10025         struct llapi_lu_ladvise advice;
10026         enum lu_ladvise_type advice_type = LU_LADVISE_INVALID;
10027         unsigned long long start = 0;
10028         unsigned long long end = LUSTRE_EOF;
10029         unsigned long long length = 0;
10030         unsigned long long size_units;
10031         unsigned long long flags = 0;
10032         int c, fd, rc = 0;
10033         const char *path;
10034         int mode = 0;
10035
10036         optind = 0;
10037         while ((c = getopt_long(argc, argv, "a:be:hl:m:s:u",
10038                                 long_opts, NULL)) != -1) {
10039                 switch (c) {
10040                 case 'a':
10041                         advice_type = lfs_get_ladvice(optarg);
10042                         if (advice_type == LU_LADVISE_INVALID) {
10043                                 fprintf(stderr,
10044                                         "%s: invalid advice type '%s'\n",
10045                                         progname, optarg);
10046                                 fprintf(stderr, "Valid types:");
10047
10048                                 for (advice_type = 0;
10049                                      advice_type < ARRAY_SIZE(ladvise_names);
10050                                      advice_type++) {
10051                                         if (ladvise_names[advice_type] == NULL)
10052                                                 continue;
10053                                         fprintf(stderr, " %s",
10054                                                 ladvise_names[advice_type]);
10055                                 }
10056                                 fprintf(stderr, "\n");
10057
10058                                 return CMD_HELP;
10059                         }
10060                         break;
10061                 case 'b':
10062                         flags |= LF_ASYNC;
10063                         break;
10064                 case 'u':
10065                         flags |= LF_UNSET;
10066                         break;
10067                 case 'e':
10068                         size_units = 1;
10069                         rc = llapi_parse_size(optarg, &end,
10070                                               &size_units, 0);
10071                         if (rc) {
10072                                 fprintf(stderr, "%s: bad end offset '%s'\n",
10073                                         argv[0], optarg);
10074                                 return CMD_HELP;
10075                         }
10076                         break;
10077                 case 's':
10078                         size_units = 1;
10079                         rc = llapi_parse_size(optarg, &start,
10080                                               &size_units, 0);
10081                         if (rc) {
10082                                 fprintf(stderr,
10083                                         "%s: bad start offset '%s'\n",
10084                                         argv[0], optarg);
10085                                 return CMD_HELP;
10086                         }
10087                         break;
10088                 case 'l':
10089                         size_units = 1;
10090                         rc = llapi_parse_size(optarg, &length,
10091                                               &size_units, 0);
10092                         if (rc) {
10093                                 fprintf(stderr, "%s: bad length '%s'\n",
10094                                         argv[0], optarg);
10095                                 return CMD_HELP;
10096                         }
10097                         break;
10098                 case 'm':
10099                         mode = lfs_get_mode(optarg);
10100                         if (mode < 0) {
10101                                 fprintf(stderr,
10102                                         "%s: bad mode '%s', valid modes are READ or WRITE\n",
10103                                         argv[0], optarg);
10104                                 return CMD_HELP;
10105                         }
10106                         break;
10107                 default:
10108                         fprintf(stderr, "%s: unrecognized option '%s'\n",
10109                                 progname, argv[optind - 1]);
10110                         /* fallthrough */
10111                 case 'h':
10112                         return CMD_HELP;
10113                 }
10114         }
10115
10116         if (advice_type == LU_LADVISE_INVALID) {
10117                 fprintf(stderr, "%s: please give an advice type\n", argv[0]);
10118                 fprintf(stderr, "Valid types:");
10119                 for (advice_type = 0; advice_type < ARRAY_SIZE(ladvise_names);
10120                      advice_type++) {
10121                         if (ladvise_names[advice_type] == NULL)
10122                                 continue;
10123                         fprintf(stderr, " %s", ladvise_names[advice_type]);
10124                 }
10125                 fprintf(stderr, "\n");
10126                 return CMD_HELP;
10127         }
10128
10129         if (advice_type == LU_LADVISE_LOCKNOEXPAND) {
10130                 fprintf(stderr,
10131                         "%s: Lock no expand advice is a per file descriptor advice, so when called from lfs, it does nothing.\n",
10132                         argv[0]);
10133                 return CMD_HELP;
10134         }
10135
10136         if (argc <= optind) {
10137                 fprintf(stderr, "%s: please give one or more file names\n",
10138                         argv[0]);
10139                 return CMD_HELP;
10140         }
10141
10142         if (end != LUSTRE_EOF && length != 0 && end != start + length) {
10143                 fprintf(stderr, "%s: conflicting arguments of -l and -e\n",
10144                         argv[0]);
10145                 return CMD_HELP;
10146         }
10147
10148         if (end == LUSTRE_EOF && length != 0)
10149                 end = start + length;
10150
10151         if (end <= start) {
10152                 fprintf(stderr, "%s: range [%llu, %llu] is invalid\n",
10153                         argv[0], start, end);
10154                 return CMD_HELP;
10155         }
10156
10157         if (advice_type != LU_LADVISE_LOCKAHEAD && mode != 0) {
10158                 fprintf(stderr, "%s: mode is only valid with lockahead\n",
10159                         argv[0]);
10160                 return CMD_HELP;
10161         }
10162
10163         if (advice_type == LU_LADVISE_LOCKAHEAD && mode == 0) {
10164                 fprintf(stderr, "%s: mode is required with lockahead\n",
10165                         argv[0]);
10166                 return CMD_HELP;
10167         }
10168
10169         while (optind < argc) {
10170                 int rc2;
10171
10172                 path = argv[optind++];
10173
10174                 fd = open(path, O_RDONLY);
10175                 if (fd < 0) {
10176                         fprintf(stderr, "%s: cannot open file '%s': %s\n",
10177                                 argv[0], path, strerror(errno));
10178                         rc2 = -errno;
10179                         goto next;
10180                 }
10181
10182                 advice.lla_start = start;
10183                 advice.lla_end = end;
10184                 advice.lla_advice = advice_type;
10185                 advice.lla_value1 = 0;
10186                 advice.lla_value2 = 0;
10187                 advice.lla_value3 = 0;
10188                 advice.lla_value4 = 0;
10189                 if (advice_type == LU_LADVISE_LOCKAHEAD) {
10190                         advice.lla_lockahead_mode = mode;
10191                         advice.lla_peradvice_flags = flags;
10192                 }
10193
10194                 rc2 = llapi_ladvise(fd, flags, 1, &advice);
10195                 close(fd);
10196                 if (rc2 < 0) {
10197                         fprintf(stderr,
10198                                 "%s: cannot give advice '%s' to file '%s': %s\n",
10199                                 argv[0], ladvise_names[advice_type],
10200                                 path, strerror(errno));
10201
10202                         goto next;
10203                 }
10204
10205 next:
10206                 if (rc == 0 && rc2 < 0)
10207                         rc = rc2;
10208         }
10209         return rc;
10210 }
10211
10212 static const char *const heat_names[] = LU_HEAT_NAMES;
10213
10214 static int lfs_heat_get(int argc, char **argv)
10215 {
10216         struct lu_heat *heat;
10217         int rc = 0, rc2;
10218         char *path;
10219         int fd;
10220         int i;
10221
10222         if (argc <= 1)
10223                 return CMD_HELP;
10224
10225         heat = calloc(sizeof(*heat) + sizeof(__u64) * OBD_HEAT_COUNT, 1);
10226         if (!heat) {
10227                 fprintf(stderr, "%s: memory allocation failed\n", argv[0]);
10228                 return -ENOMEM;
10229         }
10230
10231         optind = 1;
10232         while (optind < argc) {
10233                 path = argv[optind++];
10234
10235                 fd = open(path, O_RDONLY);
10236                 if (fd < 0) {
10237                         fprintf(stderr, "%s: cannot open file '%s': %s\n",
10238                                 argv[0], path, strerror(errno));
10239                         rc2 = -errno;
10240                         goto next;
10241                 }
10242
10243                 heat->lh_count = OBD_HEAT_COUNT;
10244                 rc2 = llapi_heat_get(fd, heat);
10245                 close(fd);
10246                 if (rc2 < 0) {
10247                         fprintf(stderr,
10248                                 "%s: cannot get heat of file '%s': %s\n",
10249                                 argv[0], path, strerror(errno));
10250                         goto next;
10251                 }
10252
10253                 printf("flags: %x\n", heat->lh_flags);
10254                 for (i = 0; i < heat->lh_count; i++)
10255                         printf("%s: %llu\n", heat_names[i],
10256                                (unsigned long long)heat->lh_heat[i]);
10257 next:
10258                 if (rc == 0 && rc2 < 0)
10259                         rc = rc2;
10260         }
10261
10262         free(heat);
10263         return rc;
10264 }
10265
10266 static int lfs_heat_set(int argc, char **argv)
10267 {
10268         struct option long_opts[] = {
10269         { .val = 'c',   .name = "clear",        .has_arg = no_argument },
10270         { .val = 'h',   .name = "help",         .has_arg = no_argument },
10271         { .val = 'o',   .name = "off",          .has_arg = no_argument },
10272         { .val = 'O',   .name = "on",           .has_arg = no_argument },
10273         { .name = NULL } };
10274         enum lu_heat_flag flags = 0;
10275         int rc = 0, rc2;
10276         char *path;
10277         int fd;
10278         int c;
10279
10280         if (argc <= 1)
10281                 return CMD_HELP;
10282
10283         optind = 0;
10284         while ((c = getopt_long(argc, argv, "choO", long_opts, NULL)) != -1) {
10285                 switch (c) {
10286                 case 'c':
10287                         flags |= LU_HEAT_FLAG_CLEAR;
10288                         break;
10289                 case 'o':
10290                         flags |= LU_HEAT_FLAG_CLEAR;
10291                         flags |= LU_HEAT_FLAG_OFF;
10292                         break;
10293                 case 'O':
10294                         flags &= ~LU_HEAT_FLAG_OFF;
10295                         break;
10296                 default:
10297                         fprintf(stderr, "%s: unrecognized option '%s'\n",
10298                                 progname, argv[optind - 1]);
10299                         /* fallthrough */
10300                 case 'h':
10301                         return CMD_HELP;
10302                 }
10303         }
10304
10305         if (argc <= optind) {
10306                 fprintf(stderr, "%s: please give one or more file names\n",
10307                         argv[0]);
10308                 return CMD_HELP;
10309         }
10310
10311         while (optind < argc) {
10312                 path = argv[optind++];
10313
10314                 fd = open(path, O_RDONLY);
10315                 if (fd < 0) {
10316                         fprintf(stderr, "%s: cannot open file '%s': %s\n",
10317                                 argv[0], path, strerror(errno));
10318                         rc2 = -errno;
10319                         goto next;
10320                 }
10321
10322                 rc2 = llapi_heat_set(fd, flags);
10323                 close(fd);
10324                 if (rc2 < 0) {
10325                         fprintf(stderr,
10326                                 "%s: cannot setflags heat of file '%s': %s\n",
10327                                 argv[0], path, strerror(errno));
10328                         goto next;
10329                 }
10330 next:
10331                 if (rc == 0 && rc2 < 0)
10332                         rc = rc2;
10333         }
10334         return rc;
10335 }
10336
10337 /**
10338  * The input string contains a comma delimited list of component ids and
10339  * ranges, for example "1,2-4,7".
10340  */
10341 static int parse_mirror_ids(__u16 *ids, int size, char *arg)
10342 {
10343         bool end_of_loop = false;
10344         char *ptr = NULL;
10345         int nr = 0;
10346         int rc;
10347
10348         if (!arg)
10349                 return -EINVAL;
10350
10351         while (!end_of_loop) {
10352                 int start_index;
10353                 int end_index;
10354                 int i;
10355                 char *endptr = NULL;
10356
10357                 rc = -EINVAL;
10358                 ptr = strchrnul(arg, ',');
10359                 end_of_loop = *ptr == '\0';
10360                 *ptr = '\0';
10361
10362                 start_index = strtol(arg, &endptr, 0);
10363                 if (endptr == arg) /* no data at all */
10364                         break;
10365                 if (*endptr != '-' && *endptr != '\0') /* has invalid data */
10366                         break;
10367                 if (start_index < 0)
10368                         break;
10369
10370                 end_index = start_index;
10371                 if (*endptr == '-') {
10372                         end_index = strtol(endptr + 1, &endptr, 0);
10373                         if (*endptr != '\0')
10374                                 break;
10375                         if (end_index < start_index)
10376                                 break;
10377                 }
10378
10379                 for (i = start_index; i <= end_index && size > 0; i++) {
10380                         int j;
10381
10382                         /* remove duplicate */
10383                         for (j = 0; j < nr; j++) {
10384                                 if (ids[j] == i)
10385                                         break;
10386                         }
10387                         if (j == nr) { /* no duplicate */
10388                                 ids[nr++] = i;
10389                                 --size;
10390                         }
10391                 }
10392
10393                 if (size == 0 && i < end_index)
10394                         break;
10395
10396                 *ptr = ',';
10397                 arg = ++ptr;
10398                 rc = 0;
10399         }
10400         if (!end_of_loop && ptr)
10401                 *ptr = ',';
10402
10403         return rc < 0 ? rc : nr;
10404 }
10405
10406 /**
10407  * struct verify_mirror_id - Mirror id to be verified.
10408  * @mirror_id:   A specified mirror id.
10409  * @is_valid_id: @mirror_id is valid or not in the mirrored file.
10410  */
10411 struct verify_mirror_id {
10412         __u16 mirror_id;
10413         bool is_valid_id;
10414 };
10415
10416 /**
10417  * compare_mirror_ids() - Compare mirror ids.
10418  * @layout: Mirror component list.
10419  * @cbdata: Callback data in verify_mirror_id structure.
10420  *
10421  * This is a callback function called by llapi_layout_comp_iterate()
10422  * to compare the specified mirror id with the one in the current
10423  * component of @layout. If they are the same, then the specified
10424  * mirror id is valid.
10425  *
10426  * Return: a negative error code on failure or
10427  *         LLAPI_LAYOUT_ITER_CONT: Proceed iteration
10428  *         LLAPI_LAYOUT_ITER_STOP: Stop iteration
10429  */
10430 static inline
10431 int compare_mirror_ids(struct llapi_layout *layout, void *cbdata)
10432 {
10433         struct verify_mirror_id *mirror_id_cbdata =
10434                                  (struct verify_mirror_id *)cbdata;
10435         uint32_t mirror_id;
10436         int rc = 0;
10437
10438         rc = llapi_layout_mirror_id_get(layout, &mirror_id);
10439         if (rc < 0) {
10440                 rc = -errno;
10441                 fprintf(stderr,
10442                         "%s: llapi_layout_mirror_id_get failed: %s.\n",
10443                         progname, strerror(errno));
10444                 return rc;
10445         }
10446
10447         if (mirror_id_cbdata->mirror_id == mirror_id) {
10448                 mirror_id_cbdata->is_valid_id = true;
10449                 return LLAPI_LAYOUT_ITER_STOP;
10450         }
10451
10452         return LLAPI_LAYOUT_ITER_CONT;
10453 }
10454
10455 /**
10456  * verify_mirror_ids() - Verify specified mirror ids.
10457  * @fname:      Mirrored file name.
10458  * @mirror_ids: Specified mirror ids to be verified.
10459  * @ids_nr:     Number of specified mirror ids.
10460  *
10461  * This function verifies that specified @mirror_ids are valid
10462  * in the mirrored file @fname.
10463  *
10464  * Return: 0 on success or a negative error code on failure.
10465  */
10466 static inline
10467 int verify_mirror_ids(const char *fname, __u16 *mirror_ids, int ids_nr)
10468 {
10469         struct llapi_layout *layout = NULL;
10470         struct verify_mirror_id mirror_id_cbdata = { 0 };
10471         struct stat stbuf;
10472         uint32_t flr_state;
10473         int i;
10474         int fd;
10475         int rc = 0;
10476         int rc2 = 0;
10477
10478         if (ids_nr <= 0)
10479                 return -EINVAL;
10480
10481         if (stat(fname, &stbuf) < 0) {
10482                 fprintf(stderr, "%s: cannot stat file '%s': %s.\n",
10483                         progname, fname, strerror(errno));
10484                 rc = -errno;
10485                 goto error;
10486         }
10487
10488         if (!S_ISREG(stbuf.st_mode)) {
10489                 fprintf(stderr, "%s: '%s' is not a regular file.\n",
10490                         progname, fname);
10491                 rc = -EINVAL;
10492                 goto error;
10493         }
10494
10495         fd = open(fname, O_DIRECT | O_RDONLY);
10496         if (fd < 0) {
10497                 fprintf(stderr, "%s: cannot open '%s': %s.\n",
10498                         progname, fname, strerror(errno));
10499                 rc = -errno;
10500                 goto error;
10501         }
10502
10503         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
10504         if (rc < 0) {
10505                 fprintf(stderr, "%s: '%s' llapi_lease_acquire failed: %s.\n",
10506                         progname, fname, strerror(errno));
10507                 goto close_fd;
10508         }
10509
10510         layout = llapi_layout_get_by_fd(fd, 0);
10511         if (!layout) {
10512                 fprintf(stderr, "%s: '%s' llapi_layout_get_by_fd failed: %s.\n",
10513                         progname, fname, strerror(errno));
10514                 rc = -errno;
10515                 llapi_lease_release(fd);
10516                 goto close_fd;
10517         }
10518
10519         rc = llapi_layout_flags_get(layout, &flr_state);
10520         if (rc < 0) {
10521                 fprintf(stderr, "%s: '%s' llapi_layout_flags_get failed: %s.\n",
10522                         progname, fname, strerror(errno));
10523                 rc = -errno;
10524                 goto free_layout;
10525         }
10526
10527         flr_state &= LCM_FL_FLR_MASK;
10528         switch (flr_state) {
10529         case LCM_FL_NONE:
10530                 rc = -EINVAL;
10531                 fprintf(stderr, "%s: '%s' file state error: %s.\n",
10532                         progname, fname, llapi_layout_flags_string(flr_state));
10533                 goto free_layout;
10534         default:
10535                 break;
10536         }
10537
10538         rc2 = 0;
10539         for (i = 0; i < ids_nr; i++) {
10540                 mirror_id_cbdata.mirror_id = mirror_ids[i];
10541                 mirror_id_cbdata.is_valid_id = false;
10542
10543                 rc = llapi_layout_comp_iterate(layout, compare_mirror_ids,
10544                                                &mirror_id_cbdata);
10545                 if (rc < 0) {
10546                         rc = -errno;
10547                         fprintf(stderr,
10548                                 "%s: '%s' failed to verify mirror id: %u.\n",
10549                                 progname, fname, mirror_ids[i]);
10550                         goto free_layout;
10551                 }
10552
10553                 if (!mirror_id_cbdata.is_valid_id) {
10554                         rc2 = -EINVAL;
10555                         fprintf(stderr,
10556                                 "%s: '%s' invalid specified mirror id: %u.\n",
10557                                 progname, fname, mirror_ids[i]);
10558                 }
10559         }
10560         rc = rc2;
10561
10562 free_layout:
10563         llapi_layout_free(layout);
10564         llapi_lease_release(fd);
10565 close_fd:
10566         close(fd);
10567 error:
10568         return rc;
10569 }
10570
10571 static inline
10572 int lfs_mirror_resync_file(const char *fname, struct ll_ioc_lease *ioc,
10573                            __u16 *mirror_ids, int ids_nr)
10574 {
10575         struct llapi_resync_comp comp_array[1024] = { { 0 } };
10576         struct llapi_layout *layout;
10577         struct stat stbuf;
10578         uint32_t flr_state;
10579         uint64_t start;
10580         uint64_t end;
10581         int comp_size = 0;
10582         int idx;
10583         int fd;
10584         int rc;
10585         int rc2;
10586
10587         if (stat(fname, &stbuf) < 0) {
10588                 fprintf(stderr, "%s: cannot stat file '%s': %s.\n",
10589                         progname, fname, strerror(errno));
10590                 rc = -errno;
10591                 goto error;
10592         }
10593         if (!S_ISREG(stbuf.st_mode)) {
10594                 fprintf(stderr, "%s: '%s' is not a regular file.\n",
10595                         progname, fname);
10596                 rc = -EINVAL;
10597                 goto error;
10598         }
10599
10600         /* Allow mirror resync even without the key on encrypted files */
10601         fd = open(fname, O_DIRECT | O_RDWR | O_FILE_ENC);
10602         if (fd < 0) {
10603                 fprintf(stderr, "%s: cannot open '%s': %s.\n",
10604                         progname, fname, strerror(errno));
10605                 rc = -errno;
10606                 goto error;
10607         }
10608
10609         layout = llapi_layout_get_by_fd(fd, 0);
10610         if (!layout) {
10611                 fprintf(stderr, "%s: '%s' llapi_layout_get_by_fd failed: %s.\n",
10612                         progname, fname, strerror(errno));
10613                 rc = -errno;
10614                 goto close_fd;
10615         }
10616
10617         rc = llapi_layout_flags_get(layout, &flr_state);
10618         if (rc) {
10619                 fprintf(stderr, "%s: '%s' llapi_layout_flags_get failed: %s.\n",
10620                         progname, fname, strerror(errno));
10621                 rc = -errno;
10622                 goto free_layout;
10623         }
10624
10625         flr_state &= LCM_FL_FLR_MASK;
10626         if (flr_state == LCM_FL_NONE) {
10627                 rc = -EINVAL;
10628                 fprintf(stderr, "%s: '%s' is not a FLR file.\n",
10629                         progname, fname);
10630                 goto free_layout;
10631         }
10632
10633         /* get stale component info */
10634         comp_size = llapi_mirror_find_stale(layout, comp_array,
10635                                             ARRAY_SIZE(comp_array),
10636                                             mirror_ids, ids_nr);
10637         if (comp_size <= 0) {
10638                 rc = comp_size;
10639                 goto free_layout;
10640         }
10641
10642         ioc->lil_mode = LL_LEASE_WRLCK;
10643         ioc->lil_flags = LL_LEASE_RESYNC;
10644         rc = llapi_lease_set(fd, ioc);
10645         if (rc < 0) {
10646                 if (rc == -EALREADY)
10647                         rc = 0;
10648                 else
10649                         fprintf(stderr,
10650                             "%s: '%s' llapi_lease_get_ext resync failed: %s.\n",
10651                                 progname, fname, strerror(-rc));
10652                 goto free_layout;
10653         }
10654
10655         /* get the read range [start, end) */
10656         start = comp_array[0].lrc_start;
10657         end = comp_array[0].lrc_end;
10658         for (idx = 1; idx < comp_size; idx++) {
10659                 if (comp_array[idx].lrc_start < start)
10660                         start = comp_array[idx].lrc_start;
10661                 if (end < comp_array[idx].lrc_end)
10662                         end = comp_array[idx].lrc_end;
10663         }
10664
10665         rc = llapi_lease_check(fd);
10666         if (rc != LL_LEASE_WRLCK) {
10667                 fprintf(stderr, "%s: '%s' lost lease lock.\n",
10668                         progname, fname);
10669                 goto free_layout;
10670         }
10671
10672         rc = llapi_mirror_resync_many(fd, layout, comp_array, comp_size,
10673                                       start, end);
10674         if (rc < 0)
10675                 fprintf(stderr, "%s: '%s' llapi_mirror_resync_many: %s.\n",
10676                         progname, fname, strerror(-rc));
10677
10678         rc = migrate_set_timestamps(fd, &stbuf);
10679         if (rc < 0) {
10680                 fprintf(stderr, "%s: '%s' cannot set timestamps: %s\n",
10681                         progname, fname, strerror(-rc));
10682                 goto free_layout;
10683         }
10684
10685         /* need to do the lease unlock even resync fails */
10686         ioc->lil_mode = LL_LEASE_UNLCK;
10687         ioc->lil_flags = LL_LEASE_RESYNC_DONE;
10688         ioc->lil_count = 0;
10689         for (idx = 0; idx < comp_size; idx++) {
10690                 if (comp_array[idx].lrc_synced) {
10691                         ioc->lil_ids[ioc->lil_count] = comp_array[idx].lrc_id;
10692                         ioc->lil_count++;
10693                 }
10694         }
10695
10696         rc2 = llapi_lease_set(fd, ioc);
10697         /**
10698          * llapi_lease_set returns lease mode when it request to unlock
10699          * the lease lock.
10700          */
10701         if (rc2 <= 0) {
10702                 /* rc2 == 0 means lost lease lock */
10703                 if (rc2 == 0 && rc == 0)
10704                         rc = -EBUSY;
10705                 else
10706                         rc = rc2;
10707                 fprintf(stderr, "%s: resync file '%s' failed: %s.\n",
10708                         progname, fname,
10709                         rc2 == 0 ? "lost lease lock" : strerror(-rc2));
10710
10711                 llapi_lease_release(fd);
10712                 goto free_layout;
10713         }
10714
10715 free_layout:
10716         llapi_layout_free(layout);
10717 close_fd:
10718         close(fd);
10719 error:
10720         return rc;
10721 }
10722
10723 static inline int lfs_mirror_resync(int argc, char **argv)
10724 {
10725         struct option long_opts[] = {
10726         { .val = 'h',   .name = "help",         .has_arg = no_argument },
10727         { .val = 'o',   .name = "only",         .has_arg = required_argument },
10728         { .name = NULL } };
10729         struct ll_ioc_lease *ioc = NULL;
10730         __u16 mirror_ids[128] = { 0 };
10731         int ids_nr = 0;
10732         int c;
10733         int rc = 0;
10734
10735         while ((c = getopt_long(argc, argv, "ho:", long_opts, NULL)) >= 0) {
10736                 switch (c) {
10737                 case 'o':
10738                         rc = parse_mirror_ids(mirror_ids,
10739                                         sizeof(mirror_ids) / sizeof(__u16),
10740                                         optarg);
10741                         if (rc < 0) {
10742                                 fprintf(stderr,
10743                                         "%s: bad mirror ids '%s'.\n",
10744                                         argv[0], optarg);
10745                                 goto error;
10746                         }
10747                         ids_nr = rc;
10748                         break;
10749                 default:
10750                         fprintf(stderr, "%s: unrecognized option '%s'\n",
10751                                 progname, argv[optind - 1]);
10752                         /* fallthrough */
10753                 case 'h':
10754                         rc = CMD_HELP;
10755                         goto error;
10756                 }
10757         }
10758
10759         if (argc == optind) {
10760                 fprintf(stderr, "%s: no file name given.\n", argv[0]);
10761                 rc = CMD_HELP;
10762                 goto error;
10763         }
10764
10765         if (ids_nr > 0 && argc > optind + 1) {
10766                 fprintf(stderr,
10767                     "%s: option '--only' cannot be used upon multiple files.\n",
10768                         argv[0]);
10769                 rc = CMD_HELP;
10770                 goto error;
10771         }
10772
10773         if (ids_nr > 0) {
10774                 rc = verify_mirror_ids(argv[optind], mirror_ids, ids_nr);
10775                 if (rc < 0)
10776                         goto error;
10777         }
10778
10779         /* set the lease on the file */
10780         ioc = calloc(sizeof(*ioc) + sizeof(__u32) * 4096, 1);
10781         if (!ioc) {
10782                 fprintf(stderr, "%s: cannot alloc id array for ioc: %s.\n",
10783                         argv[0], strerror(errno));
10784                 rc = -errno;
10785                 goto error;
10786         }
10787
10788         for (; optind < argc; optind++) {
10789                 rc = lfs_mirror_resync_file(argv[optind], ioc,
10790                                             mirror_ids, ids_nr);
10791                 /* ignore previous file's error, continue with next file */
10792
10793                 /* reset ioc */
10794                 memset(ioc, 0, sizeof(*ioc) + sizeof(__u32) * 4096);
10795         }
10796
10797         free(ioc);
10798 error:
10799         return rc;
10800 }
10801
10802 static inline int verify_mirror_id_by_fd(int fd, __u16 mirror_id)
10803 {
10804         struct llapi_layout *layout;
10805         int rc;
10806
10807         layout = llapi_layout_get_by_fd(fd, 0);
10808         if (!layout) {
10809                 fprintf(stderr, "could not get layout.\n");
10810                 return  -EINVAL;
10811         }
10812
10813         rc = llapi_layout_comp_iterate(layout, find_mirror_id, &mirror_id);
10814         if (rc < 0) {
10815                 fprintf(stderr, "failed to iterate layout\n");
10816                 llapi_layout_free(layout);
10817
10818                 return rc;
10819         } else if (rc == LLAPI_LAYOUT_ITER_CONT) {
10820                 fprintf(stderr, "does not find mirror with ID %u\n", mirror_id);
10821                 llapi_layout_free(layout);
10822
10823                 return -EINVAL;
10824         }
10825         llapi_layout_free(layout);
10826
10827         return 0;
10828 }
10829
10830 /**
10831  * Check whether two files are the same file
10832  * \retval      0  same file
10833  * \retval      1  not the same file
10834  * \retval      <0 error code
10835  */
10836 static inline int check_same_file(int fd, const char *f2)
10837 {
10838         struct stat stbuf1;
10839         struct stat stbuf2;
10840
10841         if (fstat(fd, &stbuf1) < 0)
10842                 return -errno;
10843
10844         if (stat(f2, &stbuf2) < 0)
10845                 return 1;
10846
10847         if (stbuf1.st_rdev == stbuf2.st_rdev &&
10848             stbuf1.st_ino == stbuf2.st_ino)
10849                 return 0;
10850
10851         return 1;
10852 }
10853
10854 static inline int lfs_mirror_read(int argc, char **argv)
10855 {
10856         int rc = CMD_HELP;
10857         __u16 mirror_id = 0;
10858         const char *outfile = NULL;
10859         char *fname;
10860         int fd = 0;
10861         int outfd;
10862         int c;
10863         void *buf;
10864         const size_t buflen = 4 << 20;
10865         off_t pos;
10866         struct option long_opts[] = {
10867         { .val = 'h',   .name = "help",         .has_arg = no_argument },
10868         { .val = 'N',   .name = "mirror-id",    .has_arg = required_argument },
10869         { .val = 'o',   .name = "outfile",      .has_arg = required_argument },
10870         { .name = NULL } };
10871
10872         while ((c = getopt_long(argc, argv, "hN:o:", long_opts, NULL)) >= 0) {
10873                 char *end;
10874
10875                 switch (c) {
10876                 case 'N': {
10877                         unsigned long int id;
10878
10879                         errno = 0;
10880                         id = strtoul(optarg, &end, 0);
10881                         if (errno != 0 || *end != '\0' || id == 0 ||
10882                             id > UINT16_MAX) {
10883                                 fprintf(stderr,
10884                                         "%s %s: invalid mirror ID '%s'\n",
10885                                         progname, argv[0], optarg);
10886                                 return rc;
10887                         }
10888
10889                         mirror_id = (__u16)id;
10890                         break;
10891                 }
10892                 case 'o':
10893                         outfile = optarg;
10894                         break;
10895                 default:
10896                         fprintf(stderr, "%s: unrecognized option '%s'\n",
10897                                 progname, argv[optind - 1]);
10898                         /* fallthrough */
10899                 case 'h':
10900                         return CMD_HELP;
10901                 }
10902         }
10903
10904         if (argc == optind) {
10905                 fprintf(stderr, "%s %s: no mirrored file provided\n",
10906                         progname, argv[0]);
10907                 return rc;
10908         } else if (argc > optind + 1) {
10909                 fprintf(stderr, "%s %s: too many files\n", progname, argv[0]);
10910                 return rc;
10911         }
10912
10913         if (mirror_id == 0) {
10914                 fprintf(stderr, "%s %s: no valid mirror ID is provided\n",
10915                         progname, argv[0]);
10916                 return rc;
10917         }
10918
10919         /* open mirror file */
10920         fname = argv[optind];
10921         fd = open(fname, O_DIRECT | O_RDONLY);
10922         if (fd < 0) {
10923                 fprintf(stderr, "%s %s: cannot open '%s': %s\n",
10924                         progname, argv[0], fname, strerror(errno));
10925                 return rc;
10926         }
10927
10928         /* verify mirror id */
10929         rc = verify_mirror_id_by_fd(fd, mirror_id);
10930         if (rc) {
10931                 fprintf(stderr,
10932                         "%s %s: cannot find mirror with ID %u in '%s'\n",
10933                         progname, argv[0], mirror_id, fname);
10934                 goto close_fd;
10935         }
10936
10937         /* open output file - O_EXCL ensures output is not the same as input */
10938         if (outfile) {
10939                 outfd = open(outfile, O_EXCL | O_WRONLY | O_CREAT, 0644);
10940                 if (outfd < 0) {
10941                         fprintf(stderr, "%s %s: cannot create file '%s': %s\n",
10942                                 progname, argv[0], outfile, strerror(errno));
10943                         rc = -errno;
10944                         goto close_fd;
10945                 }
10946         } else {
10947                 outfd = STDOUT_FILENO;
10948         }
10949
10950         /* allocate buffer */
10951         rc = posix_memalign(&buf, sysconf(_SC_PAGESIZE), buflen);
10952         if (rc) {
10953                 fprintf(stderr, "%s %s: posix_memalign returns %d\n",
10954                                 progname, argv[0], rc);
10955                 goto close_outfd;
10956         }
10957
10958         pos = 0;
10959         while (1) {
10960                 ssize_t bytes_read;
10961                 ssize_t written = 0;
10962
10963                 bytes_read = llapi_mirror_read(fd, mirror_id, buf, buflen, pos);
10964                 if (bytes_read < 0) {
10965                         rc = bytes_read;
10966                         fprintf(stderr,
10967                                 "%s %s: fail to read data from mirror %u: %s\n",
10968                                 progname, argv[0], mirror_id, strerror(-rc));
10969                         goto free_buf;
10970                 }
10971
10972                 /* EOF reached */
10973                 if (bytes_read == 0)
10974                         break;
10975
10976                 while (written < bytes_read) {
10977                         ssize_t written2;
10978
10979                         written2 = write(outfd, buf + written,
10980                                          bytes_read - written);
10981                         if (written2 < 0) {
10982                                 fprintf(stderr,
10983                                         "%s %s: fail to write %s: %s\n",
10984                                         progname, argv[0], outfile ? : "STDOUT",
10985                                         strerror(errno));
10986                                 rc = -errno;
10987                                 goto free_buf;
10988                         }
10989                         written += written2;
10990                 }
10991
10992                 if (written != bytes_read) {
10993                         fprintf(stderr,
10994                 "%s %s: written %ld bytes does not match with %ld read.\n",
10995                                 progname, argv[0], written, bytes_read);
10996                         rc = -EIO;
10997                         goto free_buf;
10998                 }
10999
11000                 pos += bytes_read;
11001         }
11002
11003         fsync(outfd);
11004         rc = 0;
11005
11006 free_buf:
11007         free(buf);
11008 close_outfd:
11009         if (outfile)
11010                 close(outfd);
11011 close_fd:
11012         close(fd);
11013
11014         return rc;
11015 }
11016
11017 static inline int lfs_mirror_write(int argc, char **argv)
11018 {
11019         int rc = CMD_HELP;
11020         __u16 mirror_id = 0;
11021         const char *inputfile = NULL;
11022         char *fname;
11023         int fd = 0;
11024         int inputfd;
11025         int c;
11026         void *buf;
11027         const size_t buflen = 4 << 20;
11028         off_t pos;
11029         size_t page_size = sysconf(_SC_PAGESIZE);
11030         struct ll_ioc_lease_id ioc;
11031         struct option long_opts[] = {
11032         { .val = 'h',   .name = "help",         .has_arg = no_argument },
11033         { .val = 'i',   .name = "inputfile",    .has_arg = required_argument },
11034         { .val = 'N',   .name = "mirror-id",    .has_arg = required_argument },
11035         { .name = NULL } };
11036
11037         while ((c = getopt_long(argc, argv, "hi:N:", long_opts, NULL)) >= 0) {
11038                 char *end;
11039
11040                 switch (c) {
11041                 case 'N': {
11042                         unsigned long int id;
11043
11044                         errno = 0;
11045                         id = strtoul(optarg, &end, 0);
11046                         if (errno != 0 || *end != '\0' || id == 0 ||
11047                             id > UINT16_MAX) {
11048                                 fprintf(stderr,
11049                                         "%s %s: invalid mirror ID '%s'\n",
11050                                         progname, argv[0], optarg);
11051                                 return rc;
11052                         }
11053
11054                         mirror_id = (__u16)id;
11055                         break;
11056                 }
11057                 case 'i':
11058                         inputfile = optarg;
11059                         break;
11060                 default:
11061                         fprintf(stderr, "%s: unrecognized option '%s'\n",
11062                                 progname, argv[optind - 1]);
11063                         /* fallthrough */
11064                 case 'h':
11065                         return CMD_HELP;
11066                 }
11067         }
11068
11069         if (argc == optind) {
11070                 fprintf(stderr, "%s %s: no mirrored file provided\n",
11071                         progname, argv[0]);
11072                 return rc;
11073         } else if (argc > optind + 1) {
11074                 fprintf(stderr, "%s %s: too many files\n", progname, argv[0]);
11075                 return rc;
11076         }
11077
11078         if (mirror_id == 0) {
11079                 fprintf(stderr, "%s %s: no valid mirror ID is provided\n",
11080                         progname, argv[0]);
11081                 return rc;
11082         }
11083
11084         /* open mirror file */
11085         fname = argv[optind];
11086         fd = open(fname, O_DIRECT | O_WRONLY);
11087         if (fd < 0) {
11088                 fprintf(stderr, "%s %s: cannot open '%s': %s\n",
11089                         progname, argv[0], fname, strerror(errno));
11090                 return rc;
11091         }
11092
11093         /* verify mirror id */
11094         rc = verify_mirror_id_by_fd(fd, mirror_id);
11095         if (rc) {
11096                 fprintf(stderr,
11097                         "%s %s: cannot find mirror with ID %u in '%s'\n",
11098                         progname, argv[0], mirror_id, fname);
11099                 goto close_fd;
11100         }
11101
11102         /* open input file */
11103         if (inputfile) {
11104                 rc = check_same_file(fd, inputfile);
11105                 if (rc == 0) {
11106                         fprintf(stderr,
11107                         "%s %s: input file cannot be the mirrored file\n",
11108                                 progname, argv[0]);
11109                         goto close_fd;
11110                 }
11111                 if (rc < 0)
11112                         goto close_fd;
11113
11114                 inputfd = open(inputfile, O_RDONLY, 0644);
11115                 if (inputfd < 0) {
11116                         fprintf(stderr, "%s %s: cannot open file '%s': %s\n",
11117                                 progname, argv[0], inputfile, strerror(errno));
11118                         rc = -errno;
11119                         goto close_fd;
11120                 }
11121         } else {
11122                 inputfd = STDIN_FILENO;
11123         }
11124
11125         /* allocate buffer */
11126         rc = posix_memalign(&buf, page_size, buflen);
11127         if (rc) {
11128                 fprintf(stderr, "%s %s: posix_memalign returns %d\n",
11129                         progname, argv[0], rc);
11130                 goto close_inputfd;
11131         }
11132
11133         /* prepare target mirror components instantiation */
11134         ioc.lil_mode = LL_LEASE_WRLCK;
11135         ioc.lil_flags = LL_LEASE_RESYNC;
11136         ioc.lil_mirror_id = mirror_id;
11137         rc = llapi_lease_set(fd, (struct ll_ioc_lease *)&ioc);
11138         if (rc < 0) {
11139                 fprintf(stderr,
11140                         "%s %s: '%s' llapi_lease_get_ext failed: %s\n",
11141                         progname, argv[0], fname, strerror(errno));
11142                 goto free_buf;
11143         }
11144
11145         pos = 0;
11146         while (1) {
11147                 ssize_t bytes_read;
11148                 ssize_t written;
11149                 size_t to_write;
11150
11151                 rc = llapi_lease_check(fd);
11152                 if (rc != LL_LEASE_WRLCK) {
11153                         fprintf(stderr, "%s %s: '%s' lost lease lock\n",
11154                                 progname, argv[0], fname);
11155                         goto free_buf;
11156                 }
11157
11158                 bytes_read = read(inputfd, buf, buflen);
11159                 if (bytes_read < 0) {
11160                         rc = bytes_read;
11161                         fprintf(stderr,
11162                                 "%s %s: fail to read data from '%s': %s\n",
11163                                 progname, argv[0], inputfile ? : "STDIN",
11164                                 strerror(errno));
11165                         rc = -errno;
11166                         goto free_buf;
11167                 }
11168
11169                 /* EOF reached */
11170                 if (bytes_read == 0)
11171                         break;
11172
11173                 /* round up to page align to make direct IO happy. */
11174                 to_write = (bytes_read + page_size - 1) & ~(page_size - 1);
11175
11176                 written = llapi_mirror_write(fd, mirror_id, buf, to_write,
11177                                              pos);
11178                 if (written < 0) {
11179                         rc = written;
11180                         fprintf(stderr,
11181                               "%s %s: fail to write to mirror %u: %s\n",
11182                                 progname, argv[0], mirror_id,
11183                                 strerror(-rc));
11184                         goto free_buf;
11185                 }
11186
11187                 pos += bytes_read;
11188         }
11189
11190         if (pos & (page_size - 1)) {
11191                 rc = llapi_mirror_truncate(fd, mirror_id, pos);
11192                 if (rc < 0)
11193                         goto free_buf;
11194         }
11195
11196         ioc.lil_mode = LL_LEASE_UNLCK;
11197         ioc.lil_flags = LL_LEASE_RESYNC_DONE;
11198         ioc.lil_count = 0;
11199         rc = llapi_lease_set(fd, (struct ll_ioc_lease *)&ioc);
11200         if (rc <= 0) {
11201                 if (rc == 0)
11202                         rc = -EBUSY;
11203                 fprintf(stderr,
11204                         "%s %s: release lease lock of '%s' failed: %s\n",
11205                         progname, argv[0], fname, strerror(errno));
11206                 goto free_buf;
11207         }
11208
11209         rc = 0;
11210
11211 free_buf:
11212         free(buf);
11213 close_inputfd:
11214         if (inputfile)
11215                 close(inputfd);
11216 close_fd:
11217         close(fd);
11218
11219         return rc;
11220 }
11221
11222 static inline int get_other_mirror_ids(int fd, __u16 *ids, __u16 exclude_id)
11223 {
11224         struct llapi_layout *layout;
11225         struct collect_ids_data cid = { .cid_ids = ids,
11226                                         .cid_count = 0,
11227                                         .cid_exclude = exclude_id, };
11228         int rc;
11229
11230         layout = llapi_layout_get_by_fd(fd, 0);
11231         if (!layout) {
11232                 fprintf(stderr, "could not get layout\n");
11233                 return -EINVAL;
11234         }
11235
11236         rc = llapi_layout_comp_iterate(layout, collect_mirror_id, &cid);
11237         if (rc < 0) {
11238                 fprintf(stderr, "failed to iterate layout\n");
11239                 llapi_layout_free(layout);
11240
11241                 return rc;
11242         }
11243         llapi_layout_free(layout);
11244
11245         return cid.cid_count;
11246 }
11247
11248 #ifndef MIRROR_ID_NEG
11249 #define MIRROR_ID_NEG         0x8000
11250 #endif
11251
11252 static inline int lfs_mirror_copy(int argc, char **argv)
11253 {
11254         int rc = CMD_HELP;
11255         __u16 read_mirror_id = 0;
11256         __u16 ids[128] = { 0 };
11257         int count = 0;
11258         struct llapi_layout *layout = NULL;
11259         struct llapi_resync_comp comp_array[1024] = { { 0 } };
11260         int comp_size = 0;
11261         char *fname;
11262         int fd = 0;
11263         int c;
11264         int i;
11265         ssize_t copied;
11266         struct ll_ioc_lease *ioc = NULL;
11267         struct ll_ioc_lease_id *resync_ioc;
11268         struct option long_opts[] = {
11269         { .val = 'h',   .name = "help",         .has_arg = no_argument },
11270         { .val = 'i',   .name = "read-mirror",  .has_arg = required_argument },
11271         { .val = 'o',   .name = "write-mirror", .has_arg = required_argument },
11272         { .name = NULL } };
11273         char cmd[PATH_MAX];
11274
11275         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
11276         progname = cmd;
11277         while ((c = getopt_long(argc, argv, "hi:o:", long_opts, NULL)) >= 0) {
11278                 char *end;
11279
11280                 switch (c) {
11281                 case 'i': {
11282                         unsigned long int id;
11283
11284                         errno = 0;
11285                         id = strtoul(optarg, &end, 0);
11286                         if (errno != 0 || *end != '\0' || id == 0 ||
11287                             id > UINT16_MAX) {
11288                                 fprintf(stderr,
11289                                         "%s: invalid read mirror ID '%s'\n",
11290                                         progname, optarg);
11291                                 return rc;
11292                         }
11293
11294                         read_mirror_id = (__u16)id;
11295                         break;
11296                 }
11297                 case 'o':
11298                         if (!strcmp(optarg, "-1")) {
11299                                 /* specify all other mirrors */
11300                                 ids[0] = (__u16)-1;
11301                                 count = 1;
11302                         } else {
11303                                 count = parse_mirror_ids((__u16 *)ids,
11304                                                          ARRAY_SIZE(ids),
11305                                                          optarg);
11306                                 if (count < 0)
11307                                         return rc;
11308                         }
11309                         break;
11310                 default:
11311                         fprintf(stderr, "%s: unrecognized option '%s'\n",
11312                                 progname, argv[optind - 1]);
11313                         /* fallthrough */
11314                 case 'h':
11315                         return CMD_HELP;
11316                 }
11317         }
11318
11319         if (argc == optind) {
11320                 fprintf(stderr, "%s %s: no mirrored file provided\n",
11321                         progname, argv[0]);
11322                 return rc;
11323         } else if (argc > optind + 1) {
11324                 fprintf(stderr, "%s %s: too many files\n", progname, argv[0]);
11325                 return rc;
11326         }
11327
11328         if (read_mirror_id == 0) {
11329                 fprintf(stderr,
11330                         "%s %s: no valid read mirror ID %d is provided\n",
11331                         progname, argv[0], read_mirror_id);
11332                 return rc;
11333         }
11334
11335         if (count == 0) {
11336                 fprintf(stderr,
11337                         "%s %s: no write mirror ID is provided\n",
11338                         progname, argv[0]);
11339                 return rc;
11340         }
11341
11342         for (i = 0; i < count; i++) {
11343                 if (read_mirror_id == ids[i]) {
11344                         fprintf(stderr,
11345                         "%s %s: read and write mirror ID cannot be the same\n",
11346                                 progname, argv[0]);
11347                         return rc;
11348                 }
11349         }
11350
11351         /* open mirror file */
11352         fname = argv[optind];
11353
11354         fd = open(fname, O_DIRECT | O_RDWR);
11355         if (fd < 0) {
11356                 fprintf(stderr, "%s %s: cannot open '%s': %s\n",
11357                         progname, argv[0], fname, strerror(errno));
11358                 return rc;
11359         }
11360
11361         /* write to all other mirrors */
11362         if (ids[0] == (__u16)-1) {
11363                 count = get_other_mirror_ids(fd, ids, read_mirror_id);
11364                 if (count <= 0) {
11365                         rc = count;
11366                         fprintf(stderr,
11367                         "%s %s: failed to get other mirror ids in '%s': %d\n",
11368                                 progname, argv[0], fname, rc);
11369                         goto close_fd;
11370                 }
11371         }
11372
11373         /* verify mirror id */
11374         rc = verify_mirror_id_by_fd(fd, read_mirror_id);
11375         if (rc) {
11376                 fprintf(stderr,
11377                         "%s %s: cannot find mirror with ID %u in '%s'\n",
11378                         progname, argv[0], read_mirror_id, fname);
11379                 goto close_fd;
11380         }
11381
11382         for (i = 0; i < count; i++) {
11383                 rc = verify_mirror_id_by_fd(fd, ids[i]);
11384                 if (rc) {
11385                         fprintf(stderr,
11386                         "%s %s: cannot find mirror with ID %u in '%s'\n",
11387                                 progname, argv[0], ids[i], fname);
11388                         goto close_fd;
11389                 }
11390         }
11391
11392         ioc = calloc(sizeof(*ioc) + sizeof(__u32) * 4096, 1);
11393         if (!ioc) {
11394                 fprintf(stderr,
11395                         "%s %s: cannot alloc comp id array for ioc: %s\n",
11396                         progname, argv[0], strerror(errno));
11397                 rc = -errno;
11398                 goto close_fd;
11399         }
11400
11401         /* get stale component info */
11402         layout = llapi_layout_get_by_fd(fd, 0);
11403         if (!layout) {
11404                 fprintf(stderr, "%s %s: failed to get layout of '%s': %s\n",
11405                         progname, argv[0], fname, strerror(errno));
11406                 rc = -errno;
11407                 goto free_ioc;
11408         }
11409         comp_size = llapi_mirror_find_stale(layout, comp_array,
11410                                             ARRAY_SIZE(comp_array),
11411                                             ids, count);
11412         llapi_layout_free(layout);
11413         if (comp_size < 0) {
11414                 rc = comp_size;
11415                 goto free_ioc;
11416         }
11417
11418         /* prepare target mirror components instantiation */
11419         resync_ioc = (struct ll_ioc_lease_id *)ioc;
11420         resync_ioc->lil_mode = LL_LEASE_WRLCK;
11421         resync_ioc->lil_flags = LL_LEASE_RESYNC;
11422         if (count == 1)
11423                 resync_ioc->lil_mirror_id = ids[0];
11424         else
11425                 resync_ioc->lil_mirror_id = read_mirror_id | MIRROR_ID_NEG;
11426         rc = llapi_lease_set(fd, ioc);
11427         if (rc < 0) {
11428                 fprintf(stderr,
11429                         "%s %s: '%s' llapi_lease_get_ext failed: %s\n",
11430                         progname, argv[0], fname, strerror(errno));
11431                 goto free_ioc;
11432         }
11433
11434         copied = llapi_mirror_copy_many(fd, read_mirror_id, ids, count);
11435         if (copied < 0) {
11436                 rc = copied;
11437                 fprintf(stderr, "%s %s: copy error: %d\n",
11438                         progname, argv[0], rc);
11439                 goto free_ioc;
11440         }
11441
11442         fprintf(stdout, "mirror copied successfully: ");
11443         for (i = 0; i < copied; i++)
11444                 fprintf(stdout, "%d ", ids[i]);
11445         fprintf(stdout, "\n");
11446
11447         ioc->lil_mode = LL_LEASE_UNLCK;
11448         ioc->lil_flags = LL_LEASE_RESYNC_DONE;
11449         ioc->lil_count = 0;
11450         for (i = 0; i < comp_size; i++) {
11451                 int j;
11452
11453                 for (j = 0; j < copied; j++) {
11454                         if (comp_array[i].lrc_mirror_id != ids[j])
11455                                 continue;
11456
11457                         ioc->lil_ids[ioc->lil_count] = comp_array[i].lrc_id;
11458                         ioc->lil_count++;
11459                 }
11460         }
11461         rc = llapi_lease_set(fd, ioc);
11462         if (rc <= 0) {
11463                 if (rc == 0)
11464                         rc = -EBUSY;
11465                 fprintf(stderr,
11466                         "%s %s: release lease lock of '%s' failed: %s\n",
11467                         progname, argv[0], fname, strerror(errno));
11468                 goto free_ioc;
11469         }
11470
11471         rc = 0;
11472
11473 free_ioc:
11474         free(ioc);
11475 close_fd:
11476         close(fd);
11477
11478         return rc;
11479 }
11480
11481 /**
11482  * struct verify_chunk - Mirror chunk to be verified.
11483  * @chunk:        [start, end) of the chunk.
11484  * @mirror_count: Number of mirror ids in @mirror_id array.
11485  * @mirror_id:    Array of valid mirror ids that cover the chunk.
11486  */
11487 struct verify_chunk {
11488         struct lu_extent chunk;
11489         unsigned int mirror_count;
11490         __u16 mirror_id[LUSTRE_MIRROR_COUNT_MAX];
11491 };
11492
11493 /**
11494  * print_chunks() - Print chunk information.
11495  * @fname:       Mirrored file name.
11496  * @chunks:      Array of chunks.
11497  * @chunk_count: Number of chunks in @chunks array.
11498  *
11499  * This function prints [start, end) of each chunk in @chunks
11500  * for mirrored file @fname, and also prints the valid mirror ids
11501  * that cover the chunk.
11502  *
11503  * Return: void.
11504  */
11505 static inline
11506 void print_chunks(const char *fname, struct verify_chunk *chunks,
11507                   int chunk_count)
11508 {
11509         int i;
11510         int j;
11511
11512         fprintf(stdout, "Chunks to be verified in %s:\n", fname);
11513         for (i = 0; i < chunk_count; i++) {
11514                 fprintf(stdout, DEXT, PEXT(&chunks[i].chunk));
11515
11516                 if (chunks[i].mirror_count == 0)
11517                         fprintf(stdout, "\t[");
11518                 else {
11519                         fprintf(stdout, "\t[%u", chunks[i].mirror_id[0]);
11520                         for (j = 1; j < chunks[i].mirror_count; j++)
11521                                 fprintf(stdout, ", %u", chunks[i].mirror_id[j]);
11522                 }
11523                 fprintf(stdout, "]\t%u\n", chunks[i].mirror_count);
11524         }
11525         fprintf(stdout, "\n");
11526 }
11527
11528 /**
11529  * print_checksums() - Print CRC-32 checksum values.
11530  * @chunk: A chunk and its corresponding valid mirror ids.
11531  * @crc:   CRC-32 checksum values on the chunk for each valid mirror.
11532  *
11533  * This function prints CRC-32 checksum values on @chunk for
11534  * each valid mirror that covers it.
11535  *
11536  * Return: void.
11537  */
11538 static inline
11539 void print_checksums(struct verify_chunk *chunk, unsigned long *crc)
11540 {
11541         int i;
11542
11543         fprintf(stdout,
11544                 "CRC-32 checksum value for chunk "DEXT":\n",
11545                 PEXT(&chunk->chunk));
11546         for (i = 0; i < chunk->mirror_count; i++)
11547                 fprintf(stdout, "Mirror %u:\t%#lx\n",
11548                         chunk->mirror_id[i], crc[i]);
11549         fprintf(stdout, "\n");
11550 }
11551
11552 /**
11553  * filter_mirror_id() - Filter specified mirror ids.
11554  * @chunks:      Array of chunks.
11555  * @chunk_count: Number of chunks in @chunks array.
11556  * @mirror_ids:  Specified mirror ids to be verified.
11557  * @ids_nr:      Number of specified mirror ids.
11558  *
11559  * This function scans valid mirror ids that cover each chunk in @chunks
11560  * and filters specified mirror ids.
11561  *
11562  * Return: void.
11563  */
11564 static inline
11565 void filter_mirror_id(struct verify_chunk *chunks, int chunk_count,
11566                       __u16 *mirror_ids, int ids_nr)
11567 {
11568         int i;
11569         int j;
11570         int k;
11571         __u16 valid_id[LUSTRE_MIRROR_COUNT_MAX] = { 0 };
11572         unsigned int valid_count = 0;
11573
11574         for (i = 0; i < chunk_count; i++) {
11575                 if (chunks[i].mirror_count == 0)
11576                         continue;
11577
11578                 valid_count = 0;
11579                 for (j = 0; j < ids_nr; j++) {
11580                         for (k = 0; k < chunks[i].mirror_count; k++) {
11581                                 if (chunks[i].mirror_id[k] == mirror_ids[j]) {
11582                                         valid_id[valid_count] = mirror_ids[j];
11583                                         valid_count++;
11584                                         break;
11585                                 }
11586                         }
11587                 }
11588
11589                 memcpy(chunks[i].mirror_id, valid_id,
11590                        sizeof(__u16) * valid_count);
11591                 chunks[i].mirror_count = valid_count;
11592         }
11593 }
11594
11595 /**
11596  * lfs_mirror_prepare_chunk() - Find mirror chunks to be verified.
11597  * @layout:      Mirror component list.
11598  * @chunks:      Array of chunks.
11599  * @chunks_size: Array size of @chunks.
11600  *
11601  * This function scans the components in @layout from offset 0 to LUSTRE_EOF
11602  * to find out chunk segments and store them in @chunks array.
11603  *
11604  * The @mirror_id array in each element of @chunks will store the valid
11605  * mirror ids that cover the chunk. If a mirror component covering the
11606  * chunk has LCME_FL_STALE or LCME_FL_OFFLINE flag, then the mirror id
11607  * will not be stored into the @mirror_id array, and the chunk for that
11608  * mirror will not be verified.
11609  *
11610  * The @mirror_count in each element of @chunks will store the number of
11611  * mirror ids in @mirror_id array. If @mirror_count is 0, it indicates the
11612  * chunk is invalid in all of the mirrors. And if @mirror_count is 1, it
11613  * indicates the chunk is valid in only one mirror. In both cases, the
11614  * chunk will not be verified.
11615  *
11616  * Here is an example:
11617  *
11618  *  0      1M     2M     3M     4M           EOF
11619  *  +------+-------------+--------------------+
11620  *  |      |             |      S             |       mirror1
11621  *  +------+------+------+------+-------------+
11622  *  |             |   S  |   S  |             |       mirror2
11623  *  +-------------+------+------+-------------+
11624  *
11625  * prepared @chunks array will contain 5 elements:
11626  * (([0, 1M), [1, 2], 2),
11627  *  ([1M, 2M), [1, 2], 2),
11628  *  ([2M, 3M), [1], 1),
11629  *  ([3M, 4M], [], 0),
11630  *  ([4M, EOF), [2], 1))
11631  *
11632  * Return: the actual array size of @chunks on success
11633  *         or a negative error code on failure.
11634  */
11635 static inline
11636 int lfs_mirror_prepare_chunk(struct llapi_layout *layout,
11637                              struct verify_chunk *chunks,
11638                              size_t chunks_size)
11639 {
11640         uint64_t start;
11641         uint64_t end;
11642         uint32_t mirror_id;
11643         uint32_t flags;
11644         int idx = 0;
11645         int i = 0;
11646         int rc = 0;
11647
11648         memset(chunks, 0, sizeof(*chunks) * chunks_size);
11649
11650         while (1) {
11651                 rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_FIRST);
11652                 if (rc < 0) {
11653                         fprintf(stderr,
11654                                 "%s: move to the first layout component: %s.\n",
11655                                 progname, strerror(errno));
11656                         goto error;
11657                 }
11658
11659                 i = 0;
11660                 rc = 0;
11661                 chunks[idx].chunk.e_end = LUSTRE_EOF;
11662                 while (rc == 0) {
11663                         rc = llapi_layout_comp_extent_get(layout, &start, &end);
11664                         if (rc < 0) {
11665                                 fprintf(stderr,
11666                                         "%s: llapi_layout_comp_extent_get failed: %s.\n",
11667                                         progname, strerror(errno));
11668                                 goto error;
11669                         }
11670
11671                         if (start > chunks[idx].chunk.e_start ||
11672                             end <= chunks[idx].chunk.e_start)
11673                                 goto next;
11674
11675                         if (end < chunks[idx].chunk.e_end)
11676                                 chunks[idx].chunk.e_end = end;
11677
11678                         rc = llapi_layout_comp_flags_get(layout, &flags);
11679                         if (rc < 0) {
11680                                 fprintf(stderr,
11681                                         "%s: llapi_layout_comp_flags_get failed: %s.\n",
11682                                         progname, strerror(errno));
11683                                 goto error;
11684                         }
11685
11686                         if (flags & LCME_FL_STALE || flags & LCME_FL_OFFLINE)
11687                                 goto next;
11688
11689                         rc = llapi_layout_mirror_id_get(layout, &mirror_id);
11690                         if (rc < 0) {
11691                                 fprintf(stderr,
11692                                         "%s: llapi_layout_mirror_id_get failed: %s.\n",
11693                                         progname, strerror(errno));
11694                                 goto error;
11695                         }
11696
11697                         chunks[idx].mirror_id[i] = mirror_id;
11698                         i++;
11699                         if (i >= ARRAY_SIZE(chunks[idx].mirror_id)) {
11700                                 fprintf(stderr,
11701                                         "%s: mirror_id array is too small.\n",
11702                                         progname);
11703                                 rc = -EINVAL;
11704                                 goto error;
11705                         }
11706
11707 next:
11708                         rc = llapi_layout_comp_use(layout,
11709                                                    LLAPI_LAYOUT_COMP_USE_NEXT);
11710                         if (rc < 0) {
11711                                 fprintf(stderr,
11712                                         "%s: move to the next layout component: %s.\n",
11713                                         progname, strerror(errno));
11714                                 goto error;
11715                         }
11716                 } /* loop through all components */
11717
11718                 chunks[idx].mirror_count = i;
11719
11720                 if (chunks[idx].chunk.e_end == LUSTRE_EOF)
11721                         break;
11722
11723                 idx++;
11724                 if (idx >= chunks_size) {
11725                         fprintf(stderr, "%s: chunks array is too small.\n",
11726                                 progname);
11727                         rc = -EINVAL;
11728                         goto error;
11729                 }
11730
11731                 chunks[idx].chunk.e_start = chunks[idx - 1].chunk.e_end;
11732         }
11733
11734 error:
11735         return rc < 0 ? rc : idx + 1;
11736 }
11737
11738 /**
11739  * lfs_mirror_verify_chunk() - Verify a chunk.
11740  * @fd:        File descriptor of the mirrored file.
11741  * @file_size: Size of the mirrored file.
11742  * @chunk:     A chunk and its corresponding valid mirror ids.
11743  * @verbose:   Verbose mode.
11744  *
11745  * This function verifies a @chunk contains exactly the same data
11746  * ammong the mirrors that cover it.
11747  *
11748  * If @verbose is specified, then the function will print where the
11749  * differences are if the data do not match. Otherwise, it will
11750  * just return an error in that case.
11751  *
11752  * Return: 0 on success or a negative error code on failure.
11753  */
11754 static inline
11755 int lfs_mirror_verify_chunk(int fd, size_t file_size,
11756                             struct verify_chunk *chunk, int verbose)
11757 {
11758         const size_t buflen = 4 * 1024 * 1024; /* 4M */
11759         void *buf;
11760         size_t page_size = sysconf(_SC_PAGESIZE);
11761         ssize_t bytes_read;
11762         ssize_t bytes_done;
11763         size_t count;
11764         off_t pos;
11765         unsigned long crc;
11766         unsigned long crc_array[LUSTRE_MIRROR_COUNT_MAX] = { 0 };
11767         int i;
11768         int rc = 0;
11769
11770         if (file_size == 0)
11771                 return 0;
11772
11773         rc = posix_memalign(&buf, page_size, buflen);
11774         if (rc) /* error code is returned directly */
11775                 return -rc;
11776
11777         if (verbose > 1) {
11778                 fprintf(stdout, "Verifying chunk "DEXT" on mirror:",
11779                         PEXT(&chunk->chunk));
11780                 for (i = 0; i < chunk->mirror_count; i++)
11781                         fprintf(stdout, " %u", chunk->mirror_id[i]);
11782                 fprintf(stdout, "\n");
11783         }
11784
11785         bytes_done = 0;
11786         count = MIN(chunk->chunk.e_end, file_size) - chunk->chunk.e_start;
11787         pos = chunk->chunk.e_start;
11788         while (bytes_done < count) {
11789                 /* compute initial CRC-32 checksum */
11790                 crc = crc32(0L, Z_NULL, 0);
11791                 memset(crc_array, 0, sizeof(crc_array));
11792
11793                 bytes_read = 0;
11794                 for (i = 0; i < chunk->mirror_count; i++) {
11795                         bytes_read = llapi_mirror_read(fd, chunk->mirror_id[i],
11796                                                        buf, buflen, pos);
11797                         if (bytes_read < 0) {
11798                                 rc = bytes_read;
11799                                 fprintf(stderr,
11800                                         "%s: failed to read data from mirror %u: %s.\n",
11801                                         progname, chunk->mirror_id[i],
11802                                         strerror(-rc));
11803                                 goto error;
11804                         }
11805
11806                         /* compute new CRC-32 checksum */
11807                         crc_array[i] = crc32(crc, buf, bytes_read);
11808                 }
11809
11810                 if (verbose)
11811                         print_checksums(chunk, crc_array);
11812
11813                 /* compare CRC-32 checksum values */
11814                 for (i = 1; i < chunk->mirror_count; i++) {
11815                         if (crc_array[i] != crc_array[0]) {
11816                                 rc = -EINVAL;
11817
11818                                 fprintf(stderr,
11819                                         "%s: chunk "DEXT" has different checksum value on mirror %u and mirror %u.\n",
11820                                         progname, PEXT(&chunk->chunk),
11821                                         chunk->mirror_id[0],
11822                                         chunk->mirror_id[i]);
11823                         }
11824                 }
11825
11826                 pos += bytes_read;
11827                 bytes_done += bytes_read;
11828         }
11829
11830         if (verbose > 1 && rc == 0) {
11831                 fprintf(stdout, "Verifying chunk "DEXT" on mirror:",
11832                         PEXT(&chunk->chunk));
11833                 for (i = 0; i < chunk->mirror_count; i++)
11834                         fprintf(stdout, " %u", chunk->mirror_id[i]);
11835                 fprintf(stdout, " PASS\n\n");
11836         }
11837
11838 error:
11839         free(buf);
11840         return rc;
11841 }
11842
11843 /**
11844  * lfs_mirror_verify_file() - Verify a mirrored file.
11845  * @fname:      Mirrored file name.
11846  * @mirror_ids: Specified mirror ids to be verified.
11847  * @ids_nr:     Number of specified mirror ids.
11848  * @verbose:    Verbose mode.
11849  *
11850  * This function verifies that each SYNC mirror of a mirrored file
11851  * specified by @fname contains exactly the same data.
11852  *
11853  * If @mirror_ids is specified, then the function will verify the
11854  * mirrors specified by @mirror_ids contain exactly the same data.
11855  *
11856  * If @verbose is specified, then the function will print where the
11857  * differences are if the data do not match. Otherwise, it will
11858  * just return an error in that case.
11859  *
11860  * Return: 0 on success or a negative error code on failure.
11861  */
11862 static inline
11863 int lfs_mirror_verify_file(const char *fname, __u16 *mirror_ids, int ids_nr,
11864                            int verbose)
11865 {
11866         struct verify_chunk chunks_array[1024] = { };
11867         struct llapi_layout *layout = NULL;
11868         struct stat stbuf;
11869         uint32_t flr_state;
11870         int fd;
11871         int chunk_count = 0;
11872         int idx = 0;
11873         int rc = 0;
11874         int rc1 = 0;
11875         int rc2 = 0;
11876
11877         if (stat(fname, &stbuf) < 0) {
11878                 fprintf(stderr, "%s: cannot stat file '%s': %s.\n",
11879                         progname, fname, strerror(errno));
11880                 rc = -errno;
11881                 goto error;
11882         }
11883
11884         if (!S_ISREG(stbuf.st_mode)) {
11885                 fprintf(stderr, "%s: '%s' is not a regular file.\n",
11886                         progname, fname);
11887                 rc = -EINVAL;
11888                 goto error;
11889         }
11890
11891         if (stbuf.st_size == 0) {
11892                 if (verbose)
11893                         fprintf(stdout, "%s: '%s' file size is 0.\n",
11894                                 progname, fname);
11895                 rc = 0;
11896                 goto error;
11897         }
11898
11899         /* Allow mirror verify even without the key on encrypted files */
11900         fd = open(fname, O_DIRECT | O_RDONLY | O_FILE_ENC);
11901         if (fd < 0) {
11902                 fprintf(stderr, "%s: cannot open '%s': %s.\n",
11903                         progname, fname, strerror(errno));
11904                 rc = -errno;
11905                 goto error;
11906         }
11907
11908         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
11909         if (rc < 0) {
11910                 fprintf(stderr, "%s: '%s' llapi_lease_acquire failed: %s.\n",
11911                         progname, fname, strerror(errno));
11912                 goto close_fd;
11913         }
11914
11915         layout = llapi_layout_get_by_fd(fd, 0);
11916         if (!layout) {
11917                 fprintf(stderr, "%s: '%s' llapi_layout_get_by_fd failed: %s.\n",
11918                         progname, fname, strerror(errno));
11919                 rc = -errno;
11920                 llapi_lease_release(fd);
11921                 goto close_fd;
11922         }
11923
11924         rc = llapi_layout_flags_get(layout, &flr_state);
11925         if (rc < 0) {
11926                 fprintf(stderr, "%s: '%s' llapi_layout_flags_get failed: %s.\n",
11927                         progname, fname, strerror(errno));
11928                 rc = -errno;
11929                 goto free_layout;
11930         }
11931
11932         flr_state &= LCM_FL_FLR_MASK;
11933         switch (flr_state) {
11934         case LCM_FL_NONE:
11935                 rc = -EINVAL;
11936                 fprintf(stderr, "%s: '%s' file state error: %s.\n",
11937                         progname, fname, llapi_layout_flags_string(flr_state));
11938                 goto free_layout;
11939         default:
11940                 break;
11941         }
11942
11943         /* find out mirror chunks to be verified */
11944         chunk_count = lfs_mirror_prepare_chunk(layout, chunks_array,
11945                                                ARRAY_SIZE(chunks_array));
11946         if (chunk_count < 0) {
11947                 rc = chunk_count;
11948                 goto free_layout;
11949         }
11950
11951         if (ids_nr > 0)
11952                 /* filter specified mirror ids */
11953                 filter_mirror_id(chunks_array, chunk_count, mirror_ids, ids_nr);
11954
11955         if (verbose > 2)
11956                 print_chunks(fname, chunks_array, chunk_count);
11957
11958         for (idx = 0; idx < chunk_count; idx++) {
11959                 if (chunks_array[idx].chunk.e_start >= stbuf.st_size) {
11960                         if (verbose)
11961                                 fprintf(stdout,
11962                                         "%s: '%s' chunk "DEXT" exceeds file size %#llx: skipped\n",
11963                                         progname, fname,
11964                                         PEXT(&chunks_array[idx].chunk),
11965                                         (unsigned long long)stbuf.st_size);
11966                         break;
11967                 }
11968
11969                 if (chunks_array[idx].mirror_count == 0) {
11970                         fprintf(stderr,
11971                                 "%s: '%s' chunk "DEXT" is invalid in all of the mirrors: ",
11972                                 progname, fname,
11973                                 PEXT(&chunks_array[idx].chunk));
11974                         if (verbose) {
11975                                 fprintf(stderr, "skipped\n");
11976                                 continue;
11977                         }
11978                         rc = -EINVAL;
11979                         fprintf(stderr, "failed\n");
11980                         goto free_layout;
11981                 }
11982
11983                 if (chunks_array[idx].mirror_count == 1) {
11984                         if (verbose)
11985                                 fprintf(stdout,
11986                                         "%s: '%s' chunk "DEXT" is only valid in mirror %u: skipped\n",
11987                                         progname, fname,
11988                                         PEXT(&chunks_array[idx].chunk),
11989                                         chunks_array[idx].mirror_id[0]);
11990                         continue;
11991                 }
11992
11993                 rc = llapi_lease_check(fd);
11994                 if (rc != LL_LEASE_RDLCK) {
11995                         fprintf(stderr, "%s: '%s' lost lease lock.\n",
11996                                 progname, fname);
11997                         goto free_layout;
11998                 }
11999
12000                 /* verify one chunk */
12001                 rc1 = lfs_mirror_verify_chunk(fd, stbuf.st_size,
12002                                               &chunks_array[idx], verbose);
12003                 if (rc1 < 0) {
12004                         rc2 = rc1;
12005                         if (!verbose) {
12006                                 rc = rc1;
12007                                 goto free_layout;
12008                         }
12009                 }
12010         }
12011
12012         if (rc2 < 0)
12013                 rc = rc2;
12014
12015 free_layout:
12016         llapi_layout_free(layout);
12017         llapi_lease_release(fd);
12018 close_fd:
12019         close(fd);
12020 error:
12021         return rc;
12022 }
12023
12024 /**
12025  * lfs_mirror_verify() - Parse and execute lfs mirror verify command.
12026  * @argc: The count of lfs mirror verify command line arguments.
12027  * @argv: Array of strings for lfs mirror verify command line arguments.
12028  *
12029  * This function parses lfs mirror verify command and verifies the
12030  * specified mirrored file(s).
12031  *
12032  * Return: 0 on success or a negative error code on failure.
12033  */
12034 static inline int lfs_mirror_verify(int argc, char **argv)
12035 {
12036         __u16 mirror_ids[LUSTRE_MIRROR_COUNT_MAX] = { 0 };
12037         int ids_nr = 0;
12038         int c;
12039         int verbose = 0;
12040         int rc = 0;
12041         int rc1 = 0;
12042         char cmd[PATH_MAX];
12043
12044         struct option long_opts[] = {
12045         { .val = 'h',   .name = "help",         .has_arg = no_argument },
12046         { .val = 'o',   .name = "only",         .has_arg = required_argument },
12047         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
12048         { .name = NULL } };
12049
12050         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
12051         progname = cmd;
12052         while ((c = getopt_long(argc, argv, "ho:v", long_opts, NULL)) >= 0) {
12053                 switch (c) {
12054                 case 'o':
12055                         rc = parse_mirror_ids(mirror_ids,
12056                                               ARRAY_SIZE(mirror_ids),
12057                                               optarg);
12058                         if (rc < 0) {
12059                                 fprintf(stderr,
12060                                         "%s: bad mirror ids '%s'.\n",
12061                                         progname, optarg);
12062                                 goto error;
12063                         }
12064                         ids_nr = rc;
12065                         if (ids_nr < 2) {
12066                                 fprintf(stderr,
12067                                         "%s: at least 2 mirror ids needed with '--only' option.\n",
12068                                         progname);
12069                                 rc = CMD_HELP;
12070                                 goto error;
12071                         }
12072                         break;
12073                 case 'v':
12074                         verbose++;
12075                         break;
12076                 default:
12077                         fprintf(stderr, "%s: unrecognized option '%s'\n",
12078                                 progname, argv[optind - 1]);
12079                         /* fallthrough */
12080                 case 'h':
12081                         rc = CMD_HELP;
12082                         goto error;
12083                 }
12084         }
12085
12086         if (argc == optind) {
12087                 fprintf(stderr, "%s: no file name given.\n", progname);
12088                 rc = CMD_HELP;
12089                 goto error;
12090         }
12091
12092         if (ids_nr > 0 && argc > optind + 1) {
12093                 fprintf(stderr,
12094                         "%s: '--only' cannot be used upon multiple files.\n",
12095                         progname);
12096                 rc = CMD_HELP;
12097                 goto error;
12098         }
12099
12100         if (ids_nr > 0) {
12101                 rc = verify_mirror_ids(argv[optind], mirror_ids, ids_nr);
12102                 if (rc < 0)
12103                         goto error;
12104         }
12105
12106         rc = 0;
12107         for (; optind < argc; optind++) {
12108                 rc1 = lfs_mirror_verify_file(argv[optind], mirror_ids, ids_nr,
12109                                              verbose);
12110                 if (rc1 < 0)
12111                         rc = rc1;
12112         }
12113 error:
12114         return rc;
12115 }
12116
12117 /**
12118  * lfs_mirror() - Parse and execute lfs mirror commands.
12119  * @argc: The count of lfs mirror command line arguments.
12120  * @argv: Array of strings for lfs mirror command line arguments.
12121  *
12122  * This function parses lfs mirror commands and performs the
12123  * corresponding functions specified in mirror_cmdlist[].
12124  *
12125  * Return: 0 on success or an error code on failure.
12126  */
12127 static int lfs_mirror(int argc, char **argv)
12128 {
12129         char cmd[PATH_MAX];
12130         int rc = 0;
12131
12132         setlinebuf(stdout);
12133
12134         Parser_init("lfs-mirror > ", mirror_cmdlist);
12135
12136         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
12137         progname = cmd;
12138         program_invocation_short_name = cmd;
12139         if (argc > 1)
12140                 rc = Parser_execarg(argc - 1, argv + 1, mirror_cmdlist);
12141         else
12142                 rc = Parser_commands();
12143
12144         return rc < 0 ? -rc : rc;
12145 }
12146
12147 static void lustre_som_swab(struct lustre_som_attrs *attrs)
12148 {
12149 #if __BYTE_ORDER == __BIG_ENDIAN
12150         __swab16s(&attrs->lsa_valid);
12151         __swab64s(&attrs->lsa_size);
12152         __swab64s(&attrs->lsa_blocks);
12153 #endif
12154 }
12155
12156 enum lfs_som_type {
12157         LFS_SOM_SIZE = 0x1,
12158         LFS_SOM_BLOCKS = 0x2,
12159         LFS_SOM_FLAGS = 0x4,
12160         LFS_SOM_ATTR_ALL = LFS_SOM_SIZE | LFS_SOM_BLOCKS |
12161                            LFS_SOM_FLAGS,
12162 };
12163
12164 static int lfs_getsom(int argc, char **argv)
12165 {
12166         const char *path;
12167         struct lustre_som_attrs *attrs;
12168         char buf[sizeof(*attrs) + 64];
12169         enum lfs_som_type type = LFS_SOM_ATTR_ALL;
12170         int rc = 0, c;
12171
12172         while ((c = getopt(argc, argv, "bfhs")) != -1) {
12173                 switch (c) {
12174                 case 'b':
12175                         type = LFS_SOM_BLOCKS;
12176                         break;
12177                 case 'f':
12178                         type = LFS_SOM_FLAGS;
12179                         break;
12180                 case 's':
12181                         type = LFS_SOM_SIZE;
12182                         break;
12183                 default:
12184                         fprintf(stderr, "%s: unrecognized option '%s'\n",
12185                                 progname, argv[optind - 1]);
12186                         /* fallthrough */
12187                 case 'h':
12188                         return CMD_HELP;
12189                 }
12190         }
12191
12192         argc -= optind;
12193         argv += optind;
12194
12195         if (argc != 1) {
12196                 fprintf(stderr, "%s: %s\n",
12197                         progname, argc == 0 ? "miss file target" :
12198                         "input more than 2 files");
12199                 return CMD_HELP;
12200         }
12201
12202         path = argv[0];
12203         attrs = (void *)buf;
12204         rc = lgetxattr(path, "trusted.som", attrs, sizeof(buf));
12205         if (rc < 0) {
12206                 rc = -errno;
12207                 fprintf(stderr, "%s failed to get som xattr: %s (%d)\n",
12208                         argv[0], strerror(errno), errno);
12209                 return rc;
12210         }
12211
12212         lustre_som_swab(attrs);
12213
12214         switch (type) {
12215         case LFS_SOM_ATTR_ALL:
12216                 printf("file: %s size: %llu blocks: %llu flags: %x\n",
12217                        path, (unsigned long long)attrs->lsa_size,
12218                        (unsigned long long)attrs->lsa_blocks,
12219                        attrs->lsa_valid);
12220                 break;
12221         case LFS_SOM_SIZE:
12222                 printf("%llu\n", (unsigned long long)attrs->lsa_size);
12223                 break;
12224         case LFS_SOM_BLOCKS:
12225                 printf("%llu\n", (unsigned long long)attrs->lsa_blocks);
12226                 break;
12227         case LFS_SOM_FLAGS:
12228                 printf("%x\n", attrs->lsa_valid);
12229                 break;
12230         default:
12231                 fprintf(stderr, "%s: unknown option\n", progname);
12232                 return CMD_HELP;
12233         }
12234
12235         return 0;
12236 }
12237
12238 /**
12239  * lfs_mirror_list_commands() - List lfs mirror commands.
12240  * @argc: The count of command line arguments.
12241  * @argv: Array of strings for command line arguments.
12242  *
12243  * This function lists lfs mirror commands defined in mirror_cmdlist[].
12244  *
12245  * Return: 0 on success.
12246  */
12247 static int lfs_mirror_list_commands(int argc, char **argv)
12248 {
12249         char buffer[81] = "";
12250
12251         Parser_list_commands(mirror_cmdlist, buffer, sizeof(buffer),
12252                              NULL, 0, 4);
12253
12254         return 0;
12255 }
12256
12257 static int lfs_pcc_attach(int argc, char **argv)
12258 {
12259         struct option long_opts[] = {
12260         { .val = 'h',   .name = "help", .has_arg = no_argument },
12261         { .val = 'i',   .name = "id",   .has_arg = required_argument },
12262         { .name = NULL } };
12263         int c;
12264         int rc = 0;
12265         __u32 archive_id = 0;
12266         const char *path;
12267         char *end;
12268         char fullpath[PATH_MAX];
12269         enum lu_pcc_type type = LU_PCC_READWRITE;
12270
12271         optind = 0;
12272         while ((c = getopt_long(argc, argv, "hi:",
12273                                 long_opts, NULL)) != -1) {
12274                 switch (c) {
12275                 case 'i':
12276                         errno = 0;
12277                         archive_id = strtoul(optarg, &end, 0);
12278                         if (errno != 0 || *end != '\0' ||
12279                             archive_id == 0 || archive_id > UINT32_MAX) {
12280                                 fprintf(stderr,
12281                                         "error: %s: bad archive ID '%s'\n",
12282                                         progname, optarg);
12283                                 return CMD_HELP;
12284                         }
12285                         break;
12286                 default:
12287                         fprintf(stderr, "%s: unrecognized option '%s'\n",
12288                                 progname, argv[optind - 1]);
12289                         /* fallthrough */
12290                 case 'h':
12291                         return CMD_HELP;
12292                 }
12293         }
12294
12295         if (archive_id == 0) {
12296                 fprintf(stderr, "%s: must specify attach ID\n", argv[0]);
12297                 return CMD_HELP;
12298         }
12299
12300         if (argc <= optind) {
12301                 fprintf(stderr, "%s: must specify one or more file names\n",
12302                         argv[0]);
12303                 return CMD_HELP;
12304         }
12305
12306         while (optind < argc) {
12307                 int rc2;
12308
12309                 path = argv[optind++];
12310                 if (!realpath(path, fullpath)) {
12311                         fprintf(stderr, "%s: could not find path '%s': %s\n",
12312                                 argv[0], path, strerror(errno));
12313                         if (rc == 0)
12314                                 rc = -EINVAL;
12315                         continue;
12316                 }
12317
12318                 rc2 = llapi_pcc_attach(fullpath, archive_id, type);
12319                 if (rc2 < 0) {
12320                         fprintf(stderr,
12321                                 "%s: cannot attach '%s' to PCC with archive ID '%u': %s\n",
12322                                 argv[0], path, archive_id, strerror(-rc2));
12323                         if (rc == 0)
12324                                 rc = rc2;
12325                 }
12326         }
12327         return rc;
12328 }
12329
12330 static int lfs_pcc_attach_fid(int argc, char **argv)
12331 {
12332         struct option long_opts[] = {
12333         { .val = 'h',   .name = "help", .has_arg = no_argument },
12334         { .val = 'i',   .name = "id",   .has_arg = required_argument },
12335         { .val = 'm',   .name = "mnt",  .has_arg = required_argument },
12336         { .name = NULL } };
12337         int c;
12338         int rc = 0;
12339         __u32 archive_id = 0;
12340         char *end;
12341         const char *mntpath = NULL;
12342         const char *fidstr;
12343         enum lu_pcc_type type = LU_PCC_READWRITE;
12344
12345         optind = 0;
12346         while ((c = getopt_long(argc, argv, "hi:m:",
12347                                 long_opts, NULL)) != -1) {
12348                 switch (c) {
12349                 case 'i':
12350                         errno = 0;
12351                         archive_id = strtoul(optarg, &end, 0);
12352                         if (errno != 0 || *end != '\0' ||
12353                             archive_id > UINT32_MAX) {
12354                                 fprintf(stderr,
12355                                         "error: %s: bad archive ID '%s'\n",
12356                                         argv[0], optarg);
12357                                 return CMD_HELP;
12358                         }
12359                         break;
12360                 case 'm':
12361                         mntpath = optarg;
12362                         break;
12363                 default:
12364                         fprintf(stderr, "%s: unrecognized option '%s'\n",
12365                                 progname, argv[optind - 1]);
12366                         /* fallthrough */
12367                 case 'h':
12368                         return CMD_HELP;
12369                 }
12370         }
12371
12372         if (archive_id == 0) {
12373                 fprintf(stderr, "%s: must specify an archive ID\n", argv[0]);
12374                 return CMD_HELP;
12375         }
12376
12377         if (!mntpath) {
12378                 fprintf(stderr, "%s: must specify Lustre mount point\n",
12379                         argv[0]);
12380                 return CMD_HELP;
12381         }
12382
12383         if (argc <= optind) {
12384                 fprintf(stderr, "%s: must specify one or more fids\n", argv[0]);
12385                 return CMD_HELP;
12386         }
12387
12388         while (optind < argc) {
12389                 int rc2;
12390
12391                 fidstr = argv[optind++];
12392
12393                 rc2 = llapi_pcc_attach_fid_str(mntpath, fidstr,
12394                                                archive_id, type);
12395                 if (rc2 < 0) {
12396                         fprintf(stderr,
12397                                 "%s: cannot attach '%s' on '%s' to PCC with archive ID '%u': %s\n",
12398                                 argv[0], fidstr, mntpath, archive_id,
12399                                 strerror(rc2));
12400                 }
12401                 if (rc == 0 && rc2 < 0)
12402                         rc = rc2;
12403         }
12404         return rc;
12405 }
12406
12407 static int lfs_pcc_detach(int argc, char **argv)
12408 {
12409         struct option long_opts[] = {
12410         { .val = 'h',   .name = "help", .has_arg = no_argument },
12411         { .val = 'k',   .name = "keep", .has_arg = no_argument },
12412         { .name = NULL } };
12413         int c;
12414         int rc = 0;
12415         const char *path;
12416         char fullpath[PATH_MAX];
12417         __u32 detach_opt = PCC_DETACH_OPT_UNCACHE;
12418
12419         optind = 0;
12420         while ((c = getopt_long(argc, argv, "hk",
12421                                 long_opts, NULL)) != -1) {
12422                 switch (c) {
12423                 case 'k':
12424                         detach_opt = PCC_DETACH_OPT_NONE;
12425                         break;
12426                 default:
12427                         fprintf(stderr, "%s: unrecognized option '%s'\n",
12428                                 progname, argv[optind - 1]);
12429                         /* fallthrough */
12430                 case 'h':
12431                         return CMD_HELP;
12432                 }
12433         }
12434
12435         while (optind < argc) {
12436                 int rc2;
12437
12438                 path = argv[optind++];
12439                 if (!realpath(path, fullpath)) {
12440                         fprintf(stderr, "%s: could not find path '%s': %s\n",
12441                                 argv[0], path, strerror(errno));
12442                         if (rc == 0)
12443                                 rc = -EINVAL;
12444                         continue;
12445                 }
12446
12447                 rc2 = llapi_pcc_detach_file(fullpath, detach_opt);
12448                 if (rc2 < 0) {
12449                         rc2 = -errno;
12450                         fprintf(stderr,
12451                                 "%s: cannot detach '%s' from PCC: %s\n",
12452                                 argv[0], path, strerror(errno));
12453                         if (rc == 0)
12454                                 rc = rc2;
12455                 }
12456         }
12457         return rc;
12458 }
12459
12460 static int lfs_pcc_detach_fid(int argc, char **argv)
12461 {
12462         struct option long_opts[] = {
12463         { .val = 'h',   .name = "help", .has_arg = no_argument },
12464         { .val = 'k',   .name = "keep", .has_arg = no_argument },
12465         { .name = NULL } };
12466         int c;
12467         int rc = 0;
12468         const char *fid;
12469         const char *mntpath;
12470         __u32 detach_opt = PCC_DETACH_OPT_UNCACHE;
12471
12472         optind = 0;
12473         while ((c = getopt_long(argc, argv, "hk",
12474                                 long_opts, NULL)) != -1) {
12475                 switch (c) {
12476                 case 'k':
12477                         detach_opt = PCC_DETACH_OPT_NONE;
12478                         break;
12479                 default:
12480                         fprintf(stderr, "%s: unrecognized option '%s'\n",
12481                                 progname, argv[optind - 1]);
12482                         /* fallthrough */
12483                 case 'h':
12484                         return CMD_HELP;
12485                 }
12486         }
12487
12488         mntpath = argv[optind++];
12489
12490         while (optind < argc) {
12491                 int rc2;
12492
12493                 fid = argv[optind++];
12494
12495                 rc2 = llapi_pcc_detach_fid_str(mntpath, fid, detach_opt);
12496                 if (rc2 < 0) {
12497                         fprintf(stderr,
12498                                 "%s: cannot detach '%s' on '%s' from PCC: %s\n",
12499                                 argv[0], fid, mntpath, strerror(-rc2));
12500                         if (rc == 0)
12501                                 rc = rc2;
12502                 }
12503         }
12504         return rc;
12505 }
12506
12507 static int lfs_pcc_state(int argc, char **argv)
12508 {
12509         int rc = 0;
12510         const char *path;
12511         char fullpath[PATH_MAX];
12512         struct lu_pcc_state state;
12513
12514         optind = 1;
12515
12516         if (argc <= 1) {
12517                 fprintf(stderr, "%s: must specify one or more file names\n",
12518                         progname);
12519                 return CMD_HELP;
12520         }
12521
12522         while (optind < argc) {
12523                 int rc2;
12524
12525                 path = argv[optind++];
12526                 if (!realpath(path, fullpath)) {
12527                         fprintf(stderr, "%s: could not find path '%s': %s\n",
12528                                 argv[0], path, strerror(errno));
12529                         if (rc == 0)
12530                                 rc = -EINVAL;
12531                         continue;
12532                 }
12533
12534                 rc2 = llapi_pcc_state_get(fullpath, &state);
12535                 if (rc2 < 0) {
12536                         if (rc == 0)
12537                                 rc = rc2;
12538                         fprintf(stderr,
12539                                 "%s: cannot get PCC state of '%s': %s\n",
12540                                 argv[0], path, strerror(-rc2));
12541                         continue;
12542                 }
12543
12544                 printf("file: %s", path);
12545                 printf(", type: %s", pcc_type2string(state.pccs_type));
12546                 if (state.pccs_type == LU_PCC_NONE &&
12547                     state.pccs_open_count == 0) {
12548                         printf("\n");
12549                         continue;
12550                 }
12551
12552                 printf(", PCC file: %s", state.pccs_path);
12553                 printf(", user number: %u", state.pccs_open_count);
12554                 printf(", flags: %x", state.pccs_flags);
12555                 printf("\n");
12556         }
12557         return rc;
12558 }
12559
12560 /**
12561  * lfs_pcc_list_commands() - List lfs pcc commands.
12562  * @argc: The count of command line arguments.
12563  * @argv: Array of strings for command line arguments.
12564  *
12565  * This function lists lfs pcc commands defined in pcc_cmdlist[].
12566  *
12567  * Return: 0 on success.
12568  */
12569 static int lfs_pcc_list_commands(int argc, char **argv)
12570 {
12571         char buffer[81] = "";
12572
12573         Parser_list_commands(pcc_cmdlist, buffer, sizeof(buffer),
12574                              NULL, 0, 4);
12575
12576         return 0;
12577 }
12578
12579 /**
12580  * lfs_pcc() - Parse and execute lfs pcc commands.
12581  * @argc: The count of lfs pcc command line arguments.
12582  * @argv: Array of strings for lfs pcc command line arguments.
12583  *
12584  * This function parses lfs pcc commands and performs the
12585  * corresponding functions specified in pcc_cmdlist[].
12586  *
12587  * Return: 0 on success or an error code on failure.
12588  */
12589 static int lfs_pcc(int argc, char **argv)
12590 {
12591         char cmd[PATH_MAX];
12592         int rc = 0;
12593
12594         setlinebuf(stdout);
12595
12596         Parser_init("lfs-pcc > ", pcc_cmdlist);
12597
12598         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
12599         progname = cmd;
12600         program_invocation_short_name = cmd;
12601         if (argc > 1)
12602                 rc = Parser_execarg(argc - 1, argv + 1, pcc_cmdlist);
12603         else
12604                 rc = Parser_commands();
12605
12606         return rc < 0 ? -rc : rc;
12607 }
12608
12609 static int lfs_list_commands(int argc, char **argv)
12610 {
12611         char buffer[81] = ""; /* 80 printable chars + terminating NUL */
12612
12613         Parser_list_commands(cmdlist, buffer, sizeof(buffer), NULL, 0, 4);
12614
12615         return 0;
12616 }
12617
12618 int main(int argc, char **argv)
12619 {
12620         int rc;
12621
12622         /* Ensure that liblustreapi constructor has run */
12623         if (!llapi_liblustreapi_initialized())
12624                 fprintf(stderr, "liblustreapi was not properly initialized\n");
12625
12626         setlinebuf(stdout);
12627         opterr = 0;
12628
12629         Parser_init("lfs > ", cmdlist);
12630
12631         progname = program_invocation_short_name; /* Used in error messages */
12632         if (argc > 1) {
12633                 llapi_set_command_name(argv[1]);
12634                 rc = Parser_execarg(argc - 1, argv + 1, cmdlist);
12635                 llapi_clear_command_name();
12636         } else {
12637                 rc = Parser_commands();
12638         }
12639
12640         return rc < 0 ? -rc : rc;
12641 }
12642
12643 #ifdef _LUSTRE_IDL_H_
12644 /* Everything we need here should be included by lustreapi.h. */
12645 # error "lfs should not depend on lustre_idl.h"
12646 #endif /* _LUSTRE_IDL_H_ */