Whamcloud - gitweb
LU-13482 utils: bandwidth limit for lfs migrate
[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 #ifndef NSEC_PER_SEC
82 # define NSEC_PER_SEC 1000000000UL
83 #endif
84 #define ONE_MB 0x100000
85
86 /* all functions */
87 static int lfs_find(int argc, char **argv);
88 static int lfs_getstripe(int argc, char **argv);
89 static int lfs_getdirstripe(int argc, char **argv);
90 static int lfs_setdirstripe(int argc, char **argv);
91 static int lfs_rmentry(int argc, char **argv);
92 static int lfs_unlink_foreign(int argc, char **argv);
93 static int lfs_osts(int argc, char **argv);
94 static int lfs_mdts(int argc, char **argv);
95 static int lfs_df(int argc, char **argv);
96 static int lfs_getname(int argc, char **argv);
97 static int lfs_check(int argc, char **argv);
98 #ifdef HAVE_SYS_QUOTA_H
99 static int lfs_setquota(int argc, char **argv);
100 static int lfs_quota(int argc, char **argv);
101 static int lfs_project(int argc, char **argv);
102 #endif
103 static int lfs_flushctx(int argc, char **argv);
104 static int lfs_poollist(int argc, char **argv);
105 static int lfs_changelog(int argc, char **argv);
106 static int lfs_changelog_clear(int argc, char **argv);
107 static int lfs_fid2path(int argc, char **argv);
108 static int lfs_path2fid(int argc, char **argv);
109 static int lfs_rmfid(int argc, char **argv);
110 static int lfs_data_version(int argc, char **argv);
111 static int lfs_hsm_state(int argc, char **argv);
112 static int lfs_hsm_set(int argc, char **argv);
113 static int lfs_hsm_clear(int argc, char **argv);
114 static int lfs_hsm_action(int argc, char **argv);
115 static int lfs_hsm_archive(int argc, char **argv);
116 static int lfs_hsm_restore(int argc, char **argv);
117 static int lfs_hsm_release(int argc, char **argv);
118 static int lfs_hsm_remove(int argc, char **argv);
119 static int lfs_hsm_cancel(int argc, char **argv);
120 static int lfs_swap_layouts(int argc, char **argv);
121 static int lfs_mv(int argc, char **argv);
122 static int lfs_ladvise(int argc, char **argv);
123 static int lfs_getsom(int argc, char **argv);
124 static int lfs_heat_get(int argc, char **argv);
125 static int lfs_heat_set(int argc, char **argv);
126 static int lfs_mirror(int argc, char **argv);
127 static int lfs_mirror_list_commands(int argc, char **argv);
128 static int lfs_list_commands(int argc, char **argv);
129 static inline int lfs_mirror_resync(int argc, char **argv);
130 static inline int lfs_mirror_verify(int argc, char **argv);
131 static inline int lfs_mirror_read(int argc, char **argv);
132 static inline int lfs_mirror_write(int argc, char **argv);
133 static inline int lfs_mirror_copy(int argc, char **argv);
134 static int lfs_pcc_attach(int argc, char **argv);
135 static int lfs_pcc_attach_fid(int argc, char **argv);
136 static int lfs_pcc_detach(int argc, char **argv);
137 static int lfs_pcc_detach_fid(int argc, char **argv);
138 static int lfs_pcc_state(int argc, char **argv);
139 static int lfs_pcc(int argc, char **argv);
140 static int lfs_pcc_list_commands(int argc, char **argv);
141
142 enum stats_flag {
143         STATS_ON,
144         STATS_OFF,
145 };
146
147 static int lfs_migrate_to_dom(int fd, int fdv, char *name,
148                               __u64 migration_flags,
149                               unsigned long long bandwidth_bytes_sec,
150                               enum stats_flag stats_flag,
151                               long stats_interval_sec);
152
153 struct pool_to_id_cbdata {
154         const char *pool;
155         __u32 id;
156 };
157
158 static int find_comp_id_by_pool(struct llapi_layout *layout, void *cbdata);
159 static int find_mirror_id_by_pool(struct llapi_layout *layout, void *cbdata);
160
161 enum setstripe_origin {
162         SO_SETSTRIPE,
163         SO_MIGRATE,
164         SO_MIGRATE_MDT,
165         SO_MIRROR_CREATE,
166         SO_MIRROR_EXTEND,
167         SO_MIRROR_SPLIT,
168         SO_MIRROR_DELETE,
169 };
170
171 static int lfs_setstripe_internal(int argc, char **argv,
172                                   enum setstripe_origin opc);
173
174 static inline int lfs_setstripe(int argc, char **argv)
175 {
176         return lfs_setstripe_internal(argc, argv, SO_SETSTRIPE);
177 }
178
179 static inline int lfs_setstripe_migrate(int argc, char **argv)
180 {
181         return lfs_setstripe_internal(argc, argv, SO_MIGRATE);
182 }
183
184 static inline int lfs_mirror_create(int argc, char **argv)
185 {
186         return lfs_setstripe_internal(argc, argv, SO_MIRROR_CREATE);
187 }
188
189 static inline int lfs_mirror_extend(int argc, char **argv)
190 {
191         return lfs_setstripe_internal(argc, argv, SO_MIRROR_EXTEND);
192 }
193
194 static inline int lfs_mirror_split(int argc, char **argv)
195 {
196         return lfs_setstripe_internal(argc, argv, SO_MIRROR_SPLIT);
197 }
198
199 static inline int lfs_mirror_delete(int argc, char **argv)
200 {
201         return lfs_setstripe_internal(argc, argv, SO_MIRROR_DELETE);
202 }
203
204 /* Setstripe and migrate share mostly the same parameters */
205 #define SSM_CMD_COMMON(cmd) \
206         "usage: "cmd" [--component-end|-E COMP_END]\n"                  \
207         "                 [--copy=LUSTRE_SRC]\n"                        \
208         "                 [--extension-size|--ext-size|-z SIZE]\n"      \
209         "                 [--help|-h] [--layout|-L PATTERN]\n"          \
210         "                 [--layout|-L PATTERN]\n"                      \
211         "                 [--mirror-count|-N[MIRROR_COUNT]]\n"          \
212         "                 [--ost|-o OST_INDICES]\n"                     \
213         "                 [--overstripe-count|-C STRIPE_COUNT]\n"       \
214         "                 [--pool|-p POOL_NAME]\n"                      \
215         "                 [--stripe-count|-c STRIPE_COUNT]\n"           \
216         "                 [--stripe-index|-i START_OST_IDX]\n"          \
217         "                 [--stripe-size|-S STRIPE_SIZE]\n"             \
218         "                 [--yaml|-y YAML_TEMPLATE_FILE]\n"
219
220 #define MIRROR_EXTEND_USAGE                                             \
221         "                 {--mirror-count|-N[MIRROR_COUNT]}\n"          \
222         "                 [SETSTRIPE_OPTIONS|-f|--file VICTIM_FILE]\n"  \
223         "                 [--no-verify]\n"
224
225 #define SETSTRIPE_USAGE                                                 \
226         SSM_CMD_COMMON("setstripe")                                     \
227         MIRROR_EXTEND_USAGE                                             \
228         "                 DIRECTORY|FILENAME\n"
229
230 #define MIGRATE_USAGE                                                   \
231         SSM_CMD_COMMON("migrate  ")                                     \
232         "                 [--block|-b] [--non-block|-n]\n"              \
233         "                 [--non-direct|-D] [--verbose|-v]\n"           \
234         "                 FILENAME\n"
235
236 #define SETDIRSTRIPE_USAGE                                              \
237         "               [--mdt-count|-c stripe_count>\n"                \
238         "               [--help|-h] [--mdt-hash|-H mdt_hash]\n"         \
239         "               [--mdt-index|-i mdt_index[,mdt_index,...]\n"    \
240         "               [--default|-D] [--mode|-o mode]\n"              \
241         "               [--max-inherit|-X max_inherit]\n"               \
242         "               [--max-inherit-rr max_inherit_rr] <dir>\n"      \
243         "To create dir with a foreign (free format) layout :\n"         \
244         "setdirstripe|mkdir --foreign[=FOREIGN_TYPE] -x|-xattr STRING " \
245         "               [--mode|-o MODE] [--flags HEX] DIRECTORY\n"
246
247 /**
248  * command_t mirror_cmdlist - lfs mirror commands.
249  */
250 command_t mirror_cmdlist[] = {
251         { .pc_name = "create", .pc_func = lfs_mirror_create,
252           .pc_help = "Create a mirrored file.\n"
253                 "usage: lfs mirror create --mirror-count|-N[MIRROR_COUNT]\n"
254                 "           [SETSTRIPE_OPTIONS] ... FILENAME|DIRECTORY ...\n" },
255         { .pc_name = "delete", .pc_func = lfs_mirror_delete,
256           .pc_help = "Delete a mirror from a file.\n"
257         "usage: lfs mirror delete {--mirror-id <mirror_id> |\n"
258         "\t               --component-id|--comp-id|-I COMP_ID |\n"
259         "\t               -p <pool>} MIRRORED_FILE ...\n"
260         },
261         { .pc_name = "extend", .pc_func = lfs_mirror_extend,
262           .pc_help = "Extend a mirrored file.\n"
263                 "usage: lfs mirror extend "
264                 "{--mirror-count|-N[MIRROR_COUNT]} [--no-verify] "
265                 "[SETSTRIPE_OPTIONS|-f VICTIM_FILE] ... FILENAME ...\n" },
266         { .pc_name = "split", .pc_func = lfs_mirror_split,
267           .pc_help = "Split a mirrored file.\n"
268         "usage: lfs mirror split {--mirror-id MIRROR_ID |\n"
269         "\t             --component-id|-I COMP_ID|-p POOL} [--destroy|-d]\n"
270         "\t             [-f NEW_FILE] MIRRORED_FILE ...\n" },
271         { .pc_name = "read", .pc_func = lfs_mirror_read,
272           .pc_help = "Read the content of a specified mirror of a file.\n"
273                 "usage: lfs mirror read {--mirror-id|-N MIRROR_ID}\n"
274                 "\t\t[--outfile|-o <output_file>] <mirrored_file>\n" },
275         { .pc_name = "write", .pc_func = lfs_mirror_write,
276           .pc_help = "Write to a specified mirror of a file.\n"
277                 "usage: lfs mirror write {--mirror-id|-N MIRROR_ID}\n"
278                 "\t\t[--inputfile|-i <input_file>] <mirrored_file>\n" },
279         { .pc_name = "copy", .pc_func = lfs_mirror_copy,
280           .pc_help = "Copy a specified mirror to other mirror(s) of a file.\n"
281                 "usage: lfs mirror copy {--read-mirror|-i MIRROR_ID0}\n"
282                 "\t\t{--write-mirror|-o MIRROR_ID1[,...]} <mirrored_file>\n" },
283         { .pc_name = "resync", .pc_func = lfs_mirror_resync,
284           .pc_help = "Resynchronizes out-of-sync mirrored file(s).\n"
285                 "usage: lfs mirror resync [--only MIRROR_ID[,...]>]\n"
286                 "\t\t<mirrored_file> [<mirrored_file2>...]\n" },
287         { .pc_name = "verify", .pc_func = lfs_mirror_verify,
288           .pc_help = "Verify mirrored file(s).\n"
289                 "usage: lfs mirror verify [--only MIRROR_ID[,...]]\n"
290                 "\t\t[--verbose|-v] <mirrored_file> [<mirrored_file2> ...]\n" },
291         { .pc_name = "list-commands", .pc_func = lfs_mirror_list_commands,
292           .pc_help = "list commands supported by lfs mirror"},
293         { .pc_name = "help", .pc_func = Parser_help, .pc_help = "help" },
294         { .pc_name = "exit", .pc_func = Parser_quit, .pc_help = "quit" },
295         { .pc_name = "quit", .pc_func = Parser_quit, .pc_help = "quit" },
296         { .pc_help = NULL }
297 };
298
299 /**
300  * command_t pcc_cmdlist - lfs pcc commands.
301  */
302 command_t pcc_cmdlist[] = {
303         { .pc_name = "attach", .pc_func = lfs_pcc_attach,
304           .pc_help = "Attach given files to the Persistent Client Cache.\n"
305                 "usage: lfs pcc attach <--id|-i NUM> <file> ...\n"
306                 "\t-i: archive id for RW-PCC\n" },
307         { .pc_name = "attach_fid", .pc_func = lfs_pcc_attach_fid,
308           .pc_help = "Attach given files into PCC by FID(s).\n"
309                 "usage: lfs pcc attach_id {--id|-i NUM} {--mnt|-m MOUNTPOINT} FID ...\n"
310                 "\t-i: archive id for RW-PCC\n"
311                 "\t-m: Lustre mount point\n" },
312         { .pc_name = "state", .pc_func = lfs_pcc_state,
313           .pc_help = "Display the PCC state for given files.\n"
314                 "usage: lfs pcc state <file> ...\n" },
315         { .pc_name = "detach", .pc_func = lfs_pcc_detach,
316           .pc_help = "Detach given files from the Persistent Client Cache.\n"
317                 "usage: lfs pcc detach <file> ...\n" },
318         { .pc_name = "detach_fid", .pc_func = lfs_pcc_detach_fid,
319           .pc_help = "Detach given files from PCC by FID(s).\n"
320                 "usage: lfs pcc detach_fid <mntpath> <fid>...\n" },
321         { .pc_name = "list-commands", .pc_func = lfs_pcc_list_commands,
322           .pc_help = "list commands supported by lfs pcc"},
323         { .pc_name = "help", .pc_func = Parser_help, .pc_help = "help" },
324         { .pc_name = "exit", .pc_func = Parser_quit, .pc_help = "quit" },
325         { .pc_name = "quit", .pc_func = Parser_quit, .pc_help = "quit" },
326         { .pc_help = NULL }
327 };
328
329 /* all available commands */
330 command_t cmdlist[] = {
331         {"setstripe", lfs_setstripe, 0,
332          "To create a file with specified striping/composite layout, or\n"
333          "create/replace the default layout on an existing directory:\n"
334          SSM_CMD_COMMON("setstripe")
335          "                 [--mode MODE]\n"
336          "                 <directory|filename>\n"
337          " or\n"
338          "To add component(s) to an existing composite file:\n"
339          SSM_CMD_COMMON("setstripe --component-add")
340          "To totally delete the default striping from an existing directory:\n"
341          "usage: setstripe [--delete|-d] <directory>\n"
342          " or\n"
343          "To create a mirrored file or set s default mirror layout on a directory:\n"
344          "usage: setstripe {--mirror-count|-N}[MIRROR_COUNT] [SETSTRIPE_OPTIONS] <directory|filename>\n"
345          " or\n"
346          "To delete the last component(s) from an existing composite file\n"
347          "(note that this will also delete any data in those components):\n"
348          "usage: setstripe --component-del [--component-id|-I COMP_ID]\n"
349          "                               [--component-flags|-F COMP_FLAGS]\n"
350          "                               <filename>\n"
351          "\tCOMP_ID:     Unique component ID to delete\n"
352          "\tCOMP_FLAGS:  'init' indicating all instantiated components\n"
353          "\t             '^init' indicating all uninstantiated components\n"
354          "\t-I and -F cannot be specified at the same time\n"
355          " or\n"
356          "To set or clear flags on a specific component\n"
357          "(note that this command can only be applied to mirrored files:\n"
358          "usage: setstripe --comp-set {-I COMP_ID|--comp-flags=COMP_FLAGS}\n"
359          "                            <filename>\n"
360          " or\n"
361          "To create a file with a foreign (free format) layout:\n"
362          "usage: setstripe --foreign[=FOREIGN_TYPE]\n"
363          "                 --xattr|-x LAYOUT_STRING [--flags HEX]\n"
364          "                 [--mode MODE] <filename>\n"},
365         {"getstripe", lfs_getstripe, 0,
366          "To list the layout pattern for a given file or files in a\n"
367          "directory or recursively for all files in a directory tree.\n"
368          "usage: getstripe [--ost|-O UUID] [--quiet|-q] [--verbose|-v]\n"
369          "                 [--stripe-count|-c] [--stripe-index|-i] [--fid|-F]\n"
370          "                 [--pool|-p] [--stripe-size|-S] [--directory|-d]\n"
371          "                 [--mdt-index|-m] [--recursive|-r] [--raw|-R]\n"
372          "                 [--layout|-L] [--generation|-g] [--yaml|-y]\n"
373          "                 [--help|-h] [--component-id|-I[=COMP_ID]]\n"
374          "                 [--component-flags[=COMP_FLAGS]]\n"
375          "                 [--component-count]\n"
376          "                 [--extension-size|--ext-size|-z]\n"
377          "                 [--component-start[=[+-]COMP_START]]\n"
378          "                 [--component-end[=[+-]COMP_END]|-E[[+-]comp_end]]\n"
379          "                 [[!] --mirror-index=[+-]INDEX |\n"
380          "                 [!] --mirror-id=[+-]MIRROR_ID] [--mirror-count|-N]\n"
381          "                 [--no-follow]\n"
382          "                 <directory|filename> ..."},
383         {"setdirstripe", lfs_setdirstripe, 0,
384          "Create striped directory on specified MDT, same as mkdir.\n"
385          "May be restricted to root or group users, depending on settings.\n"
386          "usage: setdirstripe [OPTION] <directory>\n"
387          SETDIRSTRIPE_USAGE},
388         {"getdirstripe", lfs_getdirstripe, 0,
389          "To list the layout pattern info for a given directory\n"
390          "or recursively for all directories in a directory tree.\n"
391          "usage: getdirstripe [--mdt-count|-c] [--mdt-index|-m|-i]\n"
392          "                    [--help|-h] [--mdt-hash|-H] [--obd|-O UUID]\n"
393          "                    [--recursive|-r] [--yaml|-y]\n"
394          "                    [--verbose|-v] [--default|-D]\n"
395          "                    [--max-inherit|-X]\n"
396          "                    [--max-inherit-rr] <dir> ..."},
397         {"mkdir", lfs_setdirstripe, 0,
398          "Create striped directory on specified MDT, same as setdirstripe.\n"
399          "usage: mkdir [OPTION] <directory>\n"
400          SETDIRSTRIPE_USAGE},
401         {"rm_entry", lfs_rmentry, 0,
402          "To remove the name entry of the remote directory. Note: This\n"
403          "command will only delete the name entry, i.e. the remote directory\n"
404          "will become inaccessable after this command. This can only be done\n"
405          "by the administrator\n"
406          "usage: rm_entry <dir>\n"},
407         {"rmentry", lfs_rmentry, 0, "remove a dir entry, same as 'rm_entry'\n"},
408         {"unlink_foreign", lfs_unlink_foreign, 0,
409          "To remove the foreign file/dir.\n"
410          "Note: This is for files/dirs prevented to be removed using\n"
411          "unlink/rmdir, but works also for regular ones\n"
412          "usage: unlink_foreign <foreign_dir/file> [<foreign_dir/file> ...]\n"},
413         {"pool_list", lfs_poollist, 0,
414          "List pools or pool OSTs\n"
415          "usage: pool_list <fsname>[.<pool>] | <pathname>\n"},
416         {"find", lfs_find, 0,
417          "find files matching given attributes recursively in directory tree.\n"
418          "usage: find <directory|filename> ...\n"
419          "     [[!] --atime|-A [+-]N[smhdwy]] [[!] --btime|-B [+-]N[smhdwy]]\n"
420          "     [[!] --ctime|-C [+-]N[smhdwy]] [[!] --mtime|-M [+-]N[smhdwy]]\n"
421          "     [[!] --blocks|-b N] [[!] --component-count [+-]<comp_cnt>]\n"
422          "     [[!] --component-start [+-]N[kMGTPE]]\n"
423          "     [[!] --component-end|-E [+-]N[kMGTPE]]\n"
424          "     [[!] --component-flags {init,stale,prefer,offline,nosync,extension}]\n"
425          "     [[!] --extension-size|--ext-size|-z [+-]N[kMGT]]\n"
426          "     [[!] --foreign[=<foreign_type>]]\n"
427          "     [[!] --gid|-g|--group|-G <gid>|<gname>] [--help|-h]\n"
428          "     [[!] --layout|-L released,raid0,mdt] [--lazy]\n"
429          "     [--maxdepth|-D N] [[!] --mdt-count|-T [+-]<stripes>]\n"
430          "     [[!] --mdt-hash|-H <[^][blm],[^]fnv_1a_64,all_char,crush,...>\n"
431          "     [[!] --mdt-index|--mdt|-m <uuid|index,...>]\n"
432          "     [[!] --mirror-count|-N [+-]<n>]\n"
433          "     [[!] --mirror-state <[^]state>]\n"
434          "     [[!] --name|-n <pattern>] [[!] --newer[XY] <reference>]\n"
435          "     [[!] --ost|-O <uuid|index,...>] [[!] --perm [/-]mode]\n"
436          "     [[!] --pool <pool>] [--print|-P] [--print0|-0] [--printf <format>]\n"
437          "     [[!] --projid <projid>] [[!] --size|-s [+-]N[bkMGTPE]]\n"
438          "     [[!] --stripe-count|-c [+-]<stripes>]\n"
439          "     [[!] --stripe-index|-i <index,...>]\n"
440          "     [[!] --stripe-size|-S [+-]N[kMGT]] [[!] --type|-t <filetype>]\n"
441          "     [[!] --uid|-u|--user|-U <uid>|<uname>]\n"
442          "\t !: used before an option indicates 'NOT' requested attribute\n"
443          "\t -: used before a value indicates less than requested value\n"
444          "\t +: used before a value indicates more than requested value\n"
445          "\t ^: used before a flag indicates to exclude it\n"},
446         {"check", lfs_check, 0,
447          "Display the status of MGTs, MDTs or OSTs (as specified in the command)\n"
448          "or all the servers (MGTs, MDTs and OSTs) [for specified path only].\n"
449          "usage: check {mgts|osts|mdts|all} [path]"},
450         {"osts", lfs_osts, 0, "list OSTs connected to client "
451          "[for specified path only]\n" "usage: osts [path]"},
452         {"mdts", lfs_mdts, 0, "list MDTs connected to client "
453          "[for specified path only]\n" "usage: mdts [path]"},
454         {"df", lfs_df, 0,
455          "report filesystem disk space usage or inodes usage "
456          "of each MDS and all OSDs or a batch belonging to a specific pool.\n"
457          "Usage: df [--inodes|-i] [--human-readable|-h] [--lazy|-l]\n"
458          "          [--pool|-p <fsname>[.<pool>]] [path]"},
459         {"getname", lfs_getname, 0,
460          "list instances and specified mount points [for specified path only]\n"
461          "Usage: getname [--help|-h] [--instance|-i] [--fsname|-n] [path ...]"},
462 #ifdef HAVE_SYS_QUOTA_H
463         {"setquota", lfs_setquota, 0, "Set filesystem quotas.\n"
464          "usage: setquota [-t][-D] {-u|-U|-g|-G|-p|-P} {-b|-B|-i|-I LIMIT} [--pool POOL] FILESYSTEM\n"
465          "       setquota {-u|-g|-p} --delete FILESYSTEM\n"},
466         {"quota", lfs_quota, 0, "Display disk usage and limits.\n"
467          "usage: quota [-q] [-v] [-h] [-o OBD_UUID|-i MDT_IDX|-I OST_IDX]\n"
468          "             [{-u|-g|-p} UNAME|UID|GNAME|GID|PROJID]\n"
469          "             [--pool <OST pool name>] <filesystem>\n"
470          "       quota -t <-u|-g|-p> [--pool <OST pool name>] <filesystem>\n"
471          "       quota [-q] [-v] [h] {-U|-G|-P} [--pool <OST pool name>] <filesystem>"},
472         {"project", lfs_project, 0,
473          "Change or list project attribute for specified file or directory.\n"
474          "usage: project [-d|-r] <file|directory...>\n"
475          "         list project ID and flags on file(s) or directories\n"
476          "       project [-p id] [-s] [-r] <file|directory...>\n"
477          "         set project ID and/or inherit flag for specified file(s) or directories\n"
478          "       project -c [-d|-r [-p id] [-0]] <file|directory...>\n"
479          "         check project ID and flags on file(s) or directories, print outliers\n"
480          "       project -C [-d|-r] [-k] <file|directory...>\n"
481          "         clear the project inherit flag and ID on the file or directory\n"
482         },
483 #endif
484         {"flushctx", lfs_flushctx, 0,
485          "Flush security context for current user.\n"
486          "usage: flushctx [-k] [-r] [mountpoint...]"},
487         {"changelog", lfs_changelog, 0,
488          "Show the metadata changes on an MDT."
489          "\nusage: changelog <mdtname> [startrec [endrec]]"},
490         {"changelog_clear", lfs_changelog_clear, 0,
491          "Indicate that old changelog records up to <endrec> are no longer of "
492          "interest to consumer <id>, allowing the system to free up space.\n"
493          "An <endrec> of 0 means all records.\n"
494          "usage: changelog_clear <mdtname> <id> <endrec>"},
495         {"fid2path", lfs_fid2path, 0,
496          "Resolve the full path(s) for given FID(s). For a specific hardlink "
497          "specify link number <linkno>.\n"
498          "usage: fid2path [--print-fid|-f] [--print-link|-c] [--link|-l <linkno>] "
499          "<fsname|root> <fid>..."},
500         {"path2fid", lfs_path2fid, 0, "Display the fid(s) for a given path(s).\n"
501          "usage: path2fid [--parents] <path> ..."},
502         {"rmfid", lfs_rmfid, 0, "Remove file(s) by FID(s)\n"
503          "usage: rmfid <fsname|rootpath> <fid> ..."},
504         {"data_version", lfs_data_version, 0, "Display file data version for "
505          "a given path.\n" "usage: data_version [-n|-r|-w] <path>"},
506         {"hsm_state", lfs_hsm_state, 0, "Display the HSM information (states, "
507          "undergoing actions) for given files.\n usage: hsm_state <file> ..."},
508         {"hsm_set", lfs_hsm_set, 0, "Set HSM user flag on specified files.\n"
509          "usage: hsm_set [--norelease] [--noarchive] [--dirty] [--exists] "
510          "[--archived] [--lost] [--archive-id NUM] <file> ..."},
511         {"hsm_clear", lfs_hsm_clear, 0, "Clear HSM user flag on specified "
512          "files.\n"
513          "usage: hsm_clear [--norelease] [--noarchive] [--dirty] [--exists] "
514          "[--archived] [--lost] <file> ..."},
515         {"hsm_action", lfs_hsm_action, 0, "Display current HSM request for "
516          "given files.\n" "usage: hsm_action <file> ..."},
517         {"hsm_archive", lfs_hsm_archive, 0,
518          "Archive file to external storage.\n"
519          "usage: hsm_archive [--filelist FILELIST] [--data DATA] [--archive NUM] "
520          "<file> ..."},
521         {"hsm_restore", lfs_hsm_restore, 0,
522          "Restore file from external storage.\n"
523          "usage: hsm_restore [--filelist FILELIST] [--data DATA] <file> ..."},
524         {"hsm_release", lfs_hsm_release, 0,
525          "Release files from Lustre.\n"
526          "usage: hsm_release [--filelist FILELIST] [--data DATA] <file> ..."},
527         {"hsm_remove", lfs_hsm_remove, 0,
528          "Remove file copy from external storage.\n"
529          "usage: hsm_remove [--filelist FILELIST] [--data DATA] "
530          "[--archive NUM]\n"
531          "                  (FILE [FILE ...] | "
532          "--mntpath MOUNTPATH FID [FID ...])\n"
533          "\n"
534          "Note: To remove an archived copy of a file already deleted from a "
535          "Lustre FS, the\n"
536          "--mntpath option and a list of FIDs must be specified"
537         },
538         {"hsm_cancel", lfs_hsm_cancel, 0,
539          "Cancel requests related to specified files.\n"
540          "usage: hsm_cancel [--filelist FILELIST] [--data DATA] <file> ..."},
541         {"swap_layouts", lfs_swap_layouts, 0, "Swap layouts between 2 files.\n"
542          "usage: swap_layouts <path1> <path2>"},
543         {"migrate", lfs_setstripe_migrate, 0,
544          "migrate directories and their inodes between MDTs.\n"
545          "usage: migrate [--mdt-count|-c STRIPE_COUNT] [--directory|-d]\n"
546          "               [--mdt-hash|-H HASH_TYPE]\n"
547          "               [--mdt-index|-m START_MDT_INDEX] [--verbose|-v]\n"
548          "               DIRECTORY\n"
549          "\n"
550          "migrate file objects from one OST layout to another\n"
551          "(may be not safe with concurent writes).\n"
552          MIGRATE_USAGE },
553         {"mv", lfs_mv, 0,
554          "To move directories between MDTs. This command is deprecated, "
555          "use \"migrate\" instead.\n"
556          "usage: mv <directory|filename> [--mdt-index|-m MDT_INDEX] "
557          "[--verbose|-v]\n"},
558         {"ladvise", lfs_ladvise, 0,
559          "Provide servers with advice about access patterns for a file.\n"
560          "usage: ladvise [--advice|-a ADVICE] [--start|-s START[kMGT]]\n"
561          "               [--background|-b] [--unset|-u]\n\n"
562          "               {--end|-e END[kMGT]|--length|-l LENGTH[kMGT]}\n"
563          "               {[--mode|-m [READ,WRITE]}\n"
564          "               <file> ...\n"},
565         {"mirror", lfs_mirror, mirror_cmdlist,
566          "lfs commands used to manage files with mirrored components:\n"
567          "lfs mirror create - create a mirrored file or directory\n"
568          "lfs mirror extend - add mirror(s) to an existing file\n"
569          "lfs mirror split  - split a mirror from an existing mirrored file\n"
570          "lfs mirror resync - resynchronize out-of-sync mirrored file(s)\n"
571          "lfs mirror read   - read a mirror content of a mirrored file\n"
572          "lfs mirror write  - write to a mirror of a mirrored file\n"
573          "lfs mirror copy   - copy a mirror to other mirror(s) of a file\n"
574          "lfs mirror verify - verify mirrored file(s)\n"},
575         {"getsom", lfs_getsom, 0, "To list the SOM info for a given file.\n"
576          "usage: getsom [-s] [-b] [-f] <path>\n"
577          "\t-s: Only show the size value of the SOM data for a given file\n"
578          "\t-b: Only show the blocks value of the SOM data for a given file\n"
579          "\t-f: Only show the flags value of the SOM data for a given file\n"},
580         {"heat_get", lfs_heat_get, 0,
581          "To get heat of files.\n"
582          "usage: heat_get <file> ...\n"},
583         {"heat_set", lfs_heat_set, 0,
584          "To set heat flags of files.\n"
585          "usage: heat_set [--clear|-c] [--off|-o] [--on|-O] <file> ...\n"
586          "\t--clear|-c: Clear file heat for given files\n"
587          "\t--off|-o:   Turn off file heat for given files\n"
588          "\t--on|-O:    Turn on file heat for given files\n"},
589         {"pcc", lfs_pcc, pcc_cmdlist,
590          "lfs commands used to interact with PCC features:\n"
591          "lfs pcc attach - attach given files to Persistent Client Cache\n"
592          "lfs pcc attach_fid - attach given files into PCC by FID(s)\n"
593          "lfs pcc state  - display the PCC state for given files\n"
594          "lfs pcc detach - detach given files from Persistent Client Cache\n"
595          "lfs pcc detach_fid - detach given files from PCC by FID(s)\n"},
596         {"help", Parser_help, 0, "help"},
597         {"exit", Parser_quit, 0, "quit"},
598         {"quit", Parser_quit, 0, "quit"},
599         {"--version", Parser_version, 0,
600          "output build version of the utility and exit"},
601         {"--list-commands", lfs_list_commands, 0,
602          "list commands supported by the utility and exit"},
603         { 0, 0, 0, NULL }
604 };
605
606 static int check_hashtype(const char *hashtype)
607 {
608         int type_num = atoi(hashtype);
609         int i;
610
611         /* numeric hash type */
612         if (hashtype && lmv_is_known_hash_type(type_num))
613                 return type_num;
614         /* string hash type */
615         for (i = LMV_HASH_TYPE_ALL_CHARS; i < ARRAY_SIZE(mdt_hash_name); i++)
616                 if (strcmp(hashtype, mdt_hash_name[i]) == 0)
617                         return i;
618
619         return 0;
620 }
621
622 static uint32_t check_foreign_type_name(const char *foreign_type_name)
623 {
624         uint32_t i;
625
626         for (i = 0; i < LU_FOREIGN_TYPE_UNKNOWN; i++) {
627                 if (!lu_foreign_types[i].lft_name)
628                         break;
629                 if (strcmp(foreign_type_name,
630                            lu_foreign_types[i].lft_name) == 0)
631                         return lu_foreign_types[i].lft_type;
632         }
633
634         return LU_FOREIGN_TYPE_UNKNOWN;
635 }
636
637 static const char *error_loc = "syserror";
638
639 static int
640 migrate_open_files(const char *name, __u64 migration_flags,
641                    const struct llapi_stripe_param *param,
642                    struct llapi_layout *layout, int *fd_src, int *fd_tgt)
643 {
644         int                      fd = -1;
645         int                      fdv = -1;
646         int                      rflags;
647         int                      mdt_index;
648         int                      random_value;
649         char                     parent[PATH_MAX];
650         char                     volatile_file[PATH_MAX];
651         char                    *ptr;
652         int                      rc;
653         struct stat              st;
654         struct stat              stv;
655
656         if (!param && !layout) {
657                 error_loc = "layout information";
658                 return -EINVAL;
659         }
660
661         /* search for file directory pathname */
662         if (strlen(name) > sizeof(parent) - 1) {
663                 error_loc = "source file name";
664                 return -ERANGE;
665         }
666
667         strncpy(parent, name, sizeof(parent));
668         ptr = strrchr(parent, '/');
669         if (!ptr) {
670                 if (!getcwd(parent, sizeof(parent))) {
671                         error_loc = "getcwd";
672                         return -errno;
673                 }
674         } else {
675                 if (ptr == parent) /* leading '/' */
676                         ptr = parent + 1;
677                 *ptr = '\0';
678         }
679
680         /* even if the file is only read, WR mode is nedeed to allow
681          * layout swap on fd
682          */
683         /* Allow migrating even without the key on encrypted files */
684         rflags = O_RDWR | O_NOATIME | O_FILE_ENC;
685         if (!(migration_flags & LLAPI_MIGRATION_NONDIRECT))
686                 rflags |= O_DIRECT;
687 source_open:
688         fd = open(name, rflags);
689         if (fd < 0) {
690                 /* If encrypted file without the key,
691                  * retry mirror extend in O_DIRECT.
692                  */
693                 if (errno == ENOKEY && !(rflags & O_DIRECT) &&
694                     migration_flags & LLAPI_MIGRATION_MIRROR) {
695                         rflags |= O_DIRECT;
696                         goto source_open;
697                 }
698                 rc = -errno;
699                 error_loc = "cannot open source file";
700                 return rc;
701         }
702
703         rc = llapi_file_fget_mdtidx(fd, &mdt_index);
704         if (rc < 0) {
705                 error_loc = "cannot get MDT index";
706                 goto out;
707         }
708
709         do {
710                 int open_flags = O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW |
711                         /* Allow migrating without the key on encrypted files */
712                         O_FILE_ENC;
713                 mode_t open_mode = S_IRUSR | S_IWUSR;
714
715                 if (rflags & O_DIRECT)
716                         open_flags |= O_DIRECT;
717                 random_value = random();
718                 rc = snprintf(volatile_file, sizeof(volatile_file),
719                               "%s/%s:%.4X:%.4X:fd=%.2d", parent,
720                               LUSTRE_VOLATILE_HDR, mdt_index,
721                               random_value, fd);
722                 if (rc >= sizeof(volatile_file)) {
723                         rc = -ENAMETOOLONG;
724                         break;
725                 }
726
727                 /* create, open a volatile file, use caching (ie no directio) */
728                 if (layout) {
729                         /* Returns -1 and sets errno on error: */
730                         fdv = llapi_layout_file_open(volatile_file, open_flags,
731                                                      open_mode, layout);
732                         if (fdv < 0)
733                                 fdv = -errno;
734                 } else {
735                         /* Does the right thing on error: */
736                         fdv = llapi_file_open_param(volatile_file, open_flags,
737                                                     open_mode, param);
738                 }
739         } while (fdv < 0 && (rc = fdv) == -EEXIST);
740
741         if (rc < 0) {
742                 error_loc = "cannot create volatile file";
743                 goto out;
744         }
745
746         /*
747          * In case the MDT does not support creation of volatile files
748          * we should try to unlink it.
749          */
750         (void)unlink(volatile_file);
751
752         /*
753          * Not-owner (root?) special case.
754          * Need to set owner/group of volatile file like original.
755          * This will allow to pass related check during layout_swap.
756          */
757         rc = fstat(fd, &st);
758         if (rc != 0) {
759                 rc = -errno;
760                 error_loc = "cannot stat source file";
761                 goto out;
762         }
763
764         rc = fstat(fdv, &stv);
765         if (rc != 0) {
766                 rc = -errno;
767                 error_loc = "cannot stat volatile";
768                 goto out;
769         }
770
771         if (st.st_uid != stv.st_uid || st.st_gid != stv.st_gid) {
772                 rc = fchown(fdv, st.st_uid, st.st_gid);
773                 if (rc != 0) {
774                         rc = -errno;
775                         error_loc = "cannot change ownwership of volatile";
776                         goto out;
777                 }
778         }
779
780 out:
781         if (rc < 0) {
782                 if (fd > 0)
783                         close(fd);
784                 if (fdv > 0)
785                         close(fdv);
786         } else {
787                 *fd_src = fd;
788                 *fd_tgt = fdv;
789                 error_loc = NULL;
790         }
791         return rc;
792 }
793
794 struct timespec timespec_sub(struct timespec *before, struct timespec *after)
795 {
796         struct timespec ret;
797
798         ret.tv_sec = after->tv_sec - before->tv_sec;
799         if (after->tv_nsec < before->tv_nsec) {
800                 ret.tv_sec--;
801                 ret.tv_nsec = NSEC_PER_SEC + after->tv_nsec - before->tv_nsec;
802         } else {
803                 ret.tv_nsec = after->tv_nsec - before->tv_nsec;
804         }
805
806         return ret;
807 }
808
809 static void stats_log(struct timespec *now, struct timespec *start_time,
810                       enum stats_flag stats_flag,
811                       ssize_t read_bytes, size_t write_bytes,
812                       off_t file_size_bytes)
813 {
814         struct timespec diff = timespec_sub(start_time, now);
815
816         if (stats_flag == STATS_ON && ((diff.tv_sec != 0) ||
817                 (diff.tv_nsec != 0)) && file_size_bytes != 0)
818                 printf("- { seconds: %li, rmbps: %5.2g, wmbps: %5.2g, copied: %lu, size: %lu, pct: %lu%% }\n",
819                         diff.tv_sec,
820                         (double) read_bytes/((ONE_MB * diff.tv_sec) +
821                                 ((ONE_MB * diff.tv_nsec)/NSEC_PER_SEC)),
822                         (double) write_bytes/((ONE_MB * diff.tv_sec) +
823                                 ((ONE_MB * diff.tv_nsec)/NSEC_PER_SEC)),
824                         write_bytes/ONE_MB,
825                         file_size_bytes/ONE_MB,
826                         ((write_bytes*100)/file_size_bytes));
827 }
828
829 static int migrate_copy_data(int fd_src, int fd_dst, int (*check_file)(int),
830                              unsigned long long bandwidth_bytes_sec,
831                              enum stats_flag stats_flag,
832                              long stats_interval_sec, off_t file_size_bytes)
833 {
834         struct llapi_layout *layout;
835         size_t buf_size = 4 * 1024 * 1024;
836         void *buf = NULL;
837         off_t pos = 0;
838         off_t data_end = 0;
839         size_t page_size = sysconf(_SC_PAGESIZE);
840         bool sparse;
841         int rc;
842         size_t write_bytes = 0;
843         ssize_t read_bytes = 0;
844         struct timespec start_time;
845         struct timespec now;
846         struct timespec last_bw_print;
847
848         layout = llapi_layout_get_by_fd(fd_src, 0);
849         if (layout) {
850                 uint64_t stripe_size;
851
852                 rc = llapi_layout_stripe_size_get(layout, &stripe_size);
853                 if (rc == 0)
854                         buf_size = stripe_size;
855
856                 llapi_layout_free(layout);
857         }
858
859         /* Use a page-aligned buffer for direct I/O */
860         rc = posix_memalign(&buf, page_size, buf_size);
861         if (rc != 0)
862                 return -rc;
863
864         sparse = llapi_file_is_sparse(fd_src);
865         if (sparse) {
866                 rc = ftruncate(fd_dst, pos);
867                 if (rc < 0) {
868                         rc = -errno;
869                         return rc;
870                 }
871         }
872
873         clock_gettime(CLOCK_REALTIME, &start_time);
874         now = last_bw_print = start_time;
875
876         while (1) {
877                 off_t data_off;
878                 size_t to_read, to_write;
879                 ssize_t rsize;
880
881                 if (sparse && pos >= data_end) {
882                         size_t data_size;
883
884                         data_off = llapi_data_seek(fd_src, pos, &data_size);
885                         if (data_off < 0) {
886                                 /* Non-fatal, switch to full copy */
887                                 sparse = false;
888                                 continue;
889                         }
890                         /* hole at the end of file, truncate up to it */
891                         if (!data_size) {
892                                 rc = ftruncate(fd_dst, data_off);
893                                 if (rc < 0)
894                                         goto out;
895                         }
896                         pos = data_off & ~(page_size - 1);
897                         data_end = data_off + data_size;
898                         to_read = ((data_end - pos - 1) | (page_size - 1)) + 1;
899                         to_read = MIN(to_read, buf_size);
900                 } else {
901                         to_read = buf_size;
902                 }
903
904                 if (check_file) {
905                         rc = check_file(fd_src);
906                         if (rc < 0)
907                                 goto out;
908                 }
909
910                 rsize = pread(fd_src, buf, to_read, pos);
911                 read_bytes += rsize;
912                 if (rsize < 0) {
913                         rc = -errno;
914                         goto out;
915                 }
916                 /* EOF */
917                 if (rsize == 0)
918                         break;
919
920                 to_write = rsize;
921                 while (to_write > 0) {
922                         unsigned long long write_target;
923                         ssize_t written;
924                         struct timespec diff;
925
926                         written = pwrite(fd_dst, buf, to_write, pos);
927                         if (written < 0) {
928                                 rc = -errno;
929                                 goto out;
930                         }
931                         pos += written;
932                         to_write -= written;
933                         write_bytes += written;
934
935                         if (bandwidth_bytes_sec == 0)
936                                 continue;
937
938                         clock_gettime(CLOCK_REALTIME, &now);
939                         diff = timespec_sub(&start_time, &now);
940                         write_target = ((bandwidth_bytes_sec * diff.tv_sec) +
941                                 ((bandwidth_bytes_sec *
942                                 diff.tv_nsec)/NSEC_PER_SEC));
943
944                         if (write_target < write_bytes) {
945                                 unsigned long long excess;
946                                 struct timespec delay = { 0, 0 };
947
948                                 excess = write_bytes - write_target;
949
950                                 if (excess == 0)
951                                         continue;
952
953                                 delay.tv_sec = excess / bandwidth_bytes_sec;
954                                 delay.tv_nsec = (excess % bandwidth_bytes_sec) *
955                                         NSEC_PER_SEC / bandwidth_bytes_sec;
956
957                                 do {
958                                         rc = clock_nanosleep(CLOCK_REALTIME, 0,
959                                                              &delay, &delay);
960                                 } while (rc < 0 && errno == EINTR);
961
962                                 if (rc < 0) {
963                                         if (stats_flag == STATS_OFF)
964                                                 fprintf(stderr,
965                                                         "error %s: delay for bandwidth control failed: %s\n",
966                                                         progname,
967                                                         strerror(-rc));
968                                         rc = 0;
969                                 }
970                         }
971                 }
972
973                 clock_gettime(CLOCK_REALTIME, &now);
974                 if ((write_bytes != file_size_bytes) &&
975                         (now.tv_sec >= last_bw_print.tv_sec +
976                         stats_interval_sec)) {
977                         stats_log(&now, &start_time, stats_flag,
978                                   read_bytes, write_bytes,
979                                   file_size_bytes);
980                         last_bw_print = now;
981                 }
982
983                 if (rc || rsize < to_read)
984                         break;
985         }
986
987         /* Output at least one log, regardless of stats_interval */
988         clock_gettime(CLOCK_REALTIME, &now);
989         stats_log(&now, &start_time, stats_flag,
990                   read_bytes, write_bytes,
991                   file_size_bytes);
992
993         rc = fsync(fd_dst);
994         if (rc < 0)
995                 rc = -errno;
996 out:
997         /* Try to avoid page cache pollution after migration. */
998         (void)posix_fadvise(fd_src, 0, 0, POSIX_FADV_DONTNEED);
999         (void)posix_fadvise(fd_dst, 0, 0, POSIX_FADV_DONTNEED);
1000
1001         free(buf);
1002         return rc;
1003 }
1004
1005 static int migrate_set_timestamps(int fd, const struct stat *st)
1006 {
1007         struct timeval tv[2] = {
1008                 {.tv_sec = st->st_atime},
1009                 {.tv_sec = st->st_mtime}
1010         };
1011
1012         return futimes(fd, tv);
1013 }
1014
1015 static int migrate_block(int fd, int fdv,
1016                          unsigned long long bandwidth_bytes_sec,
1017                          enum stats_flag stats_flag,
1018                          long stats_interval_sec)
1019 {
1020         struct stat st;
1021         __u64   dv1;
1022         int     gid;
1023         int     rc;
1024         int     rc2;
1025
1026         rc = fstat(fd, &st);
1027         if (rc < 0) {
1028                 error_loc = "cannot stat source file";
1029                 return -errno;
1030         }
1031
1032         rc = llapi_get_data_version(fd, &dv1, LL_DV_RD_FLUSH);
1033         if (rc < 0) {
1034                 error_loc = "cannot get dataversion";
1035                 return rc;
1036         }
1037
1038         do
1039                 gid = random();
1040         while (gid == 0);
1041
1042         /*
1043          * The grouplock blocks all concurrent accesses to the file.
1044          * It has to be taken after llapi_get_data_version as it would
1045          * block it too.
1046          */
1047         rc = llapi_group_lock(fd, gid);
1048         if (rc < 0) {
1049                 error_loc = "cannot get group lock";
1050                 return rc;
1051         }
1052
1053         rc = migrate_copy_data(fd, fdv, NULL, bandwidth_bytes_sec,
1054                                stats_flag, stats_interval_sec,
1055                                st.st_size);
1056         if (rc < 0) {
1057                 error_loc = "data copy failed";
1058                 goto out_unlock;
1059         }
1060
1061         /* Make sure we keep original atime/mtime values */
1062         rc = migrate_set_timestamps(fdv, &st);
1063         if (rc < 0) {
1064                 error_loc = "set target file timestamp failed";
1065                 goto out_unlock;
1066         }
1067
1068         /*
1069          * swap layouts
1070          * for a migration we need to check data version on file did
1071          * not change.
1072          *
1073          * Pass in gid=0 since we already own grouplock.
1074          */
1075         rc = llapi_fswap_layouts_grouplock(fd, fdv, dv1, 0, 0,
1076                                            SWAP_LAYOUTS_CHECK_DV1);
1077         if (rc == -EAGAIN) {
1078                 error_loc = "file changed";
1079                 goto out_unlock;
1080         } else if (rc < 0) {
1081                 error_loc = "cannot swap layout";
1082                 goto out_unlock;
1083         }
1084
1085 out_unlock:
1086         rc2 = llapi_group_unlock(fd, gid);
1087         if (rc2 < 0 && rc == 0) {
1088                 error_loc = "unlock group lock";
1089                 rc = rc2;
1090         }
1091
1092         return rc;
1093 }
1094
1095 /**
1096  * Internal helper for migrate_copy_data(). Check lease and report error if
1097  * need be.
1098  *
1099  * \param[in]  fd           File descriptor on which to check the lease.
1100  *
1101  * \retval 0       Migration can keep on going.
1102  * \retval -errno  Error occurred, abort migration.
1103  */
1104 static int check_lease(int fd)
1105 {
1106         int rc;
1107
1108         rc = llapi_lease_check(fd);
1109         if (rc > 0)
1110                 return 0; /* llapi_check_lease returns > 0 on success. */
1111
1112         return -EBUSY;
1113 }
1114
1115 static int migrate_nonblock(int fd, int fdv,
1116                             unsigned long long bandwidth_bytes_sec,
1117                             enum stats_flag stats_flag,
1118                             long stats_interval_sec)
1119 {
1120         struct stat st;
1121         __u64   dv1;
1122         __u64   dv2;
1123         int     rc;
1124
1125         rc = fstat(fd, &st);
1126         if (rc < 0) {
1127                 error_loc = "cannot stat source file";
1128                 return -errno;
1129         }
1130
1131         rc = llapi_get_data_version(fd, &dv1, LL_DV_RD_FLUSH);
1132         if (rc < 0) {
1133                 error_loc = "cannot get data version";
1134                 return rc;
1135         }
1136
1137         rc = migrate_copy_data(fd, fdv, check_lease, bandwidth_bytes_sec,
1138                                stats_flag, stats_interval_sec,
1139                                st.st_size);
1140         if (rc < 0) {
1141                 error_loc = "data copy failed";
1142                 return rc;
1143         }
1144
1145         rc = llapi_get_data_version(fd, &dv2, LL_DV_RD_FLUSH);
1146         if (rc != 0) {
1147                 error_loc = "cannot get data version";
1148                 return rc;
1149         }
1150
1151         if (dv1 != dv2) {
1152                 rc = -EAGAIN;
1153                 error_loc = "source file changed";
1154                 return rc;
1155         }
1156
1157         /* Make sure we keep original atime/mtime values */
1158         rc = migrate_set_timestamps(fdv, &st);
1159         if (rc < 0) {
1160                 error_loc = "set target file timestamp failed";
1161                 return -errno;
1162         }
1163         return 0;
1164 }
1165
1166 static
1167 int lfs_layout_compid_by_pool(char *fname, const char *pool, int *comp_id)
1168 {
1169         struct pool_to_id_cbdata data = { .pool = pool };
1170         struct llapi_layout *layout = NULL;
1171         int rc;
1172
1173         layout = llapi_layout_get_by_path(fname, 0);
1174         if (!layout) {
1175                 fprintf(stderr,
1176                         "error %s: file '%s' couldn't get layout: rc=%d\n",
1177                         progname, fname, errno);
1178                 rc = -errno;
1179                 goto free_layout;
1180         }
1181         rc = llapi_layout_sanity(layout, false, true);
1182         if (rc < 0) {
1183                 llapi_layout_sanity_perror(errno);
1184                 goto free_layout;
1185         }
1186         rc = llapi_layout_comp_iterate(layout, find_comp_id_by_pool, &data);
1187         if (rc < 0)
1188                 goto free_layout;
1189
1190         *comp_id = data.id;
1191         rc = 0;
1192
1193 free_layout:
1194         if (layout)
1195                 llapi_layout_free(layout);
1196         return rc;
1197 }
1198
1199 static int lfs_component_set(char *fname, int comp_id, const char *pool,
1200                              __u32 flags, __u32 neg_flags)
1201 {
1202         __u32 ids[2];
1203         __u32 flags_array[2];
1204         size_t count = 0;
1205         int rc;
1206
1207         if (!comp_id) {
1208                 if (pool == NULL) {
1209                         fprintf(stderr,
1210                                 "error %s: neither component id nor pool is specified\n",
1211                                 progname);
1212                         return -EINVAL;
1213                 }
1214                 rc = lfs_layout_compid_by_pool(fname, pool, &comp_id);
1215                 if (rc)
1216                         return rc;
1217         }
1218
1219         if (flags) {
1220                 ids[count] = comp_id;
1221                 flags_array[count] = flags;
1222                 ++count;
1223         }
1224
1225         if (neg_flags) {
1226                 if (neg_flags & LCME_FL_STALE) {
1227                         fprintf(stderr,
1228                                 "%s: cannot clear 'stale' flags from component. Please use lfs-mirror-resync(1) instead\n",
1229                                 progname);
1230                         return -EINVAL;
1231                 }
1232
1233                 ids[count] = comp_id;
1234                 flags_array[count] = neg_flags | LCME_FL_NEG;
1235                 ++count;
1236         }
1237
1238         rc = llapi_layout_file_comp_set(fname, ids, flags_array, count);
1239         if (rc) {
1240                 if (errno == EUCLEAN) {
1241                         rc = -errno;
1242                         fprintf(stderr,
1243                                 "%s: cannot set 'stale' flag on component '%#x' of the last non-stale mirror of '%s'\n",
1244                                 progname, comp_id, fname);
1245                 } else {
1246                         fprintf(stderr,
1247                                 "%s: cannot change the flags of component '%#x' of file '%s': %x / ^(%x)\n",
1248                                 progname, comp_id, fname, flags, neg_flags);
1249                 }
1250         }
1251
1252         return rc;
1253 }
1254
1255 static int lfs_component_del(char *fname, __u32 comp_id,
1256                              __u32 flags, __u32 neg_flags)
1257 {
1258         int     rc = 0;
1259
1260         if (flags && neg_flags) {
1261                 fprintf(stderr,
1262                         "%s: cannot specify both positive and negative flags\n",
1263                         progname);
1264                 return -EINVAL;
1265         }
1266
1267         if (!flags && neg_flags)
1268                 flags = neg_flags | LCME_FL_NEG;
1269
1270         if (flags && comp_id) {
1271                 fprintf(stderr,
1272                         "%s: cannot specify component ID and flags at the same time\n",
1273                         progname);
1274                 return -EINVAL;
1275         }
1276
1277         if (!flags && !comp_id) {
1278                 fprintf(stderr,
1279                         "%s: neither flags nor component ID is specified\n",
1280                         progname);
1281                 return -EINVAL;
1282         }
1283
1284         if (flags) {
1285                 if (flags & ~LCME_KNOWN_FLAGS) {
1286                         fprintf(stderr,
1287                                 "%s setstripe: unknown flags %#x\n",
1288                                 progname, flags);
1289                         return -EINVAL;
1290                 }
1291         } else if (comp_id > LCME_ID_MAX) {
1292                 fprintf(stderr, "%s setstripe: invalid component id %u\n",
1293                         progname, comp_id);
1294                 return -EINVAL;
1295         }
1296
1297         rc = llapi_layout_file_comp_del(fname, comp_id, flags);
1298         if (rc)
1299                 fprintf(stderr,
1300                         "%s setstripe: cannot delete component %#x from '%s': %s\n",
1301                         progname, comp_id, fname, strerror(errno));
1302         return rc;
1303 }
1304
1305 static int lfs_component_add(char *fname, struct llapi_layout *layout)
1306 {
1307         int     rc;
1308
1309         if (!layout)
1310                 return -EINVAL;
1311
1312         rc = llapi_layout_file_comp_add(fname, layout);
1313         if (rc)
1314                 fprintf(stderr, "Add layout component(s) to %s failed. %s\n",
1315                         fname, strerror(errno));
1316         return rc;
1317 }
1318
1319 static int lfs_component_create(char *fname, int open_flags, mode_t open_mode,
1320                                 struct llapi_layout *layout)
1321 {
1322         struct stat     st;
1323         int     fd;
1324
1325         if (!layout)
1326                 return -EINVAL;
1327
1328         fd = lstat(fname, &st);
1329         if (fd == 0 && S_ISDIR(st.st_mode))
1330                 open_flags = O_DIRECTORY | O_RDONLY;
1331
1332         fd = llapi_layout_file_open(fname, open_flags, open_mode, layout);
1333         if (fd < 0)
1334                 fprintf(stderr, "%s: cannot %s '%s': %s\n", progname,
1335                         S_ISDIR(st.st_mode) ?
1336                                 "set default composite layout for" :
1337                                 "create composite file",
1338                         fname, strerror(errno));
1339         return fd;
1340 }
1341
1342 static int lfs_migrate(char *name, __u64 migration_flags,
1343                         struct llapi_stripe_param *param,
1344                         struct llapi_layout *layout,
1345                         unsigned long long bandwidth_bytes_sec,
1346                         enum stats_flag stats_flag, long stats_interval_sec)
1347 {
1348         struct llapi_layout *existing;
1349         uint64_t dom_new, dom_cur;
1350         int fd = -1;
1351         int fdv = -1;
1352         int rc;
1353
1354         rc = migrate_open_files(name, migration_flags, param, layout,
1355                                 &fd, &fdv);
1356         if (rc < 0)
1357                 goto out;
1358
1359         rc = llapi_layout_dom_size(layout, &dom_new);
1360         if (rc) {
1361                 error_loc = "cannot get new layout DoM size";
1362                 goto out;
1363         }
1364         /* special case for migration to DOM layout*/
1365         existing = llapi_layout_get_by_fd(fd, 0);
1366         if (!existing) {
1367                 error_loc = "cannot get existing layout";
1368                 goto out;
1369         }
1370
1371         rc = llapi_layout_dom_size(existing, &dom_cur);
1372         if (rc) {
1373                 error_loc = "cannot get current layout DoM size";
1374                 goto out;
1375         }
1376
1377         /*
1378          * if file has DoM layout already then migration is possible to
1379          * the new layout with the same DoM component via swap layout,
1380          * if new layout used bigger DOM size, then mirroring is used
1381          */
1382         if (dom_new > dom_cur) {
1383                 rc = lfs_migrate_to_dom(fd, fdv, name, migration_flags,
1384                                         bandwidth_bytes_sec, stats_flag,
1385                                         stats_interval_sec);
1386                 if (rc)
1387                         error_loc = "cannot migrate to DOM layout";
1388                 goto out_closed;
1389         }
1390
1391         if (stats_flag == STATS_ON)
1392                 printf("%s:\n", name);
1393
1394         if (!(migration_flags & LLAPI_MIGRATION_NONBLOCK)) {
1395                 /*
1396                  * Blocking mode (forced if servers do not support file lease).
1397                  * It is also the default mode, since we cannot distinguish
1398                  * between a broken lease and a server that does not support
1399                  * atomic swap/close (LU-6785)
1400                  */
1401                 rc = migrate_block(fd, fdv, bandwidth_bytes_sec, stats_flag,
1402                                    stats_interval_sec);
1403                 goto out;
1404         }
1405
1406         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
1407         if (rc < 0) {
1408                 error_loc = "cannot get lease";
1409                 goto out;
1410         }
1411
1412         rc = migrate_nonblock(fd, fdv, bandwidth_bytes_sec, stats_flag,
1413                               stats_interval_sec);
1414         if (rc < 0) {
1415                 llapi_lease_release(fd);
1416                 goto out;
1417         }
1418
1419         /*
1420          * Atomically put lease, swap layouts and close.
1421          * for a migration we need to check data version on file did
1422          * not change.
1423          */
1424         rc = llapi_fswap_layouts(fd, fdv, 0, 0, SWAP_LAYOUTS_CLOSE);
1425         if (rc < 0) {
1426                 error_loc = "cannot swap layout";
1427                 goto out;
1428         }
1429
1430 out:
1431         if (fd >= 0)
1432                 close(fd);
1433
1434         if (fdv >= 0)
1435                 close(fdv);
1436 out_closed:
1437         if (rc < 0)
1438                 fprintf(stderr, "error: %s: %s: %s: %s\n",
1439                         progname, name, error_loc, strerror(-rc));
1440         else if (migration_flags & LLAPI_MIGRATION_VERBOSE)
1441                 printf("%s\n", name);
1442
1443         return rc;
1444 }
1445
1446 static int comp_str2flags(char *string, __u32 *flags, __u32 *neg_flags)
1447 {
1448         char *name;
1449         char *dup_string = NULL;
1450         int rc = 0;
1451
1452         *flags = 0;
1453         *neg_flags = 0;
1454
1455         if (!string || !string[0])
1456                 return -EINVAL;
1457
1458         dup_string = strdup(string);
1459         if (!dup_string) {
1460                 llapi_printf(LLAPI_MSG_ERROR,
1461                              "%s: insufficient memory\n",
1462                              progname);
1463                 return -ENOMEM;
1464         }
1465
1466         for (name = strtok(dup_string, ","); name; name = strtok(NULL, ",")) {
1467                 bool found = false;
1468                 int i;
1469
1470                 for (i = 0; i < ARRAY_SIZE(comp_flags_table); i++) {
1471                         __u32 comp_flag = comp_flags_table[i].cfn_flag;
1472                         const char *comp_name = comp_flags_table[i].cfn_name;
1473
1474                         if (strcmp(name, comp_name) == 0) {
1475                                 *flags |= comp_flag;
1476                                 found = true;
1477                         } else if (strncmp(name, "^", 1) == 0 &&
1478                                    strcmp(name + 1, comp_name) == 0) {
1479                                 *neg_flags |= comp_flag;
1480                                 found = true;
1481                         }
1482                 }
1483                 if (!found) {
1484                         llapi_printf(LLAPI_MSG_ERROR,
1485                                      "%s: component flag '%s' not supported\n",
1486                                      progname, name);
1487                         rc = -EINVAL;
1488                         goto out_free;
1489                 }
1490         }
1491
1492         if (!*flags && !*neg_flags)
1493                 rc = -EINVAL;
1494
1495         /* don't allow to set and exclude the same flag */
1496         if (*flags & *neg_flags)
1497                 rc = -EINVAL;
1498
1499 out_free:
1500         free(dup_string);
1501         return rc;
1502 }
1503
1504 static int mdthash_input(char *string, __u32 *inflags,
1505                          __u32 *exflags, __u32 *type)
1506 {
1507         char *name;
1508         struct mhf_list {
1509                 char *name;
1510                 __u32 flag;
1511         } mhflist[] = {
1512                 {"migrating", LMV_HASH_FLAG_MIGRATION},
1513                 {"bad_type", LMV_HASH_FLAG_BAD_TYPE},
1514                 {"badtype", LMV_HASH_FLAG_BAD_TYPE},
1515                 {"lost_lmv", LMV_HASH_FLAG_LOST_LMV},
1516                 {"lostlmv", LMV_HASH_FLAG_LOST_LMV},
1517         };
1518
1519         if (string == NULL)
1520                 return -EINVAL;
1521
1522         *inflags = 0;
1523         *exflags = 0;
1524         *type = 0;
1525         for (name = strtok(string, ","); name; name = strtok(NULL, ",")) {
1526                 bool found = false;
1527                 int i;
1528
1529                 for (i = 0; i < ARRAY_SIZE(mhflist); i++) {
1530                         if (strcmp(name, mhflist[i].name) == 0 ||
1531                             name[0] == mhflist[i].name[0]) {
1532                                 *inflags |= mhflist[i].flag;
1533                                 found = true;
1534                         } else if (name[0] == '^' &&
1535                                    (strcmp(name + 1, mhflist[i].name) == 0 ||
1536                                     name[1] == mhflist[i].name[0])) {
1537                                 *exflags |= mhflist[i].flag;
1538                                 found = true;
1539                         }
1540                 }
1541                 if (!found) {
1542                         i = check_hashtype(name);
1543                         if (i > 0) {
1544                                 *type |= 1 << i;
1545                                 continue;
1546                         }
1547                         llapi_printf(LLAPI_MSG_ERROR,
1548                                      "%s: invalid mdt_hash value '%s'\n",
1549                                      progname, name);
1550                         return -EINVAL;
1551                 }
1552         }
1553
1554         /* don't allow to include and exclude the same flag */
1555         if (*inflags & *exflags) {
1556                 llapi_printf(LLAPI_MSG_ERROR,
1557                              "%s: include and exclude same flag '%s'\n",
1558                              progname, string);
1559                 return -EINVAL;
1560         }
1561
1562         return 0;
1563 }
1564
1565 static int mirror_str2state(char *string, __u16 *state, __u16 *neg_state)
1566 {
1567         if (!string)
1568                 return -EINVAL;
1569
1570         *state = 0;
1571         *neg_state = 0;
1572
1573         if (strncmp(string, "^", 1) == 0) {
1574                 *neg_state = llapi_layout_string_flags(string + 1);
1575                 if (*neg_state != 0)
1576                         return 0;
1577         } else {
1578                 *state = llapi_layout_string_flags(string);
1579                 if (*state != 0)
1580                         return 0;
1581         }
1582
1583         llapi_printf(LLAPI_MSG_ERROR,
1584                      "%s: mirrored file state '%s' not supported\n",
1585                      progname, string);
1586         return -EINVAL;
1587 }
1588
1589 /**
1590  * struct mirror_args - Command-line arguments for mirror(s).
1591  * @m_count:  Number of mirrors to be created with this layout.
1592  * @m_flags:  Mirror level flags, only 'prefer' is supported.
1593  * @m_layout: Mirror layout.
1594  * @m_file:   A victim file. Its layout will be split and used as a mirror.
1595  * @m_next:   Point to the next node of the list.
1596  *
1597  * Command-line arguments for mirror(s) will be parsed and stored in
1598  * a linked list that consists of this structure.
1599  */
1600 struct mirror_args {
1601         __u32                   m_count;
1602         __u32                   m_flags;
1603         struct llapi_layout     *m_layout;
1604         const char              *m_file;
1605         struct mirror_args      *m_next;
1606         bool                    m_inherit;
1607 };
1608
1609 /**
1610  * enum mirror_flags - Flags for extending a mirrored file.
1611  * @MF_NO_VERIFY: Indicates not to verify the mirror(s) from victim file(s)
1612  *             in case the victim file(s) contains the same data as the
1613  *             original mirrored file.
1614  * @MF_DESTROY: Indicates to delete the mirror from the mirrored file.
1615  * @MF_COMP_ID: specified component id instead of mirror id
1616  *
1617  * Flags for extending a mirrored file.
1618  */
1619 enum mirror_flags {
1620         MF_NO_VERIFY    = 0x1,
1621         MF_DESTROY      = 0x2,
1622         MF_COMP_ID      = 0x4,
1623         MF_COMP_POOL    = 0x8,
1624 };
1625
1626 /**
1627  * mirror_create_sanity_check() - Check mirror list.
1628  * @list:  A linked list that stores the mirror arguments.
1629  *
1630  * This function does a sanity check on @list for creating
1631  * a mirrored file.
1632  *
1633  * Return: 0 on success or a negative error code on failure.
1634  */
1635 static int mirror_create_sanity_check(const char *fname,
1636                                       struct mirror_args *list,
1637                                       bool check_fname)
1638 {
1639         int rc = 0;
1640         bool has_m_file = false;
1641         bool has_m_layout = false;
1642
1643         if (!list)
1644                 return -EINVAL;
1645
1646         if (fname && check_fname) {
1647                 struct llapi_layout *layout;
1648
1649                 layout = llapi_layout_get_by_path(fname, 0);
1650                 if (!layout) {
1651                         fprintf(stderr,
1652                                 "error: %s: file '%s' couldn't get layout\n",
1653                                 progname, fname);
1654                         return -ENODATA;
1655                 }
1656
1657                 rc = llapi_layout_sanity(layout, false, true);
1658
1659                 llapi_layout_free(layout);
1660
1661                 if (rc) {
1662                         llapi_layout_sanity_perror(rc);
1663                         return rc;
1664                 }
1665         }
1666
1667         while (list) {
1668                 if (list->m_file) {
1669                         has_m_file = true;
1670                         llapi_layout_free(list->m_layout);
1671
1672                         list->m_layout =
1673                                 llapi_layout_get_by_path(list->m_file, 0);
1674                         if (!list->m_layout) {
1675                                 fprintf(stderr,
1676                                         "error: %s: file '%s' has no layout\n",
1677                                         progname, list->m_file);
1678                                 return -ENODATA;
1679                         }
1680                 } else {
1681                         has_m_layout = true;
1682                         if (!list->m_layout) {
1683                                 fprintf(stderr, "error: %s: no mirror layout\n",
1684                                         progname);
1685                                 return -EINVAL;
1686                         }
1687                 }
1688
1689                 rc = llapi_layout_sanity(list->m_layout, false, true);
1690                 if (rc) {
1691                         llapi_layout_sanity_perror(rc);
1692                         return rc;
1693                 }
1694
1695                 list = list->m_next;
1696         }
1697
1698         if (has_m_file && has_m_layout) {
1699                 fprintf(stderr,
1700                         "error: %s: -f <victim_file> option should not be specified with setstripe options\n",
1701                         progname);
1702                 return -EINVAL;
1703         }
1704
1705         return 0;
1706 }
1707
1708 static int mirror_set_flags(struct llapi_layout *layout, void *cbdata)
1709 {
1710         __u32 mirror_flags = *(__u32 *)cbdata;
1711         uint32_t flags;
1712         int rc;
1713
1714         rc = llapi_layout_comp_flags_get(layout, &flags);
1715         if (rc < 0)
1716                 return rc;
1717
1718         if (!flags) {
1719                 rc = llapi_layout_comp_flags_set(layout, mirror_flags);
1720                 if (rc)
1721                         return rc;
1722         }
1723
1724         return LLAPI_LAYOUT_ITER_CONT;
1725 }
1726
1727 /**
1728  * mirror_create() - Create a mirrored file.
1729  * @fname:        The file to be created.
1730  * @mirror_list:  A linked list that stores the mirror arguments.
1731  *
1732  * This function creates a mirrored file @fname with the mirror(s)
1733  * from @mirror_list.
1734  *
1735  * Return: 0 on success or a negative error code on failure.
1736  */
1737 static int mirror_create(char *fname, struct mirror_args *mirror_list)
1738 {
1739         struct llapi_layout *layout = NULL;
1740         struct mirror_args *cur_mirror = NULL;
1741         uint16_t mirror_count = 0;
1742         int i = 0;
1743         int rc = 0;
1744
1745         rc = mirror_create_sanity_check(fname, mirror_list, false);
1746         if (rc)
1747                 return rc;
1748
1749         cur_mirror = mirror_list;
1750         while (cur_mirror) {
1751                 rc = llapi_layout_comp_iterate(cur_mirror->m_layout,
1752                                                mirror_set_flags,
1753                                                &cur_mirror->m_flags);
1754                 if (rc) {
1755                         rc = -errno;
1756                         fprintf(stderr, "%s: failed to set mirror flags\n",
1757                                 progname);
1758                         goto error;
1759                 }
1760
1761                 for (i = 0; i < cur_mirror->m_count; i++) {
1762                         rc = llapi_layout_merge(&layout, cur_mirror->m_layout);
1763                         if (rc) {
1764                                 rc = -errno;
1765                                 fprintf(stderr,
1766                                         "error: %s: merge layout failed: %s\n",
1767                                         progname, strerror(errno));
1768                                 goto error;
1769                         }
1770                 }
1771                 mirror_count += cur_mirror->m_count;
1772                 cur_mirror = cur_mirror->m_next;
1773         }
1774
1775         if (!layout) {
1776                 fprintf(stderr, "error: %s: layout is NULL\n", progname);
1777                 return -EINVAL;
1778         }
1779
1780         rc = llapi_layout_mirror_count_set(layout, mirror_count);
1781         if (rc) {
1782                 rc = -errno;
1783                 fprintf(stderr, "error: %s: set mirror count failed: %s\n",
1784                         progname, strerror(errno));
1785                 goto error;
1786         }
1787
1788         rc = lfs_component_create(fname, O_CREAT | O_WRONLY, 0666,
1789                                   layout);
1790         if (rc >= 0) {
1791                 close(rc);
1792                 rc = 0;
1793         }
1794
1795 error:
1796         llapi_layout_free(layout);
1797         return rc;
1798 }
1799
1800 /**
1801  * Compare files and check lease on @fd.
1802  *
1803  * \retval bytes number of bytes are the same
1804  */
1805 static ssize_t mirror_file_compare(int fd, int fdv)
1806 {
1807         const size_t buflen = 4 * 1024 * 1024; /* 4M */
1808         void *buf;
1809         ssize_t bytes_done = 0;
1810         ssize_t bytes_read = 0;
1811
1812         buf = malloc(buflen * 2);
1813         if (!buf)
1814                 return -ENOMEM;
1815
1816         while (1) {
1817                 if (!llapi_lease_check(fd)) {
1818                         bytes_done = -EBUSY;
1819                         break;
1820                 }
1821
1822                 bytes_read = read(fd, buf, buflen);
1823                 if (bytes_read <= 0)
1824                         break;
1825
1826                 if (bytes_read != read(fdv, buf + buflen, buflen))
1827                         break;
1828
1829                 /*
1830                  * XXX: should compute the checksum on each buffer and then
1831                  * compare checksum to avoid cache collision
1832                  */
1833                 if (memcmp(buf, buf + buflen, bytes_read))
1834                         break;
1835
1836                 bytes_done += bytes_read;
1837         }
1838
1839         free(buf);
1840
1841         return bytes_done;
1842 }
1843
1844 static int mirror_extend_file(const char *fname, const char *victim_file,
1845                               enum mirror_flags mirror_flags)
1846 {
1847         int fd = -1;
1848         int fdv = -1;
1849         struct stat stbuf;
1850         struct stat stbuf_v;
1851         struct ll_ioc_lease *data = NULL;
1852         int rc;
1853
1854         fd = open(fname, O_RDWR);
1855         if (fd < 0) {
1856                 error_loc = "open source file";
1857                 rc = -errno;
1858                 goto out;
1859         }
1860
1861         fdv = open(victim_file, O_RDWR);
1862         if (fdv < 0) {
1863                 error_loc = "open target file";
1864                 rc = -errno;
1865                 goto out;
1866         }
1867
1868         if (fstat(fd, &stbuf) || fstat(fdv, &stbuf_v)) {
1869                 error_loc = "stat source or target file";
1870                 rc = -errno;
1871                 goto out;
1872         }
1873
1874         if (stbuf.st_dev != stbuf_v.st_dev) {
1875                 error_loc = "stat source and target file";
1876                 rc = -EXDEV;
1877                 goto out;
1878         }
1879
1880         /* mirrors should be of the same size */
1881         if (stbuf.st_size != stbuf_v.st_size) {
1882                 error_loc = "file sizes don't match";
1883                 rc = -EINVAL;
1884                 goto out;
1885         }
1886
1887         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
1888         if (rc < 0) {
1889                 error_loc = "cannot get lease";
1890                 goto out;
1891         }
1892
1893         if (!(mirror_flags & MF_NO_VERIFY)) {
1894                 ssize_t ret;
1895                 /* mirrors should have the same contents */
1896                 ret = mirror_file_compare(fd, fdv);
1897                 if (ret != stbuf.st_size) {
1898                         error_loc = "file busy or contents don't match";
1899                         rc = ret < 0 ? ret : -EINVAL;
1900                         goto out;
1901                 }
1902         }
1903
1904         /* Get rid of caching pages from clients */
1905         rc = llapi_file_flush(fd);
1906         if (rc < 0) {
1907                 error_loc = "cannot get data version";
1908                 goto out;
1909         }
1910
1911         rc = llapi_file_flush(fdv);
1912         if (rc < 0) {
1913                 error_loc = "cannot get data version";
1914                 goto out;
1915         }
1916
1917         rc = migrate_set_timestamps(fd, &stbuf);
1918         if (rc < 0) {
1919                 error_loc = "cannot set source file timestamp";
1920                 goto out;
1921         }
1922
1923         /* Atomically put lease, merge layouts and close. */
1924         data = calloc(1, offsetof(typeof(*data), lil_ids[1]));
1925         if (!data) {
1926                 error_loc = "memory allocation";
1927                 goto out;
1928         }
1929         data->lil_mode = LL_LEASE_UNLCK;
1930         data->lil_flags = LL_LEASE_LAYOUT_MERGE;
1931         data->lil_count = 1;
1932         data->lil_ids[0] = fdv;
1933         rc = llapi_lease_set(fd, data);
1934         if (rc < 0) {
1935                 error_loc = "cannot merge layout";
1936                 goto out;
1937         } else if (rc == 0) {
1938                 rc = -EBUSY;
1939                 error_loc = "lost lease lock";
1940                 goto out;
1941         }
1942         rc = 0;
1943
1944 out:
1945         if (data)
1946                 free(data);
1947         if (fd >= 0)
1948                 close(fd);
1949         if (fdv >= 0)
1950                 close(fdv);
1951         if (!rc)
1952                 (void) unlink(victim_file);
1953         if (rc < 0)
1954                 fprintf(stderr, "error: %s: %s: %s: %s\n",
1955                         progname, fname, error_loc, strerror(-rc));
1956         return rc;
1957 }
1958
1959 static int mirror_extend_layout(char *name, struct llapi_layout *m_layout,
1960                                 bool inherit, uint32_t flags,
1961                                 unsigned long long bandwidth_bytes_sec,
1962                                 enum stats_flag stats_flag,
1963                                 long stats_interval_sec)
1964 {
1965         struct llapi_layout *f_layout = NULL;
1966         struct ll_ioc_lease *data = NULL;
1967         struct stat st;
1968         int fd = -1;
1969         int fdv = -1;
1970         int rc = 0;
1971
1972         if (inherit) {
1973                 f_layout = llapi_layout_get_by_path(name, 0);
1974                 if (!f_layout) {
1975                         rc = -EINVAL;
1976                         fprintf(stderr, "%s: cannot get layout\n", progname);
1977                         goto out;
1978                 }
1979                 rc = llapi_layout_get_last_init_comp(f_layout);
1980                 if (rc) {
1981                         fprintf(stderr, "%s: cannot get the last init comp\n",
1982                                 progname);
1983                         goto out;
1984                 }
1985                 rc = llapi_layout_mirror_inherit(f_layout, m_layout);
1986                 if (rc) {
1987                         fprintf(stderr,
1988                                 "%s: cannot inherit from the last init comp\n",
1989                                 progname);
1990                         goto out;
1991                 }
1992         }
1993
1994         llapi_layout_comp_flags_set(m_layout, flags);
1995         rc = migrate_open_files(name,
1996                              LLAPI_MIGRATION_NONDIRECT | LLAPI_MIGRATION_MIRROR,
1997                              NULL, m_layout, &fd, &fdv);
1998         if (rc < 0)
1999                 goto out;
2000
2001         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
2002         if (rc < 0) {
2003                 error_loc = "cannot get lease";
2004                 goto out;
2005         }
2006
2007         rc = fstat(fd, &st);
2008         if (rc < 0) {
2009                 error_loc = "cannot stat source file";
2010                 goto out;
2011         }
2012
2013         if (stats_flag)
2014                 printf("%s:\n", name);
2015
2016         rc = migrate_nonblock(fd, fdv, bandwidth_bytes_sec, stats_flag,
2017                               stats_interval_sec);
2018         if (rc < 0) {
2019                 llapi_lease_release(fd);
2020                 goto out;
2021         }
2022
2023         rc = migrate_set_timestamps(fd, &st);
2024         if (rc < 0) {
2025                 error_loc = "cannot set source file timestamp";
2026                 goto out;
2027         }
2028
2029         /* Atomically put lease, merge layouts and close. */
2030         data = calloc(1, offsetof(typeof(*data), lil_ids[1]));
2031         if (!data) {
2032                 error_loc = "memory allocation";
2033                 goto out;
2034         }
2035         data->lil_mode = LL_LEASE_UNLCK;
2036         data->lil_flags = LL_LEASE_LAYOUT_MERGE;
2037         data->lil_count = 1;
2038         data->lil_ids[0] = fdv;
2039         rc = llapi_lease_set(fd, data);
2040         if (rc < 0) {
2041                 error_loc = "cannot merge layout";
2042                 goto out;
2043         } else if (rc == 0) {
2044                 rc = -EBUSY;
2045                 error_loc = "lost lease lock";
2046                 goto out;
2047         }
2048         rc = 0;
2049
2050 out:
2051         if (data)
2052                 free(data);
2053         if (fd >= 0)
2054                 close(fd);
2055         if (fdv >= 0)
2056                 close(fdv);
2057         if (rc < 0)
2058                 fprintf(stderr, "error: %s: %s: %s: %s\n",
2059                         progname, name, error_loc, strerror(-rc));
2060         return rc;
2061 }
2062
2063 static int mirror_extend(char *fname, struct mirror_args *mirror_list,
2064                          enum mirror_flags mirror_flags,
2065                          unsigned long long bandwidth_bytes_sec,
2066                          enum stats_flag stats_flag, long stats_interval_sec)
2067 {
2068         int rc = 0;
2069
2070         while (mirror_list) {
2071                 if (mirror_list->m_file) {
2072                         rc = mirror_extend_file(fname, mirror_list->m_file,
2073                                                 mirror_flags);
2074                 } else {
2075                         __u32 mirror_count = mirror_list->m_count;
2076
2077                         while (mirror_count > 0) {
2078                                 rc = mirror_extend_layout(fname,
2079                                                         mirror_list->m_layout,
2080                                                         mirror_list->m_inherit,
2081                                                         mirror_list->m_flags,
2082                                                         bandwidth_bytes_sec,
2083                                                         stats_flag,
2084                                                         stats_interval_sec);
2085                                 if (rc)
2086                                         break;
2087
2088                                 --mirror_count;
2089                         }
2090                 }
2091                 if (rc)
2092                         break;
2093
2094                 mirror_list = mirror_list->m_next;
2095         }
2096
2097         return rc;
2098 }
2099
2100 static int find_mirror_id(struct llapi_layout *layout, void *cbdata)
2101 {
2102         uint32_t id;
2103         int rc;
2104
2105         rc = llapi_layout_mirror_id_get(layout, &id);
2106         if (rc < 0)
2107                 return rc;
2108
2109         if ((__u16)id == *(__u16 *)cbdata)
2110                 return LLAPI_LAYOUT_ITER_STOP;
2111
2112         return LLAPI_LAYOUT_ITER_CONT;
2113 }
2114
2115 static int find_comp_id(struct llapi_layout *layout, void *cbdata)
2116 {
2117         uint32_t id;
2118         int rc;
2119
2120         rc = llapi_layout_comp_id_get(layout, &id);
2121         if (rc < 0)
2122                 return rc;
2123
2124         if (id == *(__u32 *)cbdata)
2125                 return LLAPI_LAYOUT_ITER_STOP;
2126
2127         return LLAPI_LAYOUT_ITER_CONT;
2128 }
2129
2130 static int find_mirror_id_by_pool(struct llapi_layout *layout, void *cbdata)
2131 {
2132         char buf[LOV_MAXPOOLNAME + 1];
2133         struct pool_to_id_cbdata *d = (void *)cbdata;
2134         uint32_t id;
2135         int rc;
2136
2137         rc = llapi_layout_pool_name_get(layout, buf, sizeof(buf));
2138         if (rc < 0)
2139                 return rc;
2140         if (strcmp(d->pool, buf))
2141                 return LLAPI_LAYOUT_ITER_CONT;
2142
2143         rc = llapi_layout_mirror_id_get(layout, &id);
2144         if (rc < 0)
2145                 return rc;
2146         d->id = id;
2147
2148         return LLAPI_LAYOUT_ITER_STOP;
2149 }
2150
2151 static int find_comp_id_by_pool(struct llapi_layout *layout, void *cbdata)
2152 {
2153         char buf[LOV_MAXPOOLNAME + 1];
2154         struct pool_to_id_cbdata *d = (void *)cbdata;
2155         uint32_t id;
2156         int rc;
2157
2158         rc = llapi_layout_pool_name_get(layout, buf, sizeof(buf));
2159         if (rc < 0)
2160                 return rc;
2161         if (strcmp(d->pool, buf))
2162                 return LLAPI_LAYOUT_ITER_CONT;
2163
2164         rc = llapi_layout_comp_id_get(layout, &id);
2165         if (rc < 0)
2166                 return rc;
2167         d->id = id;
2168
2169         return LLAPI_LAYOUT_ITER_STOP;
2170 }
2171
2172 struct collect_ids_data {
2173         __u16   *cid_ids;
2174         int     cid_count;
2175         __u16   cid_exclude;
2176 };
2177
2178 static int collect_mirror_id(struct llapi_layout *layout, void *cbdata)
2179 {
2180         struct collect_ids_data *cid = cbdata;
2181         uint32_t id;
2182         int rc;
2183
2184         rc = llapi_layout_mirror_id_get(layout, &id);
2185         if (rc < 0)
2186                 return rc;
2187
2188         if ((__u16)id != cid->cid_exclude) {
2189                 int i;
2190
2191                 for (i = 0; i < cid->cid_count; i++) {
2192                         /* already collected the mirror id */
2193                         if (id == cid->cid_ids[i])
2194                                 return LLAPI_LAYOUT_ITER_CONT;
2195                 }
2196                 cid->cid_ids[cid->cid_count] = id;
2197                 cid->cid_count++;
2198         }
2199
2200         return LLAPI_LAYOUT_ITER_CONT;
2201 }
2202
2203 /**
2204  * last_non_stale_mirror() - Check if a mirror is the last non-stale mirror.
2205  * @mirror_id: Mirror id to be checked.
2206  * @layout:    Mirror component list.
2207  *
2208  * This function checks if a mirror with specified @mirror_id is the last
2209  * non-stale mirror of a layout @layout.
2210  *
2211  * Return: true or false.
2212  */
2213 static inline
2214 bool last_non_stale_mirror(__u16 mirror_id, struct llapi_layout *layout)
2215 {
2216         __u16 mirror_ids[128] = { 0 };
2217         struct collect_ids_data cid = { .cid_ids = mirror_ids,
2218                                         .cid_count = 0,
2219                                         .cid_exclude = mirror_id, };
2220         int i;
2221
2222         llapi_layout_comp_iterate(layout, collect_mirror_id, &cid);
2223
2224         for (i = 0; i < cid.cid_count; i++) {
2225                 struct llapi_resync_comp comp_array[1024] = { { 0 } };
2226                 int comp_size = 0;
2227
2228                 comp_size = llapi_mirror_find_stale(layout, comp_array,
2229                                                     ARRAY_SIZE(comp_array),
2230                                                     &mirror_ids[i], 1);
2231                 if (comp_size == 0)
2232                         return false;
2233         }
2234
2235         return true;
2236 }
2237
2238 static int mirror_split(const char *fname, __u32 id, const char *pool,
2239                         enum mirror_flags mflags, const char *victim_file)
2240 {
2241         struct llapi_layout *layout;
2242         char parent[PATH_MAX];
2243         char victim[PATH_MAX];
2244         int flags = O_CREAT | O_EXCL | O_LOV_DELAY_CREATE | O_NOFOLLOW;
2245         char *ptr;
2246         struct ll_ioc_lease *data;
2247         uint16_t mirror_count;
2248         __u32 mirror_id;
2249         int mdt_index;
2250         int fd, fdv;
2251         bool purge = true; /* delete mirror by setting fdv=fd */
2252         bool is_encrypted;
2253         int rc;
2254
2255         if (victim_file && (strcmp(fname, victim_file) == 0)) {
2256                 fprintf(stderr,
2257                         "error %s: the source file '%s' and -f file are the same\n",
2258                         progname, fname);
2259                 return -EINVAL;
2260         }
2261
2262         /* check fname contains mirror with mirror_id/comp_id */
2263         layout = llapi_layout_get_by_path(fname, 0);
2264         if (!layout) {
2265                 fprintf(stderr,
2266                         "error %s: file '%s' couldn't get layout\n",
2267                         progname, fname);
2268                 return -EINVAL;
2269         }
2270
2271         rc = llapi_layout_sanity(layout, false, true);
2272         if (rc) {
2273                 llapi_layout_sanity_perror(rc);
2274                 goto free_layout;
2275         }
2276
2277         rc = llapi_layout_mirror_count_get(layout, &mirror_count);
2278         if (rc) {
2279                 fprintf(stderr,
2280                         "error %s: file '%s' couldn't get mirror count\n",
2281                         progname, fname);
2282                 goto free_layout;
2283         }
2284         if (mirror_count < 2) {
2285                 fprintf(stderr,
2286                         "error %s: file '%s' has %d component, cannot split\n",
2287                         progname, fname, mirror_count);
2288                 goto free_layout;
2289         }
2290
2291         if (mflags & MF_COMP_POOL) {
2292                 struct pool_to_id_cbdata data = { .pool = pool };
2293
2294                 rc = llapi_layout_comp_iterate(layout, find_mirror_id_by_pool,
2295                                                &data);
2296                 mirror_id = data.id;
2297         } else if (mflags & MF_COMP_ID) {
2298                 rc = llapi_layout_comp_iterate(layout, find_comp_id, &id);
2299                 mirror_id = mirror_id_of(id);
2300         } else {
2301                 rc = llapi_layout_comp_iterate(layout, find_mirror_id, &id);
2302                 mirror_id = id;
2303         }
2304         if (rc < 0) {
2305                 fprintf(stderr, "error %s: failed to iterate layout of '%s'\n",
2306                         progname, fname);
2307                 goto free_layout;
2308         } else if (rc == LLAPI_LAYOUT_ITER_CONT) {
2309                 if (mflags & MF_COMP_POOL) {
2310                         fprintf(stderr,
2311                                 "error %s: file '%s' does not contain mirror with pool '%s'\n",
2312                                 progname, fname, pool);
2313                         goto free_layout;
2314                 } else if (mflags & MF_COMP_ID) {
2315                         fprintf(stderr,
2316                                 "error %s: file '%s' does not contain mirror with comp-id %u\n",
2317                                 progname, fname, id);
2318                         goto free_layout;
2319                 } else {
2320                         fprintf(stderr,
2321                                 "error %s: file '%s' does not contain mirror with id %u\n",
2322                                 progname, fname, id);
2323                         goto free_layout;
2324                 }
2325         }
2326
2327         if (!victim_file && mflags & MF_DESTROY)
2328                 /* Allow mirror split even without the key on encrypted files,
2329                  * and in this case of a 'split -d', open file with O_DIRECT
2330                  * (no IOs will be done).
2331                  */
2332                 fd = open(fname, O_RDWR | O_DIRECT | O_FILE_ENC);
2333         else
2334                 fd = open(fname, O_RDWR);
2335
2336         if (fd < 0) {
2337                 fprintf(stderr,
2338                         "error %s: open file '%s' failed: %s\n",
2339                         progname, fname, strerror(errno));
2340                 goto free_layout;
2341         }
2342
2343         /* get victim file directory pathname */
2344         if (strlen(fname) > sizeof(parent) - 1) {
2345                 fprintf(stderr, "error %s: file name of '%s' too long\n",
2346                         progname, fname);
2347                 rc = -ERANGE;
2348                 goto close_fd;
2349         }
2350         strncpy(parent, fname, sizeof(parent));
2351         ptr = strrchr(parent, '/');
2352         if (!ptr) {
2353                 if (!getcwd(parent, sizeof(parent))) {
2354                         fprintf(stderr, "error %s: getcwd failed: %s\n",
2355                                 progname, strerror(errno));
2356                         rc = -errno;
2357                         goto close_fd;
2358                 }
2359         } else {
2360                 if (ptr == parent)
2361                         ptr = parent + 1;
2362                 *ptr = '\0';
2363         }
2364
2365         rc = llapi_file_fget_mdtidx(fd, &mdt_index);
2366         if (rc < 0) {
2367                 fprintf(stderr, "%s: cannot get MDT index of '%s'\n",
2368                         progname, fname);
2369                 goto close_fd;
2370         }
2371
2372         rc = llapi_file_is_encrypted(fd);
2373         if (rc < 0) {
2374                 fprintf(stderr, "%s: cannot get flags of '%s': %d\n",
2375                         progname, fname, rc);
2376                 goto close_fd;
2377         }
2378         is_encrypted = rc;
2379
2380 again:
2381         if (!victim_file) {
2382                 /* use a temp file to store the splitted layout */
2383                 if (mflags & MF_DESTROY) {
2384                         char file_path[PATH_MAX];
2385                         unsigned int rnumber;
2386                         int open_flags;
2387
2388                         if (last_non_stale_mirror(mirror_id, layout)) {
2389                                 rc = -EUCLEAN;
2390                                 fprintf(stderr,
2391                                         "%s: cannot destroy the last non-stale mirror of file '%s'\n",
2392                                         progname, fname);
2393                                 goto close_fd;
2394                         }
2395
2396                         if (purge) {
2397                                 /* don't use volatile file for mirror destroy */
2398                                 fdv = fd;
2399                         } else {
2400                                 /**
2401                                  * try the old way to delete mirror using
2402                                  * volatile file.
2403                                  */
2404                                 do {
2405                                         rnumber = random();
2406                                         rc = snprintf(file_path,
2407                                                       sizeof(file_path),
2408                                                       "%s/" LUSTRE_VOLATILE_HDR ":%.4X:%.4X:fd=%.2d",
2409                                                       parent, mdt_index,
2410                                                       rnumber, fd);
2411                                         if (rc < 0 ||
2412                                             rc >= sizeof(file_path)) {
2413                                                 fdv = -ENAMETOOLONG;
2414                                                 break;
2415                                         }
2416
2417                                         open_flags = O_RDWR |
2418                                              (O_LOV_DELAY_CREATE & ~O_ACCMODE) |
2419                                              O_CREAT | O_EXCL | O_NOFOLLOW |
2420                                              /* O_DIRECT for mirror split -d */
2421                                              O_DIRECT |
2422                                              /* Allow split without the key */
2423                                              O_FILE_ENC;
2424                                         fdv = open(file_path, open_flags,
2425                                                    S_IRUSR | S_IWUSR);
2426                                         if (fdv < 0)
2427                                                 rc = -errno;
2428                                 } while (fdv < 0 && rc == -EEXIST);
2429                         }
2430                 } else {
2431                         if (is_encrypted) {
2432                                 rc = -1;
2433                                 fprintf(stderr,
2434                                         "error %s: not permitted on encrypted file '%s': %d\n",
2435                                         progname, fname, rc);
2436                                 goto close_fd;
2437                         }
2438
2439                         snprintf(victim, sizeof(victim), "%s.mirror~%u",
2440                                  fname, mirror_id);
2441                         fdv = open(victim, flags, S_IRUSR | S_IWUSR);
2442                 }
2443         } else {
2444                 /* user specified victim file */
2445                 if (is_encrypted) {
2446                         rc = -1;
2447                         fprintf(stderr,
2448                                 "error %s: not permitted on encrypted file '%s': %d\n",
2449                                 progname, fname, rc);
2450                         goto close_fd;
2451                 }
2452                 fdv = open(victim_file, flags, S_IRUSR | S_IWUSR);
2453         }
2454
2455         if (fdv < 0) {
2456                 fprintf(stderr,
2457                         "error %s: create victim file failed: %s\n",
2458                         progname, strerror(errno));
2459                 goto close_fd;
2460         }
2461
2462         /* get lease lock of fname */
2463         rc = llapi_lease_acquire(fd, LL_LEASE_WRLCK);
2464         if (rc < 0) {
2465                 fprintf(stderr,
2466                         "error %s: cannot get lease of file '%s': %d\n",
2467                         progname, fname, rc);
2468                 goto close_victim;
2469         }
2470
2471         /* Atomatically put lease, split layouts and close. */
2472         data = malloc(offsetof(typeof(*data), lil_ids[2]));
2473         if (!data) {
2474                 rc = -ENOMEM;
2475                 goto close_victim;
2476         }
2477
2478         data->lil_mode = LL_LEASE_UNLCK;
2479         data->lil_flags = LL_LEASE_LAYOUT_SPLIT;
2480         data->lil_count = 2;
2481         data->lil_ids[0] = fdv;
2482         data->lil_ids[1] = mirror_id;
2483         rc = llapi_lease_set(fd, data);
2484         if (rc <= 0) {
2485                 if ((rc == -EINVAL || rc == -EBUSY) && purge) {
2486                         /* could be old MDS which prohibit fd==fdv */
2487                         purge = false;
2488                         goto again;
2489
2490                 }
2491                 if (rc == 0) /* lost lease lock */
2492                         rc = -EBUSY;
2493                 fprintf(stderr,
2494                         "error %s: cannot split '%s': %s\n",
2495                         progname, fname, strerror(-rc));
2496         } else {
2497                 rc = 0;
2498         }
2499         free(data);
2500
2501 close_victim:
2502         if (!purge)
2503                 close(fdv);
2504 close_fd:
2505         close(fd);
2506 free_layout:
2507         llapi_layout_free(layout);
2508         return rc;
2509 }
2510
2511 static inline
2512 int lfs_mirror_resync_file(const char *fname, struct ll_ioc_lease *ioc,
2513                            __u16 *mirror_ids, int ids_nr);
2514
2515 static int lfs_migrate_to_dom(int fd, int fdv, char *name,
2516                               __u64 migration_flags,
2517                               unsigned long long bandwidth_bytes_sec,
2518                               enum stats_flag stats_flag,
2519                               long stats_interval_sec)
2520 {
2521         struct ll_ioc_lease *data = NULL;
2522         int rc;
2523
2524         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
2525         if (rc < 0) {
2526                 error_loc = "cannot get lease";
2527                 goto out_close;
2528         }
2529
2530         if (stats_flag)
2531                 printf("%s:\n", name);
2532
2533         rc = migrate_nonblock(fd, fdv, bandwidth_bytes_sec, stats_flag,
2534                               stats_interval_sec);
2535         if (rc < 0)
2536                 goto out_release;
2537
2538         /* Atomically put lease, merge layouts, resync and close. */
2539         data = calloc(1, offsetof(typeof(*data), lil_ids[1]));
2540         if (!data) {
2541                 error_loc = "memory allocation";
2542                 goto out_release;
2543         }
2544         data->lil_mode = LL_LEASE_UNLCK;
2545         data->lil_flags = LL_LEASE_LAYOUT_MERGE;
2546         data->lil_count = 1;
2547         data->lil_ids[0] = fdv;
2548         rc = llapi_lease_set(fd, data);
2549         if (rc < 0) {
2550                 error_loc = "cannot merge layout";
2551                 goto out_close;
2552         } else if (rc == 0) {
2553                 rc = -EBUSY;
2554                 error_loc = "lost lease lock";
2555                 goto out_close;
2556         }
2557         close(fd);
2558         close(fdv);
2559
2560         rc = lfs_mirror_resync_file(name, data, NULL, 0);
2561         if (rc) {
2562                 error_loc = "cannot resync file";
2563                 goto out;
2564         }
2565
2566         /* delete first mirror now */
2567         rc = mirror_split(name, 1, NULL, MF_DESTROY, NULL);
2568         if (rc < 0)
2569                 error_loc = "cannot delete old layout";
2570         goto out;
2571
2572 out_release:
2573         llapi_lease_release(fd);
2574 out_close:
2575         close(fd);
2576         close(fdv);
2577 out:
2578         if (rc < 0)
2579                 fprintf(stderr, "error: %s: %s: %s: %s\n",
2580                         progname, name, error_loc, strerror(-rc));
2581         else if (migration_flags & LLAPI_MIGRATION_VERBOSE)
2582                 printf("%s\n", name);
2583         if (data)
2584                 free(data);
2585         return rc;
2586 }
2587
2588 /**
2589  * Parse a string containing an target index list into an array of integers.
2590  *
2591  * The input string contains a comma delimited list of individual
2592  * indices and ranges, for example "1,2-4,7". Add the indices into the
2593  * \a tgts array and remove duplicates.
2594  *
2595  * \param[out] tgts             array to store indices in
2596  * \param[in] size              size of \a tgts array
2597  * \param[in] offset            starting index in \a tgts
2598  * \param[in] arg               string containing OST index list
2599  * \param[in/out] overstriping  index list may contain duplicates
2600  *
2601  * \retval positive    number of indices in \a tgts
2602  * \retval -EINVAL     unable to parse \a arg
2603  */
2604 static int parse_targets(__u32 *tgts, int size, int offset, char *arg,
2605                          unsigned long long *pattern)
2606 {
2607         int rc;
2608         int nr = offset;
2609         int slots = size - offset;
2610         char *ptr = NULL;
2611         bool overstriped = false;
2612         bool end_of_loop;
2613
2614         if (!arg)
2615                 return -EINVAL;
2616
2617         end_of_loop = false;
2618         while (!end_of_loop) {
2619                 int start_index = 0;
2620                 int end_index = 0;
2621                 int i;
2622                 char *endptr = NULL;
2623
2624                 rc = -EINVAL;
2625
2626                 ptr = strchrnul(arg, ',');
2627
2628                 end_of_loop = *ptr == '\0';
2629                 *ptr = '\0';
2630
2631                 errno = 0;
2632                 start_index = strtol(arg, &endptr, 0);
2633                 if (endptr == arg) /* no data at all */
2634                         break;
2635                 if (errno != 0 || start_index < -1 ||
2636                     (*endptr != '-' && *endptr != '\0'))
2637                         break;
2638
2639                 end_index = start_index;
2640                 if (*endptr == '-') {
2641                         errno = 0;
2642                         end_index = strtol(endptr + 1, &endptr, 0);
2643                         if (errno != 0 || *endptr != '\0' || end_index < -1)
2644                                 break;
2645                         if (end_index < start_index)
2646                                 break;
2647                 }
2648
2649                 for (i = start_index; i <= end_index && slots > 0; i++) {
2650                         int j;
2651
2652                         /* remove duplicate */
2653                         for (j = 0; j < offset; j++) {
2654                                 if (tgts[j] == i && pattern &&
2655                                     *pattern == LLAPI_LAYOUT_OVERSTRIPING)
2656                                         overstriped = true;
2657                                 else if (tgts[j] == i)
2658                                         return -EINVAL;
2659                         }
2660
2661                         j = offset;
2662
2663                         if (j == offset) { /* check complete */
2664                                 tgts[nr++] = i;
2665                                 --slots;
2666                         }
2667                 }
2668
2669                 if (slots == 0 && i < end_index)
2670                         break;
2671
2672                 *ptr = ',';
2673                 arg = ++ptr;
2674                 offset = nr;
2675                 rc = 0;
2676         }
2677         if (!end_of_loop && ptr)
2678                 *ptr = ',';
2679
2680         if (!overstriped && pattern)
2681                 *pattern = LLAPI_LAYOUT_DEFAULT;
2682
2683         return rc < 0 ? rc : nr;
2684 }
2685
2686 struct lfs_setstripe_args {
2687         unsigned long long       lsa_comp_end;
2688         unsigned long long       lsa_stripe_size;
2689         unsigned long long       lsa_extension_size;
2690         long long                lsa_stripe_count;
2691         long long                lsa_stripe_off;
2692         __u32                    lsa_comp_flags;
2693         __u32                    lsa_comp_neg_flags;
2694         unsigned long long       lsa_pattern;
2695         unsigned int             lsa_mirror_count;
2696         int                      lsa_nr_tgts;
2697         bool                     lsa_first_comp;
2698         bool                     lsa_extension_comp;
2699         __u32                   *lsa_tgts;
2700         char                    *lsa_pool_name;
2701 };
2702
2703 static inline void setstripe_args_init(struct lfs_setstripe_args *lsa)
2704 {
2705         unsigned int mirror_count = lsa->lsa_mirror_count;
2706         bool first_comp = lsa->lsa_first_comp;
2707
2708         memset(lsa, 0, sizeof(*lsa));
2709
2710         lsa->lsa_stripe_size = LLAPI_LAYOUT_DEFAULT;
2711         lsa->lsa_stripe_count = LLAPI_LAYOUT_DEFAULT;
2712         lsa->lsa_stripe_off = LLAPI_LAYOUT_DEFAULT;
2713         lsa->lsa_pattern = LLAPI_LAYOUT_RAID0;
2714         lsa->lsa_pool_name = NULL;
2715
2716         lsa->lsa_mirror_count = mirror_count;
2717         lsa->lsa_first_comp = first_comp;
2718 }
2719
2720 /**
2721  * setstripe_args_init_inherit() - Initialize and inherit stripe options.
2722  * @lsa: Stripe options to be initialized and inherited.
2723  *
2724  * This function initializes stripe options in @lsa and inherit
2725  * stripe_size, stripe_count and OST pool_name options.
2726  *
2727  * Return: void.
2728  */
2729 static inline void setstripe_args_init_inherit(struct lfs_setstripe_args *lsa)
2730 {
2731         unsigned long long stripe_size;
2732         long long stripe_count;
2733         char *pool_name = NULL;
2734
2735         stripe_size = lsa->lsa_stripe_size;
2736         stripe_count = lsa->lsa_stripe_count;
2737         pool_name = lsa->lsa_pool_name;
2738
2739         setstripe_args_init(lsa);
2740
2741         lsa->lsa_stripe_size = stripe_size;
2742         lsa->lsa_stripe_count = stripe_count;
2743         lsa->lsa_pool_name = pool_name;
2744 }
2745
2746 static inline bool setstripe_args_specified(struct lfs_setstripe_args *lsa)
2747 {
2748         return (lsa->lsa_stripe_size != LLAPI_LAYOUT_DEFAULT ||
2749                 lsa->lsa_stripe_count != LLAPI_LAYOUT_DEFAULT ||
2750                 lsa->lsa_stripe_off != LLAPI_LAYOUT_DEFAULT ||
2751                 lsa->lsa_pattern != LLAPI_LAYOUT_RAID0 ||
2752                 lsa->lsa_comp_end != 0);
2753 }
2754
2755 static int lsa_args_stripe_count_check(struct lfs_setstripe_args *lsa)
2756 {
2757         if (lsa->lsa_nr_tgts) {
2758                 if (lsa->lsa_nr_tgts < 0 ||
2759                     lsa->lsa_nr_tgts >= LOV_MAX_STRIPE_COUNT) {
2760                         fprintf(stderr, "Invalid nr_tgts(%d)\n",
2761                                 lsa->lsa_nr_tgts);
2762                         errno = EINVAL;
2763                         return -1;
2764                 }
2765
2766                 if (lsa->lsa_stripe_count > 0 &&
2767                     lsa->lsa_stripe_count != LLAPI_LAYOUT_DEFAULT &&
2768                     lsa->lsa_stripe_count != LLAPI_LAYOUT_WIDE &&
2769                     lsa->lsa_nr_tgts != lsa->lsa_stripe_count) {
2770                         fprintf(stderr, "stripe_count(%lld) != nr_tgts(%d)\n",
2771                                 lsa->lsa_stripe_count,
2772                                 lsa->lsa_nr_tgts);
2773                         errno = EINVAL;
2774                         return -1;
2775                 }
2776         }
2777
2778         return 0;
2779
2780 }
2781
2782 /**
2783  * comp_args_to_layout() - Create or extend a composite layout.
2784  * @composite:       Pointer to the composite layout.
2785  * @lsa:             Stripe options for the new component.
2786  *
2787  * This function creates or extends a composite layout by adding a new
2788  * component with stripe options from @lsa.
2789  *
2790  * When modified, adjust llapi_stripe_param_verify() if needed as well.
2791  *
2792  * Return: 0 on success or an error code on failure.
2793  */
2794 static int comp_args_to_layout(struct llapi_layout **composite,
2795                                struct lfs_setstripe_args *lsa,
2796                                bool set_extent)
2797 {
2798         struct llapi_layout *layout = *composite;
2799         uint64_t prev_end = 0;
2800         uint64_t size;
2801         int i = 0, rc;
2802
2803 new_comp:
2804         if (!layout) {
2805                 layout = llapi_layout_alloc();
2806                 if (!layout) {
2807                         fprintf(stderr, "Alloc llapi_layout failed. %s\n",
2808                                 strerror(errno));
2809                         errno = ENOMEM;
2810                         return -1;
2811                 }
2812                 *composite = layout;
2813                 lsa->lsa_first_comp = true;
2814         } else {
2815                 uint64_t start;
2816
2817                 /*
2818                  * Get current component extent, current component
2819                  * must be the tail component.
2820                  */
2821                 rc = llapi_layout_comp_extent_get(layout, &start, &prev_end);
2822                 if (rc) {
2823                         fprintf(stderr, "Get comp extent failed. %s\n",
2824                                 strerror(errno));
2825                         return rc;
2826                 }
2827
2828                 if (lsa->lsa_first_comp) {
2829                         prev_end = 0;
2830                         rc = llapi_layout_add_first_comp(layout);
2831                 } else {
2832                         rc = llapi_layout_comp_add(layout);
2833                 }
2834                 if (rc) {
2835                         fprintf(stderr, "Add component failed. %s\n",
2836                                 strerror(errno));
2837                         return rc;
2838                 }
2839         }
2840
2841         rc = llapi_layout_comp_flags_set(layout, lsa->lsa_comp_flags);
2842         if (rc) {
2843                 fprintf(stderr, "Set flags 0x%x failed: %s\n",
2844                         lsa->lsa_comp_flags, strerror(errno));
2845                 return rc;
2846         }
2847
2848         if (set_extent) {
2849                 uint64_t comp_end = lsa->lsa_comp_end;
2850
2851                 /*
2852                  * The extendable component is 0-length, so it can be removed
2853                  * if there is insufficient space to extend it.
2854                  */
2855                 if (lsa->lsa_extension_comp)
2856                         comp_end = prev_end;
2857
2858                 rc = llapi_layout_comp_extent_set(layout, prev_end,
2859                                                   comp_end);
2860                 if (rc) {
2861                         fprintf(stderr, "Set extent [%lu, %lu) failed. %s\n",
2862                                 prev_end, comp_end, strerror(errno));
2863                         return rc;
2864                 }
2865         }
2866         /* reset lsa_first_comp */
2867         lsa->lsa_first_comp = false;
2868
2869         /* Data-on-MDT component setting */
2870         if (lsa->lsa_pattern == LLAPI_LAYOUT_MDT) {
2871                 /* Yaml support */
2872                 if (lsa->lsa_stripe_count == 0)
2873                         lsa->lsa_stripe_count = LLAPI_LAYOUT_DEFAULT;
2874                 if (lsa->lsa_stripe_size == lsa->lsa_comp_end)
2875                         lsa->lsa_stripe_size = LLAPI_LAYOUT_DEFAULT;
2876                 if (lsa->lsa_stripe_off == -1 ||
2877                     lsa->lsa_stripe_off == 0)
2878                         lsa->lsa_stripe_off = LLAPI_LAYOUT_DEFAULT;
2879                 /*
2880                  * In case of Data-on-MDT patterns the only extra option
2881                  * applicable is stripe size option.
2882                  */
2883                 if (lsa->lsa_stripe_count != LLAPI_LAYOUT_DEFAULT) {
2884                         fprintf(stderr,
2885                                 "Option 'stripe-count' can't be specified with Data-on-MDT component: %lld\n",
2886                                 lsa->lsa_stripe_count);
2887                         errno = EINVAL;
2888                         return -1;
2889                 }
2890                 if (lsa->lsa_stripe_size != LLAPI_LAYOUT_DEFAULT &&
2891                     lsa->lsa_stripe_size != lsa->lsa_comp_end - prev_end) {
2892                         fprintf(stderr,
2893                                 "Option 'stripe-size' can't be specified with Data-on-MDT component: %llu\n",
2894                                 lsa->lsa_stripe_size);
2895                         errno = EINVAL;
2896                         return -1;
2897                 }
2898                 if (lsa->lsa_nr_tgts != 0) {
2899                         fprintf(stderr,
2900                                 "Option 'ost-list' can't be specified with Data-on-MDT component: '%i'\n",
2901                                 lsa->lsa_nr_tgts);
2902                         errno = EINVAL;
2903                         return -1;
2904                 }
2905                 if (lsa->lsa_stripe_off != LLAPI_LAYOUT_DEFAULT) {
2906                         fprintf(stderr,
2907                                 "Option 'stripe-offset' can't be specified with Data-on-MDT component: %lld\n",
2908                                 lsa->lsa_stripe_off);
2909                         errno = EINVAL;
2910                         return -1;
2911                 }
2912                 if (lsa->lsa_pool_name != 0) {
2913                         fprintf(stderr,
2914                                 "Option 'pool' can't be specified with Data-on-MDT component: '%s'\n",
2915                                 lsa->lsa_pool_name);
2916                         errno = EINVAL;
2917                         return -1;
2918                 }
2919
2920                 rc = llapi_layout_pattern_set(layout, lsa->lsa_pattern);
2921                 if (rc) {
2922                         fprintf(stderr, "Set stripe pattern %#llx failed. %s\n",
2923                                 lsa->lsa_pattern,
2924                                 strerror(errno));
2925                         return rc;
2926                 }
2927                 /* Data-on-MDT component has always single stripe up to end */
2928                 lsa->lsa_stripe_size = lsa->lsa_comp_end;
2929         } else if (lsa->lsa_pattern == LLAPI_LAYOUT_OVERSTRIPING) {
2930                 rc = llapi_layout_pattern_set(layout, lsa->lsa_pattern);
2931                 if (rc) {
2932                         fprintf(stderr, "Set stripe pattern %#llx failed. %s\n",
2933                                 lsa->lsa_pattern,
2934                                 strerror(errno));
2935                         return rc;
2936                 }
2937         }
2938
2939         size = lsa->lsa_comp_flags & LCME_FL_EXTENSION ?
2940                 lsa->lsa_extension_size : lsa->lsa_stripe_size;
2941
2942         if (lsa->lsa_comp_flags & LCME_FL_EXTENSION)
2943                 rc = llapi_layout_extension_size_set(layout, size);
2944         else
2945                 rc = llapi_layout_stripe_size_set(layout, size);
2946
2947         if (rc) {
2948                 fprintf(stderr, "Set stripe size %lu failed: %s\n",
2949                         size, strerror(errno));
2950                 return rc;
2951         }
2952
2953         rc = llapi_layout_stripe_count_set(layout, lsa->lsa_stripe_count);
2954         if (rc) {
2955                 fprintf(stderr, "Set stripe count %lld failed: %s\n",
2956                         lsa->lsa_stripe_count, strerror(errno));
2957                 return rc;
2958         }
2959
2960         if (lsa->lsa_pool_name) {
2961                 rc = llapi_layout_pool_name_set(layout, lsa->lsa_pool_name);
2962                 if (rc) {
2963                         fprintf(stderr, "Set pool name: %s failed. %s\n",
2964                                 lsa->lsa_pool_name, strerror(errno));
2965                         return rc;
2966                 }
2967         } else {
2968                 rc = llapi_layout_pool_name_set(layout, "");
2969                 if (rc) {
2970                         fprintf(stderr, "Clear pool name failed: %s\n",
2971                                 strerror(errno));
2972                         return rc;
2973                 }
2974         }
2975
2976         rc = lsa_args_stripe_count_check(lsa);
2977         if (rc)
2978                 return rc;
2979
2980         if (lsa->lsa_nr_tgts > 0) {
2981                 bool found = false;
2982
2983                 for (i = 0; i < lsa->lsa_nr_tgts; i++) {
2984                         rc = llapi_layout_ost_index_set(layout, i,
2985                                                         lsa->lsa_tgts[i]);
2986                         if (rc)
2987                                 break;
2988
2989                         /* Make sure stripe offset is in OST list. */
2990                         if (lsa->lsa_tgts[i] == lsa->lsa_stripe_off)
2991                                 found = true;
2992                 }
2993                 if (!found) {
2994                         fprintf(stderr, "Invalid stripe offset '%lld', not in the target list",
2995                                 lsa->lsa_stripe_off);
2996                         errno = EINVAL;
2997                         return -1;
2998                 }
2999         } else if (lsa->lsa_stripe_off != LLAPI_LAYOUT_DEFAULT &&
3000                    lsa->lsa_stripe_off != -1) {
3001                 rc = llapi_layout_ost_index_set(layout, 0, lsa->lsa_stripe_off);
3002         }
3003         if (rc) {
3004                 fprintf(stderr, "Set ost index %d failed. %s\n",
3005                         i, strerror(errno));
3006                 return rc;
3007         }
3008
3009         /* Create the second, virtual component of extension space */
3010         if (lsa->lsa_extension_comp) {
3011                 lsa->lsa_comp_flags |= LCME_FL_EXTENSION;
3012                 lsa->lsa_extension_comp = false;
3013                 goto new_comp;
3014         }
3015
3016         return rc;
3017 }
3018
3019 static int build_component(struct llapi_layout **layout,
3020                            struct lfs_setstripe_args *lsa, bool set_extent)
3021 {
3022         int rc;
3023
3024         rc = comp_args_to_layout(layout, lsa, set_extent);
3025         if (rc)
3026                 return rc;
3027
3028         if (lsa->lsa_mirror_count > 0) {
3029                 rc = llapi_layout_mirror_count_set(*layout,
3030                                                    lsa->lsa_mirror_count);
3031                 if (rc)
3032                         return rc;
3033
3034                 rc = llapi_layout_flags_set(*layout, LCM_FL_RDONLY);
3035                 if (rc)
3036                         return rc;
3037                 lsa->lsa_mirror_count = 0;
3038         }
3039
3040         return rc;
3041 }
3042
3043 static int build_prev_component(struct llapi_layout **layout,
3044                                 struct lfs_setstripe_args *prev,
3045                                 struct lfs_setstripe_args *lsa,
3046                                 bool set_extent)
3047 {
3048         int extension = lsa->lsa_comp_flags & LCME_FL_EXTENSION;
3049         int rc;
3050
3051         if (prev->lsa_stripe_size) {
3052                 if (extension) {
3053                         prev->lsa_comp_end = lsa->lsa_comp_end;
3054                         prev->lsa_extension_size = lsa->lsa_extension_size;
3055                         prev->lsa_extension_comp = true;
3056                 }
3057
3058                 rc = build_component(layout, prev, true);
3059                 if (rc)
3060                         return rc;
3061         }
3062
3063         /*
3064          * Copy lsa to previous lsa;
3065          * if this is an extension component, make the previous invalid;
3066          */
3067         if (extension)
3068                 prev->lsa_stripe_size = 0;
3069         else
3070                 *prev = *lsa;
3071
3072         return 0;
3073 }
3074
3075 #ifndef LCME_TEMPLATE_FLAGS
3076 #define LCME_TEMPLATE_FLAGS     (LCME_FL_PREF_RW | LCME_FL_NOSYNC | \
3077                                  LCME_FL_EXTENSION)
3078 #endif
3079
3080 static int build_layout_from_yaml_node(struct cYAML *node,
3081                                        struct llapi_layout **layout,
3082                                        struct lfs_setstripe_args *lsa,
3083                                        struct lfs_setstripe_args *prevp)
3084 {
3085         struct lfs_setstripe_args prev = { 0 };
3086         __u32 *osts = lsa->lsa_tgts;
3087         char *string;
3088         int rc = 0;
3089
3090         if (!prevp)
3091                 prevp = &prev;
3092
3093         while (node) {
3094                 string = node->cy_string;
3095
3096                 if (node->cy_type == CYAML_TYPE_OBJECT) {
3097                         /* go deep to sub blocks */
3098                         if (string && !strncmp(string, "component", 9) &&
3099                             strncmp(string, "component0", 10) &&
3100                             strncmp(string, "components", 10)) {
3101                                 rc = build_prev_component(layout, prevp, lsa,
3102                                                           true);
3103                                 if (rc)
3104                                         return rc;
3105
3106                                 /* initialize lsa. */
3107                                 setstripe_args_init(lsa);
3108                                 lsa->lsa_first_comp = false;
3109                                 lsa->lsa_tgts = osts;
3110                         }
3111
3112                         rc = build_layout_from_yaml_node(node->cy_child, layout,
3113                                                          lsa, prevp);
3114                         if (rc)
3115                                 return rc;
3116                 } else {
3117                         if (!node->cy_string)
3118                                 return -EINVAL;
3119
3120                         /* skip leading lmm_ if present, to simplify parsing */
3121                         if (strncmp(string, "lmm_", 4) == 0)
3122                                 string += 4;
3123
3124                         if (node->cy_type == CYAML_TYPE_STRING) {
3125                                 if (!strcmp(string, "lcme_extent.e_end")) {
3126                                         if (!strcmp(node->cy_valuestring, "EOF") ||
3127                                             !strcmp(node->cy_valuestring, "eof"))
3128                                                 lsa->lsa_comp_end = LUSTRE_EOF;
3129                                 } else if (!strcmp(string, "pool")) {
3130                                         lsa->lsa_pool_name = node->cy_valuestring;
3131                                 } else if (!strcmp(string, "pattern")) {
3132                                         if (!strcmp(node->cy_valuestring, "mdt"))
3133                                                 lsa->lsa_pattern = LLAPI_LAYOUT_MDT;
3134                                         if (!strcmp(node->cy_valuestring,
3135                                                     "raid0,overstriped"))
3136                                                 lsa->lsa_pattern =
3137                                                         LLAPI_LAYOUT_OVERSTRIPING;
3138                                 } else if (!strcmp(string, "lcme_flags")) {
3139                                         rc = comp_str2flags(node->cy_valuestring,
3140                                                             &lsa->lsa_comp_flags,
3141                                                             &lsa->lsa_comp_neg_flags);
3142                                         if (rc)
3143                                                 return rc;
3144                                         /*
3145                                          * Only template flags have meaning in
3146                                          * the layout for a new file
3147                                          */
3148                                         lsa->lsa_comp_flags &= LCME_TEMPLATE_FLAGS;
3149                                 }
3150                         } else if (node->cy_type == CYAML_TYPE_NUMBER) {
3151                                 if (!strcmp(string, "lcm_mirror_count")) {
3152                                         lsa->lsa_mirror_count = node->cy_valueint;
3153                                 } else if (!strcmp(string, "lcme_extent.e_start")) {
3154                                         if (node->cy_valueint == 0)
3155                                                 lsa->lsa_first_comp = true;
3156                                 } else if (!strcmp(string, "lcme_extent.e_end")) {
3157                                         if (node->cy_valueint == -1)
3158                                                 lsa->lsa_comp_end = LUSTRE_EOF;
3159                                         else
3160                                                 lsa->lsa_comp_end = node->cy_valueint;
3161                                 } else if (!strcmp(string, "stripe_count")) {
3162                                         lsa->lsa_stripe_count = node->cy_valueint;
3163                                 } else if (!strcmp(string, "stripe_size")) {
3164                                         lsa->lsa_stripe_size = node->cy_valueint;
3165                                 } else if (!strcmp(string, "extension_size")) {
3166                                         lsa->lsa_extension_size = node->cy_valueint;
3167                                         lsa->lsa_extension_comp = true;
3168                                 } else if (!strcmp(string, "stripe_offset")) {
3169                                         lsa->lsa_stripe_off = node->cy_valueint;
3170                                 } else if (!strcmp(string, "l_ost_idx")) {
3171                                         osts[lsa->lsa_nr_tgts] = node->cy_valueint;
3172                                         lsa->lsa_nr_tgts++;
3173                                 }
3174                         }
3175                 }
3176                 node = node->cy_next;
3177         }
3178
3179         if (prevp == &prev) {
3180                 rc = build_prev_component(layout, prevp, lsa, true);
3181                 if (rc)
3182                         return rc;
3183
3184                 if (!(lsa->lsa_comp_flags & LCME_FL_EXTENSION))
3185                         rc = build_component(layout, lsa, *layout != NULL);
3186         }
3187
3188         return rc;
3189 }
3190
3191 static int lfs_comp_create_from_yaml(char *template,
3192                                      struct llapi_layout **layout,
3193                                      struct lfs_setstripe_args *lsa,
3194                                      __u32 *osts)
3195 {
3196         struct cYAML *tree = NULL, *err_rc = NULL;
3197         int rc = 0;
3198
3199         tree = cYAML_build_tree(template, NULL, 0, &err_rc, false);
3200         if (!tree) {
3201                 fprintf(stderr, "%s: cannot parse YAML file %s\n",
3202                         progname, template);
3203                 cYAML_build_error(-EINVAL, -1, "yaml", "from comp yaml",
3204                                   "can't parse", &err_rc);
3205                 cYAML_print_tree2file(stderr, err_rc);
3206                 cYAML_free_tree(err_rc);
3207                 rc = -EINVAL;
3208                 goto err;
3209         }
3210
3211         /* initialize lsa for plain file */
3212         setstripe_args_init(lsa);
3213         lsa->lsa_tgts = osts;
3214
3215         rc = build_layout_from_yaml_node(tree, layout, lsa, NULL);
3216         if (rc) {
3217                 fprintf(stderr, "%s: cannot build layout from YAML file %s.\n",
3218                         progname, template);
3219                 goto err;
3220         }
3221         /* clean clean lsa */
3222         setstripe_args_init(lsa);
3223
3224 err:
3225         if (tree)
3226                 cYAML_free_tree(tree);
3227         return rc;
3228 }
3229
3230 /**
3231  * Get the extension size from the next (SEL) component and extend the
3232  * current component on it. The start of the next component is to be
3233  * adjusted as well.
3234  *
3235  * \param[in] layout    the current layout
3236  * \param[in] start     the start of the current component
3237  * \param[in,out] end   the end of the current component
3238  * \param[in] offset    the offset to adjust the end position to instead of
3239  *                      extension size
3240  *
3241  * \retval 0            - extended successfully
3242  * \retval < 0          - error
3243  */
3244 static int layout_extend_comp(struct llapi_layout *layout,
3245                               uint64_t start, uint64_t *end,
3246                               uint64_t offset)
3247 {
3248         uint64_t size, next_start, next_end;
3249         int rc;
3250
3251         rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_NEXT);
3252         if (rc < 0) {
3253                 fprintf(stderr,
3254                         "%s setstripe: cannot move component cursor: %s\n",
3255                         progname, strerror(errno));
3256                 return rc;
3257         }
3258
3259         /*
3260          * Even if the @size will not be used below, this will fail if
3261          * this is not a SEL component - a good confirmation we are
3262          * working on right components.
3263          */
3264         rc = llapi_layout_extension_size_get(layout, &size);
3265         if (rc < 0) {
3266                 fprintf(stderr,
3267                         "%s setstripe: cannot get component ext size: %s\n",
3268                         progname, strerror(errno));
3269                 return rc;
3270         }
3271
3272         rc = llapi_layout_comp_extent_get(layout, &next_start, &next_end);
3273         if (rc) {
3274                 fprintf(stderr, "%s setstripe: cannot get extent: %s\n",
3275                         progname, strerror(errno));
3276                 return rc;
3277         }
3278
3279         next_start += offset ?: size;
3280         rc = llapi_layout_comp_extent_set(layout, next_start, next_end);
3281         if (rc) {
3282                 fprintf(stderr, "%s setstripe: cannot set extent: %s\n",
3283                         progname, strerror(errno));
3284                 return rc;
3285         }
3286
3287         rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_PREV);
3288         if (rc < 0) {
3289                 fprintf(stderr,
3290                         "%s setstripe: cannot move component cursor: %s\n",
3291                         progname, strerror(errno));
3292                 return rc;
3293         }
3294
3295         *end += offset ?: size;
3296         rc = llapi_layout_comp_extent_set(layout, start, *end);
3297         if (rc) {
3298                 fprintf(stderr, "%s setstripe: cannot set extent: %s\n",
3299                         progname, strerror(errno));
3300                 return rc;
3301         }
3302
3303         return 0;
3304 }
3305
3306 /**
3307  * In 'lfs setstripe --component-add' mode, we need to fetch the extent
3308  * end of the last component in the existing file, and adjust the
3309  * first extent start of the components to be added accordingly.
3310  *
3311  * In the create mode, we need to check if the first component is an extendable
3312  * SEL component and extend its length to the extension size (first component
3313  * of the PFL file is initialised at the create time, cannot be 0-lenght.
3314  */
3315 static int layout_adjust_first_extent(char *fname, struct llapi_layout *layout,
3316                                       bool comp_add)
3317 {
3318         struct llapi_layout *head;
3319         uint64_t start = 0, prev_end = 0;
3320         uint64_t end;
3321         int rc, ret = 0;
3322
3323         if (!layout || !(comp_add || llapi_layout_is_composite(layout)))
3324                 return 0;
3325
3326         errno = 0;
3327         while (comp_add) {
3328                 head = llapi_layout_get_by_path(fname, 0);
3329                 if (!head) {
3330                         fprintf(stderr,
3331                                 "%s setstripe: cannot read layout from '%s': %s\n",
3332                                 progname, fname, strerror(errno));
3333                         return -EINVAL;
3334                 } else if (errno == ENODATA) {
3335                         /*
3336                          * file without LOVEA, this component-add will be turned
3337                          * into a component-create.
3338                          */
3339                         llapi_layout_free(head);
3340                         ret = -ENODATA;
3341
3342                         /*
3343                          * the new layout will be added to an empty one, it
3344                          * still needs to be adjusted below
3345                          */
3346                         comp_add = 0;
3347                         break;
3348                 } else if (!llapi_layout_is_composite(head)) {
3349                         fprintf(stderr,
3350                                 "%s setstripe: '%s' not a composite file\n",
3351                                 progname, fname);
3352                         llapi_layout_free(head);
3353                         return -EINVAL;
3354                 }
3355
3356                 rc = llapi_layout_comp_extent_get(head, &start, &prev_end);
3357                 if (rc) {
3358                         fprintf(stderr,
3359                                 "%s setstripe: cannot get prev extent: %s\n",
3360                                 progname, strerror(errno));
3361                         llapi_layout_free(head);
3362                         return rc;
3363                 }
3364
3365                 llapi_layout_free(head);
3366                 break;
3367         }
3368
3369         /* Make sure we use the first component of the layout to be added. */
3370         rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_FIRST);
3371         if (rc < 0) {
3372                 fprintf(stderr,
3373                         "%s setstripe: cannot move component cursor: %s\n",
3374                         progname, strerror(errno));
3375                 return rc;
3376         }
3377
3378         rc = llapi_layout_comp_extent_get(layout, &start, &end);
3379         if (rc) {
3380                 fprintf(stderr, "%s setstripe: cannot get extent: %s\n",
3381                         progname, strerror(errno));
3382                 return rc;
3383         }
3384
3385         if (start == 0 && end == 0) {
3386                 rc = layout_extend_comp(layout, start, &end,
3387                                         comp_add ? prev_end : 0);
3388                 if (rc)
3389                         return rc;
3390         }
3391
3392         if (start > prev_end || end < prev_end) {
3393                 fprintf(stderr,
3394                         "%s setstripe: first extent [%lu, %lu) not adjacent with extent end %lu\n",
3395                         progname, start, end, prev_end);
3396                 return -EINVAL;
3397         }
3398
3399         rc = llapi_layout_comp_extent_set(layout, prev_end, end);
3400         if (rc) {
3401                 fprintf(stderr,
3402                         "%s setstripe: cannot set component extent [%lu, %lu): %s\n",
3403                         progname, prev_end, end, strerror(errno));
3404                 return rc;
3405         }
3406
3407         return ret;
3408 }
3409
3410 static int mirror_adjust_first_extents(struct mirror_args *list)
3411 {
3412         int rc = 0;
3413
3414         if (!list)
3415                 return 0;
3416
3417         while (list) {
3418                 rc = layout_adjust_first_extent(NULL, list->m_layout, false);
3419                 if (rc)
3420                         break;
3421                 list = list->m_next;
3422         }
3423
3424         return rc;
3425 }
3426
3427 static inline bool arg_is_eof(char *arg)
3428 {
3429         return !strncmp(arg, "-1", strlen("-1")) ||
3430                !strncmp(arg, "EOF", strlen("EOF")) ||
3431                !strncmp(arg, "eof", strlen("eof"));
3432 }
3433
3434 /**
3435  * lfs_mirror_alloc() - Allocate a mirror argument structure.
3436  *
3437  * Return: Valid mirror_args pointer on success and
3438  *         NULL if memory allocation fails.
3439  */
3440 static struct mirror_args *lfs_mirror_alloc(void)
3441 {
3442         struct mirror_args *mirror = NULL;
3443
3444         while (1) {
3445                 mirror = calloc(1, sizeof(*mirror));
3446                 if (mirror) {
3447                         mirror->m_inherit = false;
3448                         break;
3449                 }
3450
3451                 sleep(1);
3452         }
3453
3454         return mirror;
3455 }
3456
3457 /**
3458  * lfs_mirror_free() - Free memory allocated for a mirror argument
3459  *                     structure.
3460  * @mirror: Previously allocated mirror argument structure by
3461  *          lfs_mirror_alloc().
3462  *
3463  * Free memory allocated for @mirror.
3464  *
3465  * Return: void.
3466  */
3467 static void lfs_mirror_free(struct mirror_args *mirror)
3468 {
3469         if (mirror->m_layout)
3470                 llapi_layout_free(mirror->m_layout);
3471         free(mirror);
3472 }
3473
3474 /**
3475  * lfs_mirror_list_free() - Free memory allocated for a mirror list.
3476  * @mirror_list: Previously allocated mirror list.
3477  *
3478  * Free memory allocated for @mirror_list.
3479  *
3480  * Return: void.
3481  */
3482 static void lfs_mirror_list_free(struct mirror_args *mirror_list)
3483 {
3484         struct mirror_args *next_mirror = NULL;
3485
3486         while (mirror_list) {
3487                 next_mirror = mirror_list->m_next;
3488                 lfs_mirror_free(mirror_list);
3489                 mirror_list = next_mirror;
3490         }
3491 }
3492
3493 enum {
3494         LFS_SETQUOTA_DELETE = 1,
3495         LFS_POOL_OPT = 3,
3496         LFS_COMP_COUNT_OPT,
3497         LFS_COMP_START_OPT,
3498         LFS_COMP_FLAGS_OPT,
3499         LFS_COMP_DEL_OPT,
3500         LFS_COMP_SET_OPT,
3501         LFS_COMP_ADD_OPT,
3502         LFS_COMP_NO_VERIFY_OPT,
3503         LFS_PROJID_OPT,
3504         LFS_LAYOUT_FLAGS_OPT, /* used for mirror and foreign flags */
3505         LFS_MIRROR_ID_OPT,
3506         LFS_MIRROR_STATE_OPT,
3507         LFS_LAYOUT_COPY,
3508         LFS_MIRROR_INDEX_OPT,
3509         LFS_LAYOUT_FOREIGN_OPT,
3510         LFS_MODE_OPT,
3511         LFS_NEWERXY_OPT,
3512         LFS_INHERIT_RR_OPT,
3513         LFS_FIND_PERM,
3514         LFS_PRINTF_OPT,
3515         LFS_NO_FOLLOW_OPT,
3516         LFS_STATS_OPT,
3517         LFS_STATS_INTERVAL_OPT
3518 };
3519
3520 #ifndef LCME_USER_MIRROR_FLAGS
3521 /* The mirror flags can be set by users at creation time. */
3522 #define LCME_USER_MIRROR_FLAGS  (LCME_FL_PREF_RW)
3523 #endif
3524
3525 /* functions */
3526 static int lfs_setstripe_internal(int argc, char **argv,
3527                                   enum setstripe_origin opc)
3528 {
3529         struct lfs_setstripe_args        lsa = { 0 };
3530         struct llapi_stripe_param       *param = NULL;
3531         struct find_param                migrate_mdt_param = {
3532                 .fp_max_depth = -1,
3533                 .fp_mdt_index = -1,
3534         };
3535         char                            *fname;
3536         int                              result = 0;
3537         int                              result2 = 0;
3538         char                            *end;
3539         int                              c;
3540         int                              delete = 0;
3541         unsigned long long               size_units = 1;
3542         bool                             migrate_mode = false;
3543         bool                             migrate_mdt_mode = false;
3544         bool                             setstripe_mode = false;
3545         bool                             migration_block = false;
3546         __u64                            migration_flags = 0;
3547         __u32                            tgts[LOV_MAX_STRIPE_COUNT] = { 0 };
3548         int                              comp_del = 0, comp_set = 0;
3549         int                              comp_add = 0;
3550         __u32                            comp_id = 0;
3551         struct llapi_layout             *layout = NULL;
3552         struct llapi_layout             **lpp = &layout;
3553         bool                             mirror_mode = false;
3554         bool                             has_m_file = false;
3555         __u32                            mirror_count = 0;
3556         enum mirror_flags                mirror_flags = 0;
3557         struct mirror_args              *mirror_list = NULL;
3558         struct mirror_args              *new_mirror = NULL;
3559         struct mirror_args              *last_mirror = NULL;
3560         __u16                            mirror_id = 0;
3561         char                             cmd[PATH_MAX];
3562         bool from_yaml = false;
3563         bool from_copy = false;
3564         char *template = NULL;
3565         bool foreign_mode = false;
3566         char *xattr = NULL;
3567         uint32_t type = LU_FOREIGN_TYPE_NONE, flags = 0;
3568         char *mode_opt = NULL;
3569         mode_t previous_umask = 0;
3570         mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
3571         unsigned long long bandwidth_bytes_sec = 0;
3572         unsigned long long bandwidth_unit = ONE_MB;
3573         enum stats_flag stats_flag = STATS_OFF;
3574         long stats_interval_sec = 5;
3575
3576         struct option long_opts[] = {
3577 /* find { .val = '0',   .name = "null",         .has_arg = no_argument }, */
3578 /* find { .val = 'A',   .name = "atime",        .has_arg = required_argument }*/
3579         /* --block is only valid in migrate mode */
3580         { .val = 'b',   .name = "block",        .has_arg = no_argument },
3581 /* find { .val = 'B',   .name = "btime",        .has_arg = required_argument }*/
3582         { .val = LFS_COMP_ADD_OPT,
3583                         .name = "comp-add",     .has_arg = no_argument },
3584         { .val = LFS_COMP_ADD_OPT,
3585                         .name = "component-add", .has_arg = no_argument },
3586         { .val = LFS_COMP_DEL_OPT,
3587                         .name = "comp-del",     .has_arg = no_argument },
3588         { .val = LFS_COMP_DEL_OPT,
3589                         .name = "component-del", .has_arg = no_argument },
3590         { .val = LFS_COMP_FLAGS_OPT,
3591                         .name = "comp-flags",   .has_arg = required_argument },
3592         { .val = LFS_COMP_FLAGS_OPT,
3593                         .name = "component-flags",
3594                                                 .has_arg = required_argument },
3595         { .val = LFS_COMP_SET_OPT,
3596                         .name = "comp-set",     .has_arg = no_argument },
3597         { .val = LFS_COMP_SET_OPT,
3598                         .name = "component-set",
3599                                                 .has_arg = no_argument},
3600         { .val = LFS_COMP_NO_VERIFY_OPT,
3601                         .name = "no-verify",    .has_arg = no_argument},
3602         { .val = LFS_LAYOUT_FLAGS_OPT,
3603                         .name = "flags",        .has_arg = required_argument},
3604         { .val = LFS_LAYOUT_FOREIGN_OPT,
3605                         .name = "foreign",      .has_arg = optional_argument},
3606         { .val = LFS_MIRROR_ID_OPT,
3607                         .name = "mirror-id",    .has_arg = required_argument},
3608         { .val = LFS_MODE_OPT,
3609                         .name = "mode",         .has_arg = required_argument},
3610         { .val = LFS_LAYOUT_COPY,
3611                         .name = "copy",         .has_arg = required_argument},
3612         { .val = LFS_STATS_OPT,
3613                         .name = "stats",        .has_arg = no_argument},
3614         { .val = LFS_STATS_INTERVAL_OPT,
3615                         .name = "stats-interval",
3616                                                 .has_arg = required_argument},
3617         { .val = 'c',   .name = "stripe-count", .has_arg = required_argument},
3618         { .val = 'c',   .name = "stripe_count", .has_arg = required_argument},
3619         { .val = 'c',   .name = "mdt-count",    .has_arg = required_argument},
3620         { .val = 'C',   .name = "overstripe-count",
3621                                                 .has_arg = required_argument},
3622         { .val = 'd',   .name = "delete",       .has_arg = no_argument},
3623         { .val = 'd',   .name = "destroy",      .has_arg = no_argument},
3624         /* used with "lfs migrate -m" */
3625         { .val = 'd',   .name = "directory",    .has_arg = no_argument},
3626         /* --non-direct is only valid in migrate mode */
3627         { .val = 'D',   .name = "non-direct",   .has_arg = no_argument },
3628         { .val = 'E',   .name = "comp-end",     .has_arg = required_argument},
3629         { .val = 'E',   .name = "component-end",
3630                                                 .has_arg = required_argument},
3631         { .val = 'f',   .name = "file",         .has_arg = required_argument },
3632 /* find { .val = 'F',   .name = "fid",          .has_arg = no_argument }, */
3633 /* find { .val = 'g',   .name = "gid",          .has_arg = no_argument }, */
3634 /* find { .val = 'G',   .name = "group",        .has_arg = required_argument }*/
3635         { .val = 'h',   .name = "help",         .has_arg = no_argument },
3636         { .val = 'H',   .name = "mdt-hash",     .has_arg = required_argument},
3637         { .val = 'i',   .name = "stripe-index", .has_arg = required_argument},
3638         { .val = 'i',   .name = "stripe_index", .has_arg = required_argument},
3639         { .val = 'I',   .name = "comp-id",      .has_arg = required_argument},
3640         { .val = 'I',   .name = "component-id", .has_arg = required_argument},
3641 /* find { .val = 'l',   .name = "lazy",         .has_arg = no_argument }, */
3642         { .val = 'L',   .name = "layout",       .has_arg = required_argument },
3643         { .val = 'm',   .name = "mdt",          .has_arg = required_argument},
3644         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument},
3645         { .val = 'm',   .name = "mdt_index",    .has_arg = required_argument},
3646         /* --non-block is only valid in migrate mode */
3647         { .val = 'n',   .name = "non-block",    .has_arg = no_argument },
3648         { .val = 'N',   .name = "mirror-count", .has_arg = optional_argument},
3649         { .val = 'o',   .name = "ost",          .has_arg = required_argument },
3650 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
3651         { .val = 'o',   .name = "ost-list",     .has_arg = required_argument },
3652         { .val = 'o',   .name = "ost_list",     .has_arg = required_argument },
3653 #endif
3654         { .val = 'p',   .name = "pool",         .has_arg = required_argument },
3655 /* find { .val = 'P',   .name = "print",        .has_arg = no_argument }, */
3656 /* getstripe { .val = 'q', .name = "quiet",     .has_arg = no_argument }, */
3657 /* getstripe { .val = 'R', .name = "raw",       .has_arg = no_argument }, */
3658         { .val = 'S',   .name = "stripe-size",  .has_arg = required_argument },
3659         { .val = 'S',   .name = "stripe_size",  .has_arg = required_argument },
3660 /* find { .val = 't',   .name = "type",         .has_arg = required_argument }*/
3661 /* dirstripe { .val = 'T', .name = "mdt-count", .has_arg = required_argument }*/
3662 /* find { .val = 'u',   .name = "uid",          .has_arg = required_argument }*/
3663 /* find { .val = 'U',   .name = "user",         .has_arg = required_argument }*/
3664         /* --verbose is only valid in migrate mode */
3665         { .val = 'v',   .name = "verbose",      .has_arg = no_argument},
3666         { .val = 'W',   .name = "bandwidth",    .has_arg = required_argument },
3667         { .val = 'x',   .name = "xattr",        .has_arg = required_argument },
3668 /* dirstripe { .val = 'X',.name = "max-inherit",.has_arg = required_argument }*/
3669         { .val = 'y',   .name = "yaml",         .has_arg = required_argument },
3670         { .val = 'z',   .name = "ext-size",     .has_arg = required_argument},
3671         { .val = 'z',   .name = "extension-size", .has_arg = required_argument},
3672         { .name = NULL } };
3673
3674         setstripe_args_init(&lsa);
3675
3676         migrate_mode = (opc == SO_MIGRATE);
3677         mirror_mode = (opc == SO_MIRROR_CREATE || opc == SO_MIRROR_EXTEND);
3678         setstripe_mode = (opc == SO_SETSTRIPE);
3679         if (opc == SO_MIRROR_DELETE) {
3680                 delete = 1;
3681                 mirror_flags = MF_DESTROY;
3682         }
3683
3684         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
3685         progname = cmd;
3686         while ((c = getopt_long(argc, argv,
3687                                 "bc:C:dDE:f:hH:i:I:m:N::no:p:L:s:S:vx:W:y:z:",
3688                                 long_opts, NULL)) >= 0) {
3689                 size_units = 1;
3690                 switch (c) {
3691                 case 0:
3692                         /* Long options. */
3693                         break;
3694                 case LFS_COMP_ADD_OPT:
3695                         comp_add = 1;
3696                         break;
3697                 case LFS_COMP_DEL_OPT:
3698                         comp_del = 1;
3699                         break;
3700                 case LFS_COMP_FLAGS_OPT:
3701                         result = comp_str2flags(optarg, &lsa.lsa_comp_flags,
3702                                                 &lsa.lsa_comp_neg_flags);
3703                         if (result != 0)
3704                                 goto usage_error;
3705                         if (mirror_mode && lsa.lsa_comp_neg_flags) {
3706                                 fprintf(stderr,
3707                                         "%s: inverted flags are not supported\n",
3708                                         progname);
3709                                 goto usage_error;
3710                         }
3711                         break;
3712                 case LFS_COMP_SET_OPT:
3713                         comp_set = 1;
3714                         break;
3715                 case LFS_COMP_NO_VERIFY_OPT:
3716                         mirror_flags |= MF_NO_VERIFY;
3717                         break;
3718                 case LFS_MIRROR_ID_OPT: {
3719                         unsigned long int id;
3720
3721                         errno = 0;
3722                         id = strtoul(optarg, &end, 0);
3723                         if (errno != 0 || *end != '\0' || id == 0 ||
3724                             id > UINT16_MAX) {
3725                                 fprintf(stderr,
3726                                         "%s %s: invalid mirror ID '%s'\n",
3727                                         progname, argv[0], optarg);
3728                                 goto usage_error;
3729                         }
3730
3731                         mirror_id = (__u16)id;
3732                         break;
3733                 }
3734                 case LFS_LAYOUT_FLAGS_OPT: {
3735                         uint32_t neg_flags;
3736
3737                         /* check for numeric flags (foreign and mirror cases) */
3738                         if (setstripe_mode && !mirror_mode && !last_mirror) {
3739                                 errno = 0;
3740                                 flags = strtoul(optarg, &end, 16);
3741                                 if (errno != 0 || *end != '\0' ||
3742                                     flags >= UINT32_MAX) {
3743                                         fprintf(stderr,
3744                                                 "%s %s: invalid hex flags '%s'\n",
3745                                                 progname, argv[0], optarg);
3746                                         return CMD_HELP;
3747                                 }
3748                                 if (!foreign_mode) {
3749                                         fprintf(stderr,
3750                                                 "%s %s: hex flags must be specified with --foreign option\n",
3751                                                 progname, argv[0]);
3752                                         return CMD_HELP;
3753                                 }
3754                                 break;
3755                         }
3756
3757                         if (!mirror_mode || !last_mirror) {
3758                                 fprintf(stderr,
3759                                         "error: %s: --flags must be specified with --mirror-count|-N option\n",
3760                                         progname);
3761                                 goto usage_error;
3762                         }
3763
3764                         result = comp_str2flags(optarg, &last_mirror->m_flags,
3765                                                 &neg_flags);
3766                         if (result != 0)
3767                                 goto usage_error;
3768
3769                         if (neg_flags) {
3770                                 fprintf(stderr,
3771                                         "%s: inverted flags are not supported\n",
3772                                         progname);
3773                                 result = -EINVAL;
3774                                 goto usage_error;
3775                         }
3776                         if (last_mirror->m_flags & ~LCME_USER_MIRROR_FLAGS) {
3777                                 fprintf(stderr,
3778                                         "%s: unsupported mirror flags: %s\n",
3779                                         progname, optarg);
3780                                 result = -EINVAL;
3781                                 goto error;
3782                         }
3783                         break;
3784                 }
3785                 case LFS_LAYOUT_FOREIGN_OPT:
3786                         if (optarg) {
3787                                 /* check pure numeric */
3788                                 type = strtoul(optarg, &end, 0);
3789                                 if (*end) {
3790                                         /* check name */
3791                                         type = check_foreign_type_name(optarg);
3792                                         if (type == LU_FOREIGN_TYPE_UNKNOWN) {
3793                                                 fprintf(stderr,
3794                                                         "%s %s: unrecognized foreign type '%s'\n",
3795                                                         progname, argv[0],
3796                                                         optarg);
3797                                                 return CMD_HELP;
3798                                         }
3799                                 } else if (type >= UINT32_MAX) {
3800                                         fprintf(stderr,
3801                                                 "%s %s: invalid foreign type '%s'\n",
3802                                                 progname, argv[0], optarg);
3803                                         return CMD_HELP;
3804                                 }
3805                         }
3806                         foreign_mode = true;
3807                         break;
3808                 case LFS_MODE_OPT:
3809                         mode_opt = optarg;
3810                         if (mode_opt) {
3811                                 mode = strtoul(mode_opt, &end, 8);
3812                                 if (*end != '\0') {
3813                                         fprintf(stderr,
3814                                                 "%s %s: bad mode '%s'\n",
3815                                                 progname, argv[0], mode_opt);
3816                                         return CMD_HELP;
3817                                 }
3818                                 previous_umask = umask(0);
3819                         }
3820                         break;
3821                 case LFS_LAYOUT_COPY:
3822                         from_copy = true;
3823                         template = optarg;
3824                         break;
3825                 case LFS_STATS_OPT:
3826                         stats_flag = STATS_ON;
3827                         break;
3828                 case LFS_STATS_INTERVAL_OPT:
3829                         stats_interval_sec = strtol(optarg, &end, 0);
3830                         if (stats_interval_sec == 0)
3831                                 stats_interval_sec = 5;
3832                         break;
3833                 case 'b':
3834                         if (!migrate_mode) {
3835                                 fprintf(stderr,
3836                                         "%s %s: -b|--block valid only for migrate command\n",
3837                                         progname, argv[0]);
3838                                 goto usage_error;
3839                         }
3840                         migration_block = true;
3841                         break;
3842                 case 'C':
3843                         if (lsa.lsa_pattern == LLAPI_LAYOUT_MDT) {
3844                                 fprintf(stderr,
3845                                         "%s %s: -C|--overstripe-count incompatible with DoM layout\n",
3846                                         progname, argv[0]);
3847                                 goto usage_error;
3848                         }
3849                         lsa.lsa_pattern = LLAPI_LAYOUT_OVERSTRIPING;
3850                         fallthrough;
3851                 case 'c':
3852                         errno = 0;
3853                         lsa.lsa_stripe_count = strtoul(optarg, &end, 0);
3854                         if (errno != 0 || *end != '\0'|| optarg == end ||
3855                             lsa.lsa_stripe_count < -1 ||
3856                             lsa.lsa_stripe_count > LOV_MAX_STRIPE_COUNT) {
3857                                 fprintf(stderr,
3858                                         "%s %s: invalid stripe count '%s'\n",
3859                                         progname, argv[0], optarg);
3860                                 goto usage_error;
3861                         }
3862
3863                         if (lsa.lsa_stripe_count == -1)
3864                                 lsa.lsa_stripe_count = LLAPI_LAYOUT_WIDE;
3865                         break;
3866                 case 'd':
3867                         if (migrate_mode) {
3868                                 migrate_mdt_param.fp_max_depth = 1;
3869                         } else {
3870                                 /* delete the default striping pattern */
3871                                 delete = 1;
3872                                 if (opc == SO_MIRROR_SPLIT) {
3873                                         if (has_m_file) {
3874                                                 fprintf(stderr,
3875                                                       "%s %s: -d cannot used with -f\n",
3876                                                         progname, argv[0]);
3877                                                 goto usage_error;
3878                                         }
3879                                         mirror_flags |= MF_DESTROY;
3880                                 }
3881                         }
3882                         break;
3883                 case 'D':
3884                         if (!migrate_mode) {
3885                                 fprintf(stderr,
3886                                         "%s %s: -D|--non-direct is valid only for migrate command\n",
3887                                         progname, argv[0]);
3888                                 goto usage_error;
3889                         }
3890                         migration_flags |= LLAPI_MIGRATION_NONDIRECT;
3891                         break;
3892                 case 'E':
3893                         if (lsa.lsa_comp_end != 0) {
3894                                 result = comp_args_to_layout(lpp, &lsa, true);
3895                                 if (result) {
3896                                         fprintf(stderr, "%s: invalid layout\n",
3897                                                 progname);
3898                                         goto usage_error;
3899                                 }
3900
3901                                 setstripe_args_init_inherit(&lsa);
3902                         }
3903
3904                         if (arg_is_eof(optarg)) {
3905                                 lsa.lsa_comp_end = LUSTRE_EOF;
3906                         } else {
3907                                 result = llapi_parse_size(optarg,
3908                                                           &lsa.lsa_comp_end,
3909                                                           &size_units, 0);
3910                                 /* assume units of KB if too small */
3911                                 if (lsa.lsa_comp_end < 4096)
3912                                         lsa.lsa_comp_end *= 1024;
3913                                 if (result ||
3914                                     lsa.lsa_comp_end & (LOV_MIN_STRIPE_SIZE - 1)) {
3915                                         fprintf(stderr,
3916                                                 "%s %s: invalid component end '%s'\n",
3917                                                 progname, argv[0], optarg);
3918                                         goto usage_error;
3919                                 }
3920                         }
3921                         break;
3922                 case 'H':
3923                         if (!migrate_mode) {
3924                                 fprintf(stderr,
3925                                         "--mdt-hash is valid only for migrate command\n");
3926                                 return CMD_HELP;
3927                         }
3928
3929                         lsa.lsa_pattern = check_hashtype(optarg);
3930                         if (lsa.lsa_pattern == 0) {
3931                                 fprintf(stderr,
3932                                         "%s %s: bad stripe hash type '%s'\n",
3933                                         progname, argv[0], optarg);
3934                                 return CMD_HELP;
3935                         }
3936                         break;
3937                 case 'i':
3938                         errno = 0;
3939                         lsa.lsa_stripe_off = strtol(optarg, &end, 0);
3940                         if (errno != 0 || *end != '\0' || optarg == end ||
3941                             lsa.lsa_stripe_off < -1 ||
3942                             lsa.lsa_stripe_off > LOV_V1_INSANE_STRIPE_COUNT) {
3943                                 fprintf(stderr,
3944                                         "%s %s: invalid stripe offset '%s'\n",
3945                                         progname, argv[0], optarg);
3946                                 goto usage_error;
3947                         }
3948                         if (lsa.lsa_stripe_off == -1)
3949                                 lsa.lsa_stripe_off = LLAPI_LAYOUT_DEFAULT;
3950                         break;
3951                 case 'I':
3952                         comp_id = strtoul(optarg, &end, 0);
3953                         if (*end != '\0' || comp_id == 0 ||
3954                             comp_id > LCME_ID_MAX) {
3955                                 fprintf(stderr,
3956                                         "%s %s: invalid component ID '%s'\n",
3957                                         progname, argv[0], optarg);
3958                                 goto usage_error;
3959                         }
3960                         break;
3961                 case 'f':
3962                         if (opc != SO_MIRROR_EXTEND && opc != SO_MIRROR_SPLIT) {
3963                                 fprintf(stderr,
3964                                         "error: %s: invalid option: %s\n",
3965                                         progname, argv[optopt + 1]);
3966                                 goto usage_error;
3967                         }
3968                         if (opc == SO_MIRROR_EXTEND) {
3969                                 if (!last_mirror) {
3970                                         fprintf(stderr,
3971                                 "error: %s: '-N' must exist in front of '%s'\n",
3972                                                 progname, argv[optopt + 1]);
3973                                         goto usage_error;
3974                                 }
3975                                 last_mirror->m_file = optarg;
3976                                 last_mirror->m_count = 1;
3977                         } else {
3978                                 /* mirror split */
3979                                 if (!mirror_list)
3980                                         mirror_list = lfs_mirror_alloc();
3981                                 mirror_list->m_file = optarg;
3982                         }
3983                         has_m_file = true;
3984                         break;
3985                 case 'L':
3986                         if (strcmp(argv[optind - 1], "mdt") == 0) {
3987                                 /* Can be only the first component */
3988                                 if (layout) {
3989                                         result = -EINVAL;
3990                                         fprintf(stderr,
3991                                                 "error: 'mdt' layout can be only the first one\n");
3992                                         goto error;
3993                                 }
3994                                 if (lsa.lsa_comp_end > (1ULL << 30)) { /* 1Gb */
3995                                         result = -EFBIG;
3996                                         fprintf(stderr,
3997                                                 "error: 'mdt' layout size is too big\n");
3998                                         goto error;
3999                                 }
4000                                 lsa.lsa_pattern = LLAPI_LAYOUT_MDT;
4001                                 lsa.lsa_stripe_size = LLAPI_LAYOUT_DEFAULT;
4002                         } else if (strcmp(argv[optind - 1], "raid0") != 0) {
4003                                 result = -EINVAL;
4004                                 fprintf(stderr,
4005                                         "error: layout '%s' is unknown, supported layouts are: 'mdt', 'raid0'\n",
4006                                         argv[optind]);
4007                                 goto error;
4008                         }
4009                         break;
4010                 case 'm':
4011                         if (!migrate_mode) {
4012                                 fprintf(stderr,
4013                                         "%s %s: -m|--mdt-index is valid only for migrate command\n",
4014                                         progname, argv[0]);
4015                                 goto usage_error;
4016                         }
4017                         migrate_mdt_mode = true;
4018                         lsa.lsa_nr_tgts = parse_targets(tgts,
4019                                                 sizeof(tgts) / sizeof(__u32),
4020                                                 lsa.lsa_nr_tgts, optarg, NULL);
4021                         if (lsa.lsa_nr_tgts < 0) {
4022                                 fprintf(stderr,
4023                                         "%s: invalid MDT target(s) '%s'\n",
4024                                         progname, optarg);
4025                                 goto usage_error;
4026                         }
4027
4028                         lsa.lsa_tgts = tgts;
4029                         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
4030                                 lsa.lsa_stripe_off = tgts[0];
4031                         break;
4032                 case 'n':
4033                         if (!migrate_mode) {
4034                                 fprintf(stderr,
4035                                         "%s %s: -n|--non-block valid only for migrate command\n",
4036                                         progname, argv[0]);
4037                                 goto usage_error;
4038                         }
4039                         migration_flags |= LLAPI_MIGRATION_NONBLOCK;
4040                         break;
4041                 case 'N':
4042                         if (opc == SO_SETSTRIPE) {
4043                                 opc = SO_MIRROR_CREATE;
4044                                 mirror_mode = true;
4045                         }
4046                         mirror_count = 1;
4047                         if (optarg) {
4048                                 errno = 0;
4049                                 mirror_count = strtoul(optarg, &end, 0);
4050                                 if (errno != 0 || *end != '\0' ||
4051                                     mirror_count == 0 ||
4052                                     mirror_count > LUSTRE_MIRROR_COUNT_MAX) {
4053                                         fprintf(stderr,
4054                                                 "error: %s: bad mirror count: %s\n",
4055                                                 progname, optarg);
4056                                         result = -EINVAL;
4057                                         goto error;
4058                                 }
4059                         }
4060
4061                         new_mirror = lfs_mirror_alloc();
4062                         new_mirror->m_count = mirror_count;
4063
4064                         if (!mirror_list)
4065                                 mirror_list = new_mirror;
4066
4067                         if (last_mirror) {
4068                                 /* wrap up last mirror */
4069                                 if (!setstripe_args_specified(&lsa))
4070                                         last_mirror->m_inherit = true;
4071                                 if (lsa.lsa_comp_end == 0)
4072                                         lsa.lsa_comp_end = LUSTRE_EOF;
4073
4074                                 result = comp_args_to_layout(lpp, &lsa, true);
4075                                 if (result) {
4076                                         lfs_mirror_free(new_mirror);
4077                                         goto error;
4078                                 }
4079
4080                                 setstripe_args_init_inherit(&lsa);
4081
4082                                 last_mirror->m_next = new_mirror;
4083                         }
4084
4085                         last_mirror = new_mirror;
4086                         lpp = &last_mirror->m_layout;
4087                         break;
4088                 case 'o':
4089 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
4090                         if (strcmp(argv[optind - 1], "--ost-list") == 0)
4091                                 fprintf(stderr,
4092                                         "warning: '--ost-list' is deprecated, use '--ost' instead\n");
4093 #endif
4094                         if (lsa.lsa_pattern == LLAPI_LAYOUT_MDT) {
4095                                 fprintf(stderr,
4096                                         "%s %s: -o|--ost incompatible with DoM layout\n",
4097                                         progname, argv[0]);
4098                                 goto usage_error;
4099                         }
4100                         /*
4101                          * -o allows overstriping, and must note it because
4102                          * parse_targets is shared with MDT striping, which
4103                          * does not allow duplicates
4104                          */
4105                         lsa.lsa_pattern = LLAPI_LAYOUT_OVERSTRIPING;
4106                         lsa.lsa_nr_tgts = parse_targets(tgts,
4107                                                 sizeof(tgts) / sizeof(__u32),
4108                                                 lsa.lsa_nr_tgts, optarg,
4109                                                 &lsa.lsa_pattern);
4110                         if (lsa.lsa_nr_tgts < 0) {
4111                                 fprintf(stderr,
4112                                         "%s %s: invalid OST target(s) '%s'\n",
4113                                         progname, argv[0], optarg);
4114                                 goto usage_error;
4115                         }
4116
4117                         lsa.lsa_tgts = tgts;
4118                         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
4119                                 lsa.lsa_stripe_off = tgts[0];
4120                         break;
4121                 case 'p':
4122                         if (!optarg)
4123                                 goto usage_error;
4124
4125                         if (optarg[0] == '\0' || lov_pool_is_inherited(optarg))
4126                                 lsa.lsa_pool_name = NULL;
4127                         else
4128                                 lsa.lsa_pool_name = optarg;
4129                         break;
4130                 case 'S':
4131                         result = llapi_parse_size(optarg, &lsa.lsa_stripe_size,
4132                                                   &size_units, 0);
4133                         /* assume units of KB if too small to be valid */
4134                         if (lsa.lsa_stripe_size < 4096)
4135                                 lsa.lsa_stripe_size *= 1024;
4136                         if (result ||
4137                             lsa.lsa_stripe_size & (LOV_MIN_STRIPE_SIZE - 1)) {
4138                                 fprintf(stderr,
4139                                         "%s %s: invalid stripe size '%s'\n",
4140                                         progname, argv[0], optarg);
4141                                 goto usage_error;
4142                         }
4143                         break;
4144                 case 'v':
4145                         if (!migrate_mode) {
4146                                 fprintf(stderr,
4147                                         "%s %s: -v|--verbose valid only for migrate command\n",
4148                                         progname, argv[0]);
4149                                 goto usage_error;
4150                         }
4151                         migrate_mdt_param.fp_verbose = VERBOSE_DETAIL;
4152                         migration_flags = LLAPI_MIGRATION_VERBOSE;
4153                         break;
4154                 case 'x':
4155                         xattr = optarg;
4156                         break;
4157                 case 'W':
4158                         if (!migrate_mode) {
4159                                 fprintf(stderr,
4160                                         "--bandwidth is valid only for migrate and mirror mode\n");
4161                                 goto error;
4162                         }
4163                         if (llapi_parse_size(optarg, &bandwidth_bytes_sec,
4164                                              &bandwidth_unit, 0) < 0) {
4165                                 fprintf(stderr,
4166                                         "error: %s: bad value for bandwidth '%s'\n",
4167                                         argv[0], optarg);
4168                                 goto error;
4169                         }
4170                         break;
4171                 case 'y':
4172                         from_yaml = true;
4173                         template = optarg;
4174                         break;
4175                 case 'z':
4176                         result = llapi_parse_size(optarg,
4177                                                   &lsa.lsa_extension_size,
4178                                                   &size_units, 0);
4179                         if (result) {
4180                                 fprintf(stderr,
4181                                         "%s %s: invalid extension size '%s'\n",
4182                                         progname, argv[0], optarg);
4183                                 goto usage_error;
4184                         }
4185
4186                         lsa.lsa_extension_comp = true;
4187                         break;
4188                 default:
4189                         fprintf(stderr, "%s: unrecognized option '%s'\n",
4190                                 progname, argv[optind - 1]);
4191                 case 'h':
4192                         goto usage_error;
4193                 }
4194         }
4195
4196         fname = argv[optind];
4197
4198         if (optind == argc) {
4199                 fprintf(stderr, "%s %s: FILE must be specified\n",
4200                         progname, argv[0]);
4201                 goto usage_error;
4202         }
4203
4204         /* lfs migrate $filename should keep the file's layout by default */
4205         if (migrate_mode && !layout && !from_yaml &&
4206             !setstripe_args_specified(&lsa) && !lsa.lsa_pool_name)
4207                 from_copy = true;
4208
4209         if (xattr && !foreign_mode) {
4210                 /*
4211                  * only print a warning as this is harmless and will be ignored
4212                  */
4213                 fprintf(stderr,
4214                         "%s %s: xattr has been specified for non-foreign layout\n",
4215                         progname, argv[0]);
4216         } else if (foreign_mode && !xattr) {
4217                 fprintf(stderr,
4218                         "%s %s: xattr must be provided in foreign mode\n",
4219                         progname, argv[0]);
4220                 goto usage_error;
4221         }
4222
4223         if (foreign_mode && (!setstripe_mode || comp_add | comp_del ||
4224             comp_set || comp_id || delete || from_copy ||
4225             setstripe_args_specified(&lsa) || lsa.lsa_nr_tgts ||
4226             lsa.lsa_tgts)) {
4227                 fprintf(stderr,
4228                         "%s %s: only --xattr/--flags/--mode options are valid with --foreign\n",
4229                         progname, argv[0]);
4230                 return CMD_HELP;
4231         }
4232
4233         if (mirror_mode && mirror_count == 0) {
4234                 fprintf(stderr,
4235                         "error: %s: --mirror-count|-N option is required\n",
4236                         progname);
4237                 result = -EINVAL;
4238                 goto error;
4239         }
4240
4241         if (mirror_mode) {
4242                 if (!setstripe_args_specified(&lsa))
4243                         last_mirror->m_inherit = true;
4244                 if (lsa.lsa_comp_end == 0)
4245                         lsa.lsa_comp_end = LUSTRE_EOF;
4246         }
4247
4248         if (lsa.lsa_comp_end != 0) {
4249                 result = comp_args_to_layout(lpp, &lsa, true);
4250                 if (result) {
4251                         fprintf(stderr, "error: %s: invalid layout\n",
4252                                 progname);
4253                         result = -EINVAL;
4254                         goto error;
4255                 }
4256         }
4257
4258         if (mirror_flags & MF_NO_VERIFY) {
4259                 if (opc != SO_MIRROR_EXTEND) {
4260                         fprintf(stderr,
4261                                 "error: %s: --no-verify is valid only for lfs mirror extend command\n",
4262                                 progname);
4263                         result = -EINVAL;
4264                         goto error;
4265                 } else if (!has_m_file) {
4266                         fprintf(stderr,
4267                                 "error: %s: --no-verify must be specified with -f <victim_file> option\n",
4268                                 progname);
4269                         result = -EINVAL;
4270                         goto error;
4271                 }
4272         }
4273
4274         if (comp_set && !comp_id && !lsa.lsa_pool_name) {
4275                 fprintf(stderr,
4276                         "%s %s: --component-set doesn't have component-id set\n",
4277                         progname, argv[0]);
4278                 goto usage_error;
4279         }
4280
4281         if ((delete + comp_set + comp_del + comp_add) > 1) {
4282                 fprintf(stderr,
4283                         "%s %s: options --component-set, --component-del, --component-add and -d are mutually exclusive\n",
4284                         progname, argv[0]);
4285                 goto usage_error;
4286         }
4287
4288         if (delete && (setstripe_args_specified(&lsa) || comp_id != 0 ||
4289                        lsa.lsa_comp_flags != 0 || layout != NULL)) {
4290                 fprintf(stderr,
4291                         "%s %s: option -d is mutually exclusive with -s, -c, -o, -p, -I, -F and -E options\n",
4292                         progname, argv[0]);
4293                 goto usage_error;
4294         }
4295
4296         if ((comp_set || comp_del) &&
4297             (setstripe_args_specified(&lsa) || layout != NULL)) {
4298                 fprintf(stderr,
4299                         "%s %s: options --component-del and --component-set are mutually exclusive when used with -c, -E, -o, -p, or -s\n",
4300                         progname, argv[0]);
4301                 goto usage_error;
4302         }
4303
4304         if (comp_del && comp_id != 0 && lsa.lsa_comp_flags != 0) {
4305                 fprintf(stderr,
4306                         "%s %s: options -I and -F are mutually exclusive when used with --component-del\n",
4307                         progname, argv[0]);
4308                 goto usage_error;
4309         }
4310
4311         if (comp_add || comp_del) {
4312                 struct stat st;
4313
4314                 result = lstat(fname, &st);
4315                 if (result == 0 && S_ISDIR(st.st_mode)) {
4316                         fprintf(stderr,
4317                                 "%s setstripe: cannot use --component-add or --component-del for directory\n",
4318                                 progname);
4319                         goto usage_error;
4320                 }
4321
4322                 if (mirror_mode) {
4323                         fprintf(stderr,
4324                                 "error: %s: can't use --component-add or --component-del for mirror operation\n",
4325                                 progname);
4326                         goto usage_error;
4327                 }
4328         }
4329
4330         if (comp_add) {
4331                 if (!layout) {
4332                         fprintf(stderr,
4333                                 "%s %s: option -E must be specified with --component-add\n",
4334                                 progname, argv[0]);
4335                         goto usage_error;
4336                 }
4337         }
4338
4339         if (from_yaml && from_copy) {
4340                 fprintf(stderr,
4341                         "%s: can't specify --yaml and --copy together\n",
4342                         progname);
4343                 goto error;
4344         }
4345
4346         if ((from_yaml || from_copy) &&
4347             (setstripe_args_specified(&lsa) || layout != NULL)) {
4348                 fprintf(stderr,
4349                         "error: %s: can't specify --yaml or --copy with -c, -S, -i, -o, -p or -E options.\n",
4350                         argv[0]);
4351                 goto error;
4352         }
4353
4354         if ((migration_flags & LLAPI_MIGRATION_NONBLOCK) && migration_block) {
4355                 fprintf(stderr,
4356                         "%s %s: options --non-block and --block are mutually exclusive\n",
4357                         progname, argv[0]);
4358                 goto usage_error;
4359         }
4360
4361         if (!comp_del && !comp_set && opc != SO_MIRROR_SPLIT &&
4362             opc != SO_MIRROR_DELETE && comp_id != 0) {
4363                 fprintf(stderr,
4364                         "%s: option -I can only be used with --component-del or --component-set or lfs mirror split\n",
4365                         progname);
4366                 goto usage_error;
4367         }
4368
4369         if (migrate_mdt_mode) {
4370                 struct lmv_user_md *lmu;
4371
4372                 /* initialize migrate mdt parameters */
4373                 lmu = calloc(1, lmv_user_md_size(lsa.lsa_nr_tgts,
4374                                                  LMV_USER_MAGIC_SPECIFIC));
4375                 if (!lmu) {
4376                         fprintf(stderr,
4377                                 "%s %s: cannot allocate memory for lmv_user_md: %s\n",
4378                                 progname, argv[0], strerror(ENOMEM));
4379                         result = -ENOMEM;
4380                         goto error;
4381                 }
4382                 if (lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT)
4383                         lmu->lum_stripe_count = lsa.lsa_stripe_count;
4384                 if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT) {
4385                         fprintf(stderr,
4386                                 "%s %s: migrate should specify MDT index\n",
4387                                 progname, argv[0]);
4388                         free(lmu);
4389                         goto usage_error;
4390                 }
4391                 lmu->lum_stripe_offset = lsa.lsa_stripe_off;
4392                 if (lsa.lsa_pattern != LLAPI_LAYOUT_RAID0)
4393                         lmu->lum_hash_type = lsa.lsa_pattern;
4394                 else
4395                         lmu->lum_hash_type = LMV_HASH_TYPE_UNKNOWN;
4396                 if (lsa.lsa_pool_name) {
4397                         strncpy(lmu->lum_pool_name, lsa.lsa_pool_name,
4398                                 sizeof(lmu->lum_pool_name) - 1);
4399                         lmu->lum_pool_name[sizeof(lmu->lum_pool_name) - 1] = 0;
4400                 }
4401                 if (lsa.lsa_nr_tgts > 1) {
4402                         int i;
4403
4404                         if (lsa.lsa_stripe_count > 0 &&
4405                             lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT &&
4406                             lsa.lsa_stripe_count != lsa.lsa_nr_tgts) {
4407                                 fprintf(stderr,
4408                                         "error: %s: stripe count %lld doesn't match the number of MDTs: %d\n",
4409                                         progname, lsa.lsa_stripe_count,
4410                                         lsa.lsa_nr_tgts);
4411                                 free(lmu);
4412                                 goto usage_error;
4413                         }
4414
4415                         lmu->lum_magic = LMV_USER_MAGIC_SPECIFIC;
4416                         lmu->lum_stripe_count = lsa.lsa_nr_tgts;
4417                         for (i = 0; i < lsa.lsa_nr_tgts; i++)
4418                                 lmu->lum_objects[i].lum_mds = lsa.lsa_tgts[i];
4419                 } else {
4420                         lmu->lum_magic = LMV_USER_MAGIC;
4421                 }
4422
4423                 migrate_mdt_param.fp_lmv_md = lmu;
4424                 migrate_mdt_param.fp_migrate = 1;
4425         } else if (!layout) {
4426                 if (lsa_args_stripe_count_check(&lsa))
4427                         goto usage_error;
4428
4429                 /* initialize stripe parameters */
4430                 param = calloc(1, offsetof(typeof(*param),
4431                                lsp_osts[lsa.lsa_nr_tgts]));
4432                 if (!param) {
4433                         fprintf(stderr,
4434                                 "%s %s: cannot allocate memory for parameters: %s\n",
4435                                 progname, argv[0], strerror(ENOMEM));
4436                         result = -ENOMEM;
4437                         goto error;
4438                 }
4439
4440                 if (lsa.lsa_stripe_size != LLAPI_LAYOUT_DEFAULT)
4441                         param->lsp_stripe_size = lsa.lsa_stripe_size;
4442                 if (lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT) {
4443                         if (lsa.lsa_stripe_count == LLAPI_LAYOUT_WIDE)
4444                                 param->lsp_stripe_count = -1;
4445                         else
4446                                 param->lsp_stripe_count = lsa.lsa_stripe_count;
4447                 }
4448                 if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
4449                         param->lsp_stripe_offset = -1;
4450                 else
4451                         param->lsp_stripe_offset = lsa.lsa_stripe_off;
4452                 param->lsp_stripe_pattern =
4453                                 llapi_pattern_to_lov(lsa.lsa_pattern);
4454                 if (param->lsp_stripe_pattern == EINVAL) {
4455                         fprintf(stderr, "error: %s: invalid stripe pattern\n",
4456                                 argv[0]);
4457                         free(param);
4458                         goto usage_error;
4459                 }
4460                 param->lsp_pool = lsa.lsa_pool_name;
4461                 param->lsp_is_specific = false;
4462
4463                 if (lsa.lsa_nr_tgts > 0) {
4464                         param->lsp_is_specific = true;
4465                         param->lsp_stripe_count = lsa.lsa_nr_tgts;
4466                         memcpy(param->lsp_osts, tgts,
4467                                sizeof(*tgts) * lsa.lsa_nr_tgts);
4468                 }
4469         }
4470
4471         if (from_yaml) {
4472                 /* generate a layout from a YAML template */
4473                 result = lfs_comp_create_from_yaml(template, &layout,
4474                                                    &lsa, tgts);
4475                 if (result) {
4476                         fprintf(stderr,
4477                                 "error: %s: can't create composite layout from template file %s\n",
4478                                 argv[0], template);
4479                         goto error;
4480                 }
4481         }
4482
4483         if (layout != NULL || mirror_list != NULL) {
4484                 if (mirror_list)
4485                         result = mirror_adjust_first_extents(mirror_list);
4486                 else
4487                         result = layout_adjust_first_extent(fname, layout,
4488                                                             comp_add);
4489                 if (result == -ENODATA)
4490                         comp_add = 0;
4491                 else if (result != 0) {
4492                         fprintf(stderr, "error: %s: invalid layout\n",
4493                                 progname);
4494                         goto error;
4495                 }
4496         }
4497
4498         for (fname = argv[optind]; fname != NULL; fname = argv[++optind]) {
4499                 if (from_copy) {
4500                         layout = llapi_layout_get_by_path(template ?: fname, 0);
4501                         if (!layout) {
4502                                 fprintf(stderr,
4503                                         "%s: can't create composite layout from file %s: %s\n",
4504                                         progname, template ?: fname,
4505                                         strerror(errno));
4506                                 result = -errno;
4507                                 goto error;
4508                         }
4509                 }
4510
4511                 if (migrate_mdt_mode) {
4512                         result = llapi_migrate_mdt(fname, &migrate_mdt_param);
4513                 } else if (migrate_mode) {
4514                         result = lfs_migrate(fname, migration_flags, param,
4515                                              layout, bandwidth_bytes_sec,
4516                                              stats_flag, stats_interval_sec);
4517                 } else if (comp_set != 0) {
4518                         result = lfs_component_set(fname, comp_id,
4519                                                    lsa.lsa_pool_name,
4520                                                    lsa.lsa_comp_flags,
4521                                                    lsa.lsa_comp_neg_flags);
4522                 } else if (comp_del != 0) {
4523                         result = lfs_component_del(fname, comp_id,
4524                                                    lsa.lsa_comp_flags,
4525                                                    lsa.lsa_comp_neg_flags);
4526                 } else if (comp_add != 0) {
4527                         result = lfs_component_add(fname, layout);
4528                 } else if (opc == SO_MIRROR_CREATE) {
4529                         result = mirror_create(fname, mirror_list);
4530                 } else if (opc == SO_MIRROR_EXTEND) {
4531                         result = mirror_extend(fname, mirror_list,
4532                                                mirror_flags,
4533                                                bandwidth_bytes_sec,
4534                                                stats_flag, stats_interval_sec);
4535                 } else if (opc == SO_MIRROR_SPLIT || opc == SO_MIRROR_DELETE) {
4536                         if (!mirror_id && !comp_id && !lsa.lsa_pool_name) {
4537                                 fprintf(stderr,
4538                                         "%s: no mirror id, component id, or pool name specified to delete from '%s'\n",
4539                                         progname, fname);
4540                                 goto usage_error;
4541                         }
4542                         if (lsa.lsa_pool_name)
4543                                 mirror_flags |= MF_COMP_POOL;
4544                         else if (mirror_id != 0)
4545                                 comp_id = mirror_id;
4546                         else
4547                                 mirror_flags |= MF_COMP_ID;
4548                         if (has_m_file && !strcmp(fname, mirror_list->m_file)) {
4549                                 fprintf(stderr,
4550                                         "%s: the file specified by -f cannot be same as the source file '%s'\n",
4551                                         progname, fname);
4552                                 goto usage_error;
4553                         }
4554                         result = mirror_split(fname, comp_id, lsa.lsa_pool_name,
4555                                               mirror_flags,
4556                                               has_m_file ? mirror_list->m_file :
4557                                               NULL);
4558                 } else if (layout) {
4559                         result = lfs_component_create(fname, O_CREAT | O_WRONLY,
4560                                                       mode, layout);
4561                         if (result >= 0) {
4562                                 close(result);
4563                                 result = 0;
4564                         }
4565                 } else if (foreign_mode) {
4566                         result = llapi_file_create_foreign(fname, mode, type,
4567                                                            flags, xattr);
4568                         if (result >= 0) {
4569                                 close(result);
4570                                 result = 0;
4571                         }
4572                 } else {
4573                         result = llapi_file_open_param(fname,
4574                                                        O_CREAT | O_WRONLY,
4575                                                        mode, param);
4576                         if (result >= 0) {
4577                                 close(result);
4578                                 result = 0;
4579                         }
4580                 }
4581                 if (result) {
4582                         /* Save the first error encountered. */
4583                         if (result2 == 0)
4584                                 result2 = result;
4585                         continue;
4586                 }
4587         }
4588
4589         if (mode_opt)
4590                 umask(previous_umask);
4591
4592         free(param);
4593         free(migrate_mdt_param.fp_lmv_md);
4594         llapi_layout_free(layout);
4595         lfs_mirror_list_free(mirror_list);
4596         return result2;
4597 usage_error:
4598         result = CMD_HELP;
4599 error:
4600         llapi_layout_free(layout);
4601         lfs_mirror_list_free(mirror_list);
4602         return result;
4603 }
4604
4605 static int lfs_poollist(int argc, char **argv)
4606 {
4607         if (argc != 2)
4608                 return CMD_HELP;
4609
4610         return llapi_poollist(argv[1]);
4611 }
4612
4613 #define FP_DEFAULT_TIME_MARGIN (24 * 60 * 60)
4614 static time_t set_time(struct find_param *param, time_t *time, time_t *set,
4615                        char *str)
4616 {
4617         long long t = 0;
4618         int sign = 0;
4619         char *endptr = "AD";
4620         char *timebuf;
4621
4622         if (str[0] == '+')
4623                 sign = 1;
4624         else if (str[0] == '-')
4625                 sign = -1;
4626
4627         if (sign)
4628                 str++;
4629
4630         for (timebuf = str; *endptr && *(endptr + 1); timebuf = endptr + 1) {
4631                 long long val = strtoll(timebuf, &endptr, 0);
4632                 int unit = 1;
4633
4634                 switch (*endptr) {
4635                 case  'y':
4636                         unit *= 52; /* 52 weeks + 1 day below */
4637                         fallthrough;
4638                 case  'w':
4639                         unit *= 7;
4640                         if (param->fp_time_margin == FP_DEFAULT_TIME_MARGIN)
4641                                 param->fp_time_margin *= (1 + unit / 52);
4642                         unit += (*endptr == 'y'); /* +1 day for 365 days/year */
4643                         fallthrough;
4644                 case '\0': /* days are default unit if none used */
4645                         fallthrough;
4646                 case  'd':
4647                         unit *= 24;
4648                         fallthrough;
4649                 case  'h':
4650                         unit *= 60;
4651                         fallthrough;
4652                 case  'm':
4653                         unit *= 60;
4654                         fallthrough;
4655                 case  's':
4656                         break;
4657                         /* don't need to multiply by 1 for seconds */
4658                 default:
4659                         fprintf(stderr,
4660                                 "%s find: bad time string '%s': %s\n",
4661                                 progname, timebuf, strerror(EINVAL));
4662                         return LONG_MAX;
4663                 }
4664
4665                 if (param->fp_time_margin == 0 ||
4666                     (*endptr && unit < param->fp_time_margin))
4667                         param->fp_time_margin = unit;
4668
4669                 t += val * unit;
4670         }
4671         if (*time < t) {
4672                 if (sign != 0)
4673                         str--;
4674                 fprintf(stderr, "%s find: bad time '%s': too large\n",
4675                         progname, str);
4676                 return LONG_MAX;
4677         }
4678
4679         *set = *time - t;
4680
4681         return sign;
4682 }
4683
4684 static int str2quotaid(__u32 *id, const char *arg)
4685 {
4686         unsigned long int projid_tmp = 0;
4687         char *endptr = NULL;
4688
4689         projid_tmp = strtoul(arg, &endptr, 10);
4690         if (*endptr != '\0')
4691                 return -EINVAL;
4692         /* UINT32_MAX is not allowed - see projid_valid()/INVALID_PROJID */
4693         if (projid_tmp >= UINT32_MAX)
4694                 return -ERANGE;
4695
4696         *id = projid_tmp;
4697         return 0;
4698 }
4699
4700 static int name2uid(unsigned int *id, const char *name)
4701 {
4702         struct passwd *passwd;
4703
4704         passwd = getpwnam(name);
4705         if (!passwd)
4706                 return -ENOENT;
4707         *id = passwd->pw_uid;
4708
4709         return 0;
4710 }
4711
4712 static int name2gid(unsigned int *id, const char *name)
4713 {
4714         struct group *group;
4715
4716         group = getgrnam(name);
4717         if (!group)
4718                 return -ENOENT;
4719         *id = group->gr_gid;
4720
4721         return 0;
4722 }
4723
4724 static inline int name2projid(unsigned int *id, const char *name)
4725 {
4726         return -ENOTSUP;
4727 }
4728
4729 static int uid2name(char **name, unsigned int id)
4730 {
4731         struct passwd *passwd;
4732
4733         passwd = getpwuid(id);
4734         if (!passwd)
4735                 return -ENOENT;
4736         *name = passwd->pw_name;
4737
4738         return 0;
4739 }
4740
4741 static inline int gid2name(char **name, unsigned int id)
4742 {
4743         struct group *group;
4744
4745         group = getgrgid(id);
4746         if (!group)
4747                 return -ENOENT;
4748         *name = group->gr_name;
4749
4750         return 0;
4751 }
4752
4753 static int name2layout(__u32 *layout, char *name)
4754 {
4755         char *ptr, *layout_name;
4756
4757         *layout = 0;
4758         for (ptr = name; ; ptr = NULL) {
4759                 layout_name = strtok(ptr, ",");
4760                 if (!layout_name)
4761                         break;
4762                 if (strcmp(layout_name, "released") == 0)
4763                         *layout |= LOV_PATTERN_F_RELEASED;
4764                 else if (strcmp(layout_name, "raid0") == 0)
4765                         *layout |= LOV_PATTERN_RAID0;
4766                 else if (strcmp(layout_name, "mdt") == 0)
4767                         *layout |= LOV_PATTERN_MDT;
4768                 else if (strcmp(layout_name, "overstriping") == 0)
4769                         *layout |= LOV_PATTERN_OVERSTRIPING;
4770                 else
4771                         return -1;
4772         }
4773         return 0;
4774 }
4775
4776 static int parse_symbolic(const char *input, mode_t *outmode, const char **end)
4777 {
4778         int loop;
4779         int user, group, other;
4780         int who, all;
4781         char c, op;
4782         mode_t perm;
4783         mode_t usermask;
4784         mode_t previous_flags;
4785
4786         user = group = other = 0;
4787         all = 0;
4788         loop = 1;
4789         perm = 0;
4790         previous_flags = 0;
4791         *end = input;
4792         usermask = 0;
4793
4794         while (loop) {
4795                 switch (*input) {
4796                 case 'u':
4797                         user = 1;
4798                         break;
4799                 case 'g':
4800                         group = 1;
4801                         break;
4802                 case 'o':
4803                         other = 1;
4804                         break;
4805                 case 'a':
4806                         user = group = other = 1;
4807                         all = 1;
4808                         break;
4809                 default:
4810                         loop = 0;
4811                 }
4812
4813                 if (loop)
4814                         input++;
4815         }
4816
4817         who = user || group || other;
4818         if (!who) {
4819                 /* get the umask */
4820                 usermask = umask(0022);
4821                 umask(usermask);
4822                 usermask &= 07777;
4823         }
4824
4825         if (*input == '-' || *input == '+' || *input == '=')
4826                 op = *input++;
4827         else
4828                 /* operation is required */
4829                 return -1;
4830
4831         /* get the flags in *outmode */
4832         switch (*input) {
4833         case 'u':
4834                 previous_flags = (*outmode & 0700);
4835                 perm |= user  ? previous_flags : 0;
4836                 perm |= group ? (previous_flags >> 3) : 0;
4837                 perm |= other ? (previous_flags >> 6) : 0;
4838                 input++;
4839                 goto write_perm;
4840         case 'g':
4841                 previous_flags = (*outmode & 0070);
4842                 perm |= user  ? (previous_flags << 3) : 0;
4843                 perm |= group ? previous_flags : 0;
4844                 perm |= other ? (previous_flags >> 3) : 0;
4845                 input++;
4846                 goto write_perm;
4847         case 'o':
4848                 previous_flags = (*outmode & 0007);
4849                 perm |= user  ? (previous_flags << 6) : 0;
4850                 perm |= group ? (previous_flags << 3) : 0;
4851                 perm |= other ? previous_flags : 0;
4852                 input++;
4853                 goto write_perm;
4854         default:
4855                 break;
4856         }
4857
4858         /* this part is optional,
4859          * if empty perm = 0 and *outmode is not modified
4860          */
4861         loop = 1;
4862         while (loop) {
4863                 c = *input;
4864                 switch (c) {
4865                 case 'r':
4866                         perm |= user  ? 0400 : 0;
4867                         perm |= group ? 0040 : 0;
4868                         perm |= other ? 0004 : 0;
4869                         /* set read permission for uog except for umask's
4870                          * permissions
4871                          */
4872                         perm |= who   ? 0 : (0444 & ~usermask);
4873                         break;
4874                 case 'w':
4875                         perm |= user  ? 0200 : 0;
4876                         perm |= group ? 0020 : 0;
4877                         perm |= other ? 0002 : 0;
4878                         /* set write permission for uog except for umask'
4879                          * permissions
4880                          */
4881                         perm |= who   ? 0 : (0222 & ~usermask);
4882                         break;
4883                 case 'x':
4884                         perm |= user  ? 0100 : 0;
4885                         perm |= group ? 0010 : 0;
4886                         perm |= other ? 0001 : 0;
4887                         /* set execute permission for uog except for umask'
4888                          * permissions
4889                          */
4890                         perm |= who   ? 0 : (0111 & ~usermask);
4891                         break;
4892                 case 'X':
4893                         /*
4894                          * Adds execute permission to 'u', 'g' and/or 'g' if
4895                          * specified and either 'u', 'g' or 'o' already has
4896                          * execute permissions.
4897                          */
4898                         if ((*outmode & 0111) != 0) {
4899                                 perm |= user  ? 0100 : 0;
4900                                 perm |= group ? 0010 : 0;
4901                                 perm |= other ? 0001 : 0;
4902                                 perm |= !who  ? 0111 : 0;
4903                         }
4904                         break;
4905                 case 's':
4906                         /* s is ignored if o is given, but it's not an error */
4907                         if (other && !group && !user)
4908                                 break;
4909                         perm |= user  ? S_ISUID : 0;
4910                         perm |= group ? S_ISGID : 0;
4911                         break;
4912                 case 't':
4913                         /* 't' should be used when 'a' is given
4914                          * or who is empty
4915                          */
4916                         perm |= (!who || all) ? S_ISVTX : 0;
4917                         /* using ugo with t is not an error */
4918                         break;
4919                 default:
4920                         loop = 0;
4921                         break;
4922                 }
4923                 if (loop)
4924                         input++;
4925         }
4926
4927 write_perm:
4928         /* uog flags should be only one character long */
4929         if (previous_flags && (*input != '\0' && *input != ','))
4930                 return -1;
4931
4932         switch (op) {
4933         case '-':
4934                 /* remove the flags from outmode */
4935                 *outmode &= ~perm;
4936                 break;
4937         case '+':
4938                 /* add the flags to outmode */
4939                 *outmode |= perm;
4940                 break;
4941         case '=':
4942                 /* set the flags of outmode to perm */
4943                 if (perm != 0)
4944                         *outmode = perm;
4945                 break;
4946         }
4947
4948         *end = input;
4949         return 0;
4950 }
4951
4952 static int str2mode_t(const char *input, mode_t *outmode)
4953 {
4954         int ret;
4955         const char *iter;
4956
4957         ret = 0;
4958
4959         if (*input >= '0' && *input <= '7') {
4960                 /* parse octal representation */
4961                 char *end;
4962
4963                 iter = input;
4964
4965                 /* look for invalid digits in octal representation */
4966                 while (isdigit(*iter))
4967                         if (*iter++ > '7')
4968                                 return -1;
4969
4970                 errno = 0;
4971                 *outmode = strtoul(input, &end, 8);
4972
4973                 if (errno != 0 || *outmode > 07777) {
4974                         *outmode = 0;
4975                         ret = -1;
4976                 }
4977
4978         } else if (*input == '8' || *input == '9') {
4979                 /* error: invalid octal number */
4980                 ret = -1;
4981         } else {
4982                 /* parse coma seperated list of symbolic representation */
4983                 int rc;
4984                 const char *end;
4985
4986                 *outmode = 0;
4987                 rc = 0;
4988                 end = NULL;
4989
4990                 do {
4991                         rc = parse_symbolic(input, outmode, &end);
4992                         if (rc)
4993                                 return -1;
4994
4995                         input = end+1;
4996                 } while (*end == ',');
4997
4998                 if (*end != '\0')
4999                         ret = -1;
5000         }
5001         return ret;
5002 }
5003
5004 static int lfs_find(int argc, char **argv)
5005 {
5006         int c, rc;
5007         int ret = 0;
5008         time_t t;
5009         struct find_param param = {
5010                 .fp_max_depth = -1,
5011                 .fp_quiet = 1,
5012                 .fp_time_margin = FP_DEFAULT_TIME_MARGIN,
5013         };
5014         struct option long_opts[] = {
5015         { .val = 'A',   .name = "atime",        .has_arg = required_argument },
5016         { .val = 'b',   .name = "blocks",       .has_arg = required_argument },
5017         { .val = 'B',   .name = "btime",        .has_arg = required_argument },
5018         { .val = 'B',   .name = "Btime",        .has_arg = required_argument },
5019         { .val = LFS_COMP_COUNT_OPT,
5020                         .name = "comp-count",   .has_arg = required_argument },
5021         { .val = LFS_COMP_COUNT_OPT,
5022                         .name = "component-count",
5023                                                 .has_arg = required_argument },
5024         { .val = LFS_COMP_FLAGS_OPT,
5025                         .name = "comp-flags",   .has_arg = required_argument },
5026         { .val = LFS_COMP_FLAGS_OPT,
5027                         .name = "component-flags",
5028                                                 .has_arg = required_argument },
5029         { .val = LFS_COMP_START_OPT,
5030                         .name = "comp-start",   .has_arg = required_argument },
5031         { .val = LFS_COMP_START_OPT,
5032                         .name = "component-start",
5033                                                 .has_arg = required_argument },
5034         { .val = LFS_MIRROR_STATE_OPT,
5035                         .name = "mirror-state", .has_arg = required_argument },
5036         { .val = LFS_NEWERXY_OPT,
5037                         .name = "newer",        .has_arg = required_argument},
5038         { .val = LFS_NEWERXY_OPT,
5039                         .name = "neweraa",      .has_arg = required_argument},
5040         { .val = LFS_NEWERXY_OPT,
5041                         .name = "neweram",      .has_arg = required_argument},
5042         { .val = LFS_NEWERXY_OPT,
5043                         .name = "newerac",      .has_arg = required_argument},
5044         { .val = LFS_NEWERXY_OPT,
5045                         .name = "newerab",      .has_arg = required_argument},
5046         { .val = LFS_NEWERXY_OPT,
5047                         .name = "newerma",      .has_arg = required_argument},
5048         { .val = LFS_NEWERXY_OPT,
5049                         .name = "newermm",      .has_arg = required_argument},
5050         { .val = LFS_NEWERXY_OPT,
5051                         .name = "newermc",      .has_arg = required_argument},
5052         { .val = LFS_NEWERXY_OPT,
5053                         .name = "newermb",      .has_arg = required_argument},
5054         { .val = LFS_NEWERXY_OPT,
5055                         .name = "newerca",      .has_arg = required_argument},
5056         { .val = LFS_NEWERXY_OPT,
5057                         .name = "newercm",      .has_arg = required_argument},
5058         { .val = LFS_NEWERXY_OPT,
5059                         .name = "newercc",      .has_arg = required_argument},
5060         { .val = LFS_NEWERXY_OPT,
5061                         .name = "newercb",      .has_arg = required_argument},
5062         { .val = LFS_NEWERXY_OPT,
5063                         .name = "newerba",      .has_arg = required_argument},
5064         { .val = LFS_NEWERXY_OPT,
5065                         .name = "newerbm",      .has_arg = required_argument},
5066         { .val = LFS_NEWERXY_OPT,
5067                         .name = "newerbc",      .has_arg = required_argument},
5068         { .val = LFS_NEWERXY_OPT,
5069                         .name = "newerbb",      .has_arg = required_argument},
5070         { .val = LFS_NEWERXY_OPT,
5071                         .name = "newerBa",      .has_arg = required_argument},
5072         { .val = LFS_NEWERXY_OPT,
5073                         .name = "newerBm",      .has_arg = required_argument},
5074         { .val = LFS_NEWERXY_OPT,
5075                         .name = "newerBc",      .has_arg = required_argument},
5076         { .val = LFS_NEWERXY_OPT,
5077                         .name = "newerBB",      .has_arg = required_argument},
5078         { .val = LFS_NEWERXY_OPT,
5079                         .name = "newerat",      .has_arg = required_argument},
5080         { .val = LFS_NEWERXY_OPT,
5081                         .name = "newermt",      .has_arg = required_argument},
5082         { .val = LFS_NEWERXY_OPT,
5083                         .name = "newerct",      .has_arg = required_argument},
5084         { .val = LFS_NEWERXY_OPT,
5085                         .name = "newerbt",      .has_arg = required_argument},
5086         { .val = LFS_NEWERXY_OPT,
5087                         .name = "newerBt",      .has_arg = required_argument},
5088         { .val = 'c',   .name = "stripe-count", .has_arg = required_argument },
5089         { .val = 'c',   .name = "stripe_count", .has_arg = required_argument },
5090         { .val = 'C',   .name = "ctime",        .has_arg = required_argument },
5091 /* getstripe { .val = 'd', .name = "directory", .has_arg = no_argument }, */
5092         { .val = 'D',   .name = "maxdepth",     .has_arg = required_argument },
5093         { .val = 'E',   .name = "comp-end",     .has_arg = required_argument },
5094         { .val = 'E',   .name = "component-end",
5095                                                 .has_arg = required_argument },
5096 /* find { .val = 'F',   .name = "fid",          .has_arg = no_argument }, */
5097         { .val = LFS_LAYOUT_FOREIGN_OPT,
5098                         .name = "foreign",      .has_arg = optional_argument},
5099         { .val = 'g',   .name = "gid",          .has_arg = required_argument },
5100         { .val = 'G',   .name = "group",        .has_arg = required_argument },
5101         { .val = 'h',   .name = "help",         .has_arg = no_argument },
5102         { .val = 'H',   .name = "mdt-hash",     .has_arg = required_argument },
5103         { .val = 'i',   .name = "stripe-index", .has_arg = required_argument },
5104         { .val = 'i',   .name = "stripe_index", .has_arg = required_argument },
5105 /* getstripe { .val = 'I', .name = "comp-id",   .has_arg = required_argument }*/
5106         { .val = 'l',   .name = "lazy",         .has_arg = no_argument },
5107         { .val = 'L',   .name = "layout",       .has_arg = required_argument },
5108         { .val = 'm',   .name = "mdt",          .has_arg = required_argument },
5109         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument },
5110         { .val = 'm',   .name = "mdt_index",    .has_arg = required_argument },
5111         { .val = 'M',   .name = "mtime",        .has_arg = required_argument },
5112         { .val = 'n',   .name = "name",         .has_arg = required_argument },
5113         { .val = 'N',   .name = "mirror-count", .has_arg = required_argument },
5114 /* find { .val = 'o'    .name = "or", .has_arg = no_argument }, like find(1) */
5115         { .val = 'O',   .name = "obd",          .has_arg = required_argument },
5116         { .val = 'O',   .name = "ost",          .has_arg = required_argument },
5117         { .val = LFS_FIND_PERM,
5118                         .name = "perm",         .has_arg = required_argument },
5119         /* no short option for pool yet, can be 'p' after 2.18 */
5120         { .val = LFS_POOL_OPT,
5121                         .name = "pool",         .has_arg = required_argument },
5122         { .val = '0',   .name = "print0",       .has_arg = no_argument },
5123         { .val = 'P',   .name = "print",        .has_arg = no_argument },
5124         { .val = LFS_PRINTF_OPT,
5125                         .name = "printf",       .has_arg = required_argument },
5126         { .val = LFS_PROJID_OPT,
5127                         .name = "projid",       .has_arg = required_argument },
5128 /* getstripe { .val = 'q', .name = "quiet",     .has_arg = no_argument }, */
5129 /* getstripe { .val = 'r', .name = "recursive", .has_arg = no_argument }, */
5130 /* getstripe { .val = 'R', .name = "raw",       .has_arg = no_argument }, */
5131         { .val = 's',   .name = "size",         .has_arg = required_argument },
5132         { .val = 'S',   .name = "stripe-size",  .has_arg = required_argument },
5133         { .val = 'S',   .name = "stripe_size",  .has_arg = required_argument },
5134         { .val = 't',   .name = "type",         .has_arg = required_argument },
5135         { .val = 'T',   .name = "mdt-count",    .has_arg = required_argument },
5136         { .val = 'u',   .name = "uid",          .has_arg = required_argument },
5137         { .val = 'U',   .name = "user",         .has_arg = required_argument },
5138 /* getstripe { .val = 'v', .name = "verbose",   .has_arg = no_argument }, */
5139 /* setstripe { .val = 'W', .name = "bandwidth", .has_arg = required_argument }, */
5140         { .val = 'z',   .name = "extension-size",
5141                                                 .has_arg = required_argument },
5142         { .val = 'z',   .name = "ext-size",     .has_arg = required_argument },
5143         { .name = NULL } };
5144         int optidx = 0;
5145         int pathstart = -1;
5146         int pathend = -1;
5147         int pathbad = -1;
5148         int neg_opt = 0;
5149         time_t *xtime;
5150         int *xsign;
5151         int isoption;
5152         char *endptr;
5153
5154         time(&t);
5155
5156         /* when getopt_long_only() hits '!' it returns 1, puts "!" in optarg */
5157         while ((c = getopt_long_only(argc, argv,
5158                 "-0A:b:B:c:C:D:E:g:G:hH:i:L:m:M:n:N:O:Ppqrs:S:t:T:u:U:z:",
5159                 long_opts, &optidx)) >= 0) {
5160                 xtime = NULL;
5161                 xsign = NULL;
5162                 if (neg_opt)
5163                         --neg_opt;
5164                 /* '!' is part of option */
5165                 /*
5166                  * when getopt_long_only() finds a string which is not
5167                  * an option nor a known option argument it returns 1
5168                  * in that case if we already have found pathstart and pathend
5169                  * (i.e. we have the list of pathnames),
5170                  * the only supported value is "!"
5171                  */
5172                 isoption = (c != 1) || (strcmp(optarg, "!") == 0);
5173                 if (!isoption && pathend != -1) {
5174                         fprintf(stderr,
5175                                 "err: %s: filename|dirname must either precede options or follow options\n",
5176                                 argv[0]);
5177                         ret = CMD_HELP;
5178                         goto err;
5179                 }
5180                 if (!isoption && pathstart == -1)
5181                         pathstart = optind - 1;
5182                 if (isoption && pathstart != -1 && pathend == -1)
5183                         pathend = optind - 2;
5184                 switch (c) {
5185                 case 0:
5186                         /* Long options. */
5187                         break;
5188                 case 1:
5189                         /*
5190                          * unknown; opt is "!" or path component,
5191                          * checking done above.
5192                          */
5193                         if (strcmp(optarg, "!") == 0)
5194                                 neg_opt = 2;
5195                         break;
5196                 case 'A':
5197                         xtime = &param.fp_atime;
5198                         xsign = &param.fp_asign;
5199                         param.fp_exclude_atime = !!neg_opt;
5200                         /* no break, this falls through to 'B' for btime */
5201                         fallthrough;
5202                 case 'B':
5203                         if (c == 'B') {
5204                                 xtime = &param.fp_btime;
5205                                 xsign = &param.fp_bsign;
5206                                 param.fp_exclude_btime = !!neg_opt;
5207                         }
5208                         /* no break, this falls through to 'C' for ctime */
5209                         fallthrough;
5210                 case 'C':
5211                         if (c == 'C') {
5212                                 xtime = &param.fp_ctime;
5213                                 xsign = &param.fp_csign;
5214                                 param.fp_exclude_ctime = !!neg_opt;
5215                         }
5216                         /* no break, this falls through to 'M' for mtime */
5217                         fallthrough;
5218                 case 'M':
5219                         if (c == 'M') {
5220                                 xtime = &param.fp_mtime;
5221                                 xsign = &param.fp_msign;
5222                                 param.fp_exclude_mtime = !!neg_opt;
5223                         }
5224                         rc = set_time(&param, &t, xtime, optarg);
5225                         if (rc == LONG_MAX) {
5226                                 ret = -1;
5227                                 goto err;
5228                         }
5229                         if (rc)
5230                                 *xsign = rc;
5231                         break;
5232                 case 'b':
5233                         if (optarg[0] == '+') {
5234                                 param.fp_blocks_sign = -1;
5235                                 optarg++;
5236                         } else if (optarg[0] == '-') {
5237                                 param.fp_blocks_sign =  1;
5238                                 optarg++;
5239                         }
5240
5241                         param.fp_blocks_units = 1024;
5242                         ret = llapi_parse_size(optarg, &param.fp_blocks,
5243                                                &param.fp_blocks_units, 0);
5244                         if (ret) {
5245                                 fprintf(stderr, "error: bad blocks '%s'\n",
5246                                         optarg);
5247                                 goto err;
5248                         }
5249                         param.fp_check_blocks = 1;
5250                         param.fp_exclude_blocks = !!neg_opt;
5251                         break;
5252                 case LFS_COMP_COUNT_OPT:
5253                         if (optarg[0] == '+') {
5254                                 param.fp_comp_count_sign = -1;
5255                                 optarg++;
5256                         } else if (optarg[0] == '-') {
5257                                 param.fp_comp_count_sign =  1;
5258                                 optarg++;
5259                         }
5260
5261                         errno = 0;
5262                         param.fp_comp_count = strtoul(optarg, &endptr, 0);
5263                         if (errno != 0 || *endptr != '\0' ||
5264                             param.fp_comp_count > UINT32_MAX) {
5265                                 fprintf(stderr,
5266                                         "error: bad component count '%s'\n",
5267                                         optarg);
5268                                 goto err;
5269                         }
5270                         param.fp_check_comp_count = 1;
5271                         param.fp_exclude_comp_count = !!neg_opt;
5272                         break;
5273                 case LFS_COMP_FLAGS_OPT:
5274                         rc = comp_str2flags(optarg, &param.fp_comp_flags,
5275                                             &param.fp_comp_neg_flags);
5276                         if (rc) {
5277                                 fprintf(stderr,
5278                                         "error: bad component flags '%s'\n",
5279                                         optarg);
5280                                 goto err;
5281                         }
5282                         param.fp_check_comp_flags = 1;
5283                         if (neg_opt) {
5284                                 __u32 flags = param.fp_comp_neg_flags;
5285
5286                                 param.fp_comp_neg_flags = param.fp_comp_flags;
5287                                 param.fp_comp_flags = flags;
5288                         }
5289                         break;
5290                 case LFS_COMP_START_OPT:
5291                         if (optarg[0] == '+') {
5292                                 param.fp_comp_start_sign = -1;
5293                                 optarg++;
5294                         } else if (optarg[0] == '-') {
5295                                 param.fp_comp_start_sign =  1;
5296                                 optarg++;
5297                         }
5298
5299                         rc = llapi_parse_size(optarg, &param.fp_comp_start,
5300                                               &param.fp_comp_start_units, 0);
5301                         if (rc) {
5302                                 fprintf(stderr,
5303                                         "error: bad component start '%s'\n",
5304                                         optarg);
5305                                 goto err;
5306                         }
5307                         param.fp_check_comp_start = 1;
5308                         param.fp_exclude_comp_start = !!neg_opt;
5309                         break;
5310                 case LFS_MIRROR_STATE_OPT:
5311                         rc = mirror_str2state(optarg, &param.fp_mirror_state,
5312                                               &param.fp_mirror_neg_state);
5313                         if (rc) {
5314                                 fprintf(stderr,
5315                                         "error: bad mirrored file state '%s'\n",
5316                                         optarg);
5317                                 goto err;
5318                         }
5319                         param.fp_check_mirror_state = 1;
5320                         if (neg_opt) {
5321                                 __u16 state = param.fp_mirror_neg_state;
5322
5323                                 param.fp_mirror_neg_state =
5324                                         param.fp_mirror_state;
5325                                 param.fp_mirror_state = state;
5326                         }
5327                         break;
5328                 case 'c':
5329                         if (optarg[0] == '+') {
5330                                 param.fp_stripe_count_sign = -1;
5331                                 optarg++;
5332                         } else if (optarg[0] == '-') {
5333                                 param.fp_stripe_count_sign =  1;
5334                                 optarg++;
5335                         }
5336
5337                         errno = 0;
5338                         param.fp_stripe_count = strtoul(optarg, &endptr, 0);
5339                         if (errno != 0 || *endptr != '\0' ||
5340                             param.fp_stripe_count > LOV_MAX_STRIPE_COUNT) {
5341                                 fprintf(stderr,
5342                                         "error: bad stripe_count '%s'\n",
5343                                         optarg);
5344                                 ret = -1;
5345                                 goto err;
5346                         }
5347                         param.fp_check_stripe_count = 1;
5348                         param.fp_exclude_stripe_count = !!neg_opt;
5349                         break;
5350                 case 'D':
5351                         errno = 0;
5352                         param.fp_max_depth = strtol(optarg, 0, 0);
5353                         if (errno != 0 || param.fp_max_depth < 0) {
5354                                 fprintf(stderr,
5355                                         "error: bad maxdepth '%s'\n",
5356                                         optarg);
5357                                 ret = -1;
5358                                 goto err;
5359                         }
5360                         break;
5361                 case 'E':
5362                         if (optarg[0] == '+') {
5363                                 param.fp_comp_end_sign = -1;
5364                                 optarg++;
5365                         } else if (optarg[0] == '-') {
5366                                 param.fp_comp_end_sign =  1;
5367                                 optarg++;
5368                         }
5369
5370                         if (arg_is_eof(optarg)) {
5371                                 param.fp_comp_end = LUSTRE_EOF;
5372                                 param.fp_comp_end_units = 1;
5373                                 rc = 0;
5374                         } else {
5375                                 rc = llapi_parse_size(optarg,
5376                                                 &param.fp_comp_end,
5377                                                 &param.fp_comp_end_units, 0);
5378                                 /* assume units of KB if too small */
5379                                 if (param.fp_comp_end < 4096)
5380                                         param.fp_comp_end *= 1024;
5381                         }
5382                         if (rc) {
5383                                 fprintf(stderr,
5384                                         "error: bad component end '%s'\n",
5385                                         optarg);
5386                                 goto err;
5387                         }
5388                         param.fp_check_comp_end = 1;
5389                         param.fp_exclude_comp_end = !!neg_opt;
5390                         break;
5391                 case LFS_LAYOUT_FOREIGN_OPT: {
5392                         /* all types by default */
5393                         uint32_t type = LU_FOREIGN_TYPE_UNKNOWN;
5394
5395                         if (optarg) {
5396                                 /* check pure numeric */
5397                                 type = strtoul(optarg, &endptr, 0);
5398                                 if (*endptr) {
5399                                         /* check name */
5400                                         type = check_foreign_type_name(optarg);
5401                                         if (type == LU_FOREIGN_TYPE_UNKNOWN) {
5402                                                 fprintf(stderr,
5403                                                         "%s %s: unknown foreign type '%s'\n",
5404                                                         progname, argv[0],
5405                                                         optarg);
5406                                                 return CMD_HELP;
5407                                         }
5408                                 } else if (type >= UINT32_MAX) {
5409                                         fprintf(stderr,
5410                                                 "%s %s: invalid foreign type '%s'\n",
5411                                                 progname, argv[0], optarg);
5412                                         return CMD_HELP;
5413                                 }
5414                         }
5415                         param.fp_foreign_type = type;
5416                         param.fp_check_foreign = 1;
5417                         param.fp_exclude_foreign = !!neg_opt;
5418                         break;
5419                 }
5420                 case LFS_NEWERXY_OPT: {
5421                         char x = 'm';
5422                         char y = 'm';
5423                         int xidx;
5424                         int negidx;
5425                         time_t *newery;
5426                         time_t ref = time(NULL);
5427
5428                         /* no need to check bad options, they won't get here */
5429                         if (strlen(long_opts[optidx].name) == 7) {
5430                                 x = long_opts[optidx].name[5];
5431                                 y = long_opts[optidx].name[6];
5432                         }
5433
5434                         if (y == 't') {
5435                                 static const char *const fmts[] = {
5436                                         "%Y-%m-%d %H:%M:%S",
5437                                         "%Y-%m-%d %H:%M",
5438                                         "%Y-%m-%d",
5439                                         "%H:%M:%S", /* sometime today */
5440                                         "%H:%M",
5441                                         "@%s",
5442                                         "%s",
5443                                         NULL };
5444                                 struct tm tm;
5445                                 bool found = false;
5446                                 int i;
5447
5448                                 for (i = 0; fmts[i] != NULL; i++) {
5449                                         char *ptr;
5450
5451                                         /* Init for times relative to today */
5452                                         if (strncmp(fmts[i], "%H", 2) == 0) {
5453                                                 localtime_r(&ref, &tm);
5454                                         } else {
5455                                                 memset(&tm, 0, sizeof(tm));
5456                                                 tm.tm_isdst = -1;
5457                                         }
5458                                         ptr = strptime(optarg, fmts[i], &tm);
5459                                         /* Skip spaces */
5460                                         while (ptr && isspace(*ptr))
5461                                                 ptr++;
5462                                         if (ptr == optarg + strlen(optarg)) {
5463                                                 found = true;
5464                                                 break;
5465                                         }
5466                                 }
5467
5468                                 if (!found) {
5469                                         fprintf(stderr,
5470                                                 "%s: invalid time '%s'\n",
5471                                                 progname, optarg);
5472                                         fprintf(stderr,
5473                                                 "supported formats are:\n  ");
5474                                         for (i = 0; fmts[i] != NULL; i++)
5475                                                 fprintf(stderr, "'%s', ",
5476                                                         fmts[i]);
5477                                         fprintf(stderr, "\n");
5478                                         ret = -EINVAL;
5479                                         goto err;
5480                                 }
5481
5482                                 ref = mktime(&tm);
5483                         } else if (y == 'b' || y == 'B') {
5484                                 lstatx_t stx;
5485
5486                                 rc = llapi_get_lum_file(optarg, NULL, &stx,
5487                                                         NULL, 0);
5488                                 if (rc || !(stx.stx_mask & STATX_BTIME)) {
5489                                         if (!(stx.stx_mask & STATX_BTIME))
5490                                                 ret = -EOPNOTSUPP;
5491                                         else
5492                                                 ret = -errno;
5493                                         fprintf(stderr,
5494                                                 "%s: get btime failed '%s': %s\n",
5495                                                 progname, optarg,
5496                                                 strerror(-ret));
5497                                         goto err;
5498                                 }
5499
5500                                 ref = stx.stx_btime.tv_sec;
5501                         } else {
5502                                 struct stat statbuf;
5503
5504                                 if (stat(optarg, &statbuf) < 0) {
5505                                         fprintf(stderr,
5506                                                 "%s: cannot stat file '%s': %s\n",
5507                                                 progname, optarg,
5508                                                 strerror(errno));
5509                                         ret = -errno;
5510                                         goto err;
5511                                 }
5512
5513                                 switch (y) {
5514                                 case 'a':
5515                                         ref = statbuf.st_atime;
5516                                         break;
5517                                 case 'm':
5518                                         ref = statbuf.st_mtime;
5519                                         break;
5520                                 case 'c':
5521                                         ref = statbuf.st_ctime;
5522                                         break;
5523                                 default:
5524                                         fprintf(stderr,
5525                                                 "%s: invalid Y argument: '%c'\n",
5526                                                 progname, x);
5527                                         ret = -EINVAL;
5528                                         goto err;
5529                                 }
5530                         }
5531
5532                         switch (x) {
5533                         case 'a':
5534                                 xidx = NEWERXY_ATIME;
5535                                 break;
5536                         case 'm':
5537                                 xidx = NEWERXY_MTIME;
5538                                 break;
5539                         case 'c':
5540                                 xidx = NEWERXY_CTIME;
5541                                 break;
5542                         case 'b':
5543                         case 'B':
5544                                 xidx = NEWERXY_BTIME;
5545                                 break;
5546                         default:
5547                                 fprintf(stderr,
5548                                         "%s: invalid X argument: '%c'\n",
5549                                         progname, x);
5550                                 ret = -EINVAL;
5551                                 goto err;
5552                         }
5553
5554                         negidx = !!neg_opt;
5555                         newery = &param.fp_newery[xidx][negidx];
5556
5557                         if (*newery == 0) {
5558                                 *newery = ref;
5559                         } else {
5560                                 if (negidx)
5561                                         *newery = *newery > ref ? ref : *newery;
5562                                 else
5563                                         *newery = *newery > ref ? *newery : ref;
5564                         }
5565                         param.fp_newerxy = 1;
5566                         break;
5567                 }
5568                 case 'g':
5569                 case 'G':
5570                         rc = name2gid(&param.fp_gid, optarg);
5571                         if (rc) {
5572                                 if (str2quotaid(&param.fp_gid, optarg)) {
5573                                         fprintf(stderr,
5574                                                 "Group/GID: %s cannot be found.\n",
5575                                                 optarg);
5576                                         ret = -1;
5577                                         goto err;
5578                                 }
5579                         }
5580                         param.fp_exclude_gid = !!neg_opt;
5581                         param.fp_check_gid = 1;
5582                         break;
5583                 case 'H':
5584                         rc = mdthash_input(optarg, &param.fp_hash_inflags,
5585                                            &param.fp_hash_exflags,
5586                                            &param.fp_hash_type);
5587                         if (rc) {
5588                                 ret = -1;
5589                                 goto err;
5590                         }
5591                         if (param.fp_hash_inflags || param.fp_hash_exflags)
5592                                 param.fp_check_hash_flag = 1;
5593                         param.fp_exclude_hash_type = !!neg_opt;
5594                         break;
5595                 case 'l':
5596                         param.fp_lazy = 1;
5597                         break;
5598                 case 'L':
5599                         ret = name2layout(&param.fp_layout, optarg);
5600                         if (ret)
5601                                 goto err;
5602                         param.fp_exclude_layout = !!neg_opt;
5603                         param.fp_check_layout = 1;
5604                         break;
5605                 case 'u':
5606                 case 'U':
5607                         rc = name2uid(&param.fp_uid, optarg);
5608                         if (rc) {
5609                                 if (str2quotaid(&param.fp_uid, optarg)) {
5610                                         fprintf(stderr,
5611                                                 "User/UID: %s cannot be found.\n",
5612                                                 optarg);
5613                                         ret = -1;
5614                                         goto err;
5615                                 }
5616                         }
5617                         param.fp_exclude_uid = !!neg_opt;
5618                         param.fp_check_uid = 1;
5619                         break;
5620                 case 'n':
5621                         param.fp_pattern = (char *)optarg;
5622                         param.fp_exclude_pattern = !!neg_opt;
5623                         break;
5624                 case 'N':
5625                         if (optarg[0] == '+') {
5626                                 param.fp_mirror_count_sign = -1;
5627                                 optarg++;
5628                         } else if (optarg[0] == '-') {
5629                                 param.fp_mirror_count_sign =  1;
5630                                 optarg++;
5631                         }
5632
5633                         errno = 0;
5634                         param.fp_mirror_count = strtoul(optarg, &endptr, 0);
5635                         if (errno != 0 || *endptr != '\0' ||
5636                             param.fp_mirror_count > LUSTRE_MIRROR_COUNT_MAX) {
5637                                 fprintf(stderr,
5638                                         "error: bad mirror count '%s'\n",
5639                                         optarg);
5640                                 goto err;
5641                         }
5642                         param.fp_check_mirror_count = 1;
5643                         param.fp_exclude_mirror_count = !!neg_opt;
5644                         break;
5645                 case 'm':
5646                 case 'i':
5647                 case 'O': {
5648                         char *buf, *token, *next, *p;
5649                         int len = 1;
5650                         void *tmp;
5651
5652                         buf = strdup(optarg);
5653                         if (!buf) {
5654                                 ret = -ENOMEM;
5655                                 goto err;
5656                         }
5657
5658                         param.fp_exclude_obd = !!neg_opt;
5659
5660                         token = buf;
5661                         while (token && *token) {
5662                                 token = strchr(token, ',');
5663                                 if (token) {
5664                                         len++;
5665                                         token++;
5666                                 }
5667                         }
5668                         if (c == 'm') {
5669                                 param.fp_exclude_mdt = !!neg_opt;
5670                                 param.fp_num_alloc_mdts += len;
5671                                 tmp = realloc(param.fp_mdt_uuid,
5672                                               param.fp_num_alloc_mdts *
5673                                               sizeof(*param.fp_mdt_uuid));
5674                                 if (!tmp) {
5675                                         ret = -ENOMEM;
5676                                         goto err_free;
5677                                 }
5678
5679                                 param.fp_mdt_uuid = tmp;
5680                         } else {
5681                                 param.fp_exclude_obd = !!neg_opt;
5682                                 param.fp_num_alloc_obds += len;
5683                                 tmp = realloc(param.fp_obd_uuid,
5684                                               param.fp_num_alloc_obds *
5685                                               sizeof(*param.fp_obd_uuid));
5686                                 if (!tmp) {
5687                                         ret = -ENOMEM;
5688                                         goto err_free;
5689                                 }
5690
5691                                 param.fp_obd_uuid = tmp;
5692                         }
5693                         for (token = buf; token && *token; token = next) {
5694                                 struct obd_uuid *puuid;
5695
5696                                 if (c == 'm') {
5697                                         puuid =
5698                                         &param.fp_mdt_uuid[param.fp_num_mdts++];
5699                                 } else {
5700                                         puuid =
5701                                         &param.fp_obd_uuid[param.fp_num_obds++];
5702                                 }
5703                                 p = strchr(token, ',');
5704                                 next = 0;
5705                                 if (p) {
5706                                         *p = 0;
5707                                         next = p+1;
5708                                 }
5709
5710                                 if (strlen(token) > sizeof(puuid->uuid) - 1) {
5711                                         ret = -E2BIG;
5712                                         goto err_free;
5713                                 }
5714
5715                                 strncpy(puuid->uuid, token,
5716                                         sizeof(puuid->uuid));
5717                         }
5718 err_free:
5719                         if (buf)
5720                                 free(buf);
5721                         break;
5722                 }
5723 #if LUSTRE_VERSION_CODE >= OBD_OCD_VERSION(2, 18, 53, 0)
5724                 case 'p':
5725 #endif
5726                 case LFS_POOL_OPT:
5727                         if (strlen(optarg) > LOV_MAXPOOLNAME) {
5728                                 fprintf(stderr,
5729                                         "Pool name %s is too long (max %d)\n",
5730                                         optarg, LOV_MAXPOOLNAME);
5731                                 ret = -1;
5732                                 goto err;
5733                         }
5734                         /*
5735                          * We do check for empty pool because empty pool
5736                          * is used to find V1 LOV attributes
5737                          */
5738                         strncpy(param.fp_poolname, optarg, LOV_MAXPOOLNAME);
5739                         param.fp_poolname[LOV_MAXPOOLNAME] = '\0';
5740                         param.fp_exclude_pool = !!neg_opt;
5741                         param.fp_check_pool = 1;
5742                         break;
5743                 case '0':
5744                         param.fp_zero_end = 1;
5745                         break;
5746                 case 'P': /* we always print, this option is a no-op */
5747                         break;
5748                 case LFS_PRINTF_OPT:
5749                         param.fp_format_printf_str = optarg;
5750                         break;
5751                 case LFS_PROJID_OPT:
5752                         rc = name2projid(&param.fp_projid, optarg);
5753                         if (rc) {
5754                                 if (str2quotaid(&param.fp_projid, optarg)) {
5755                                         fprintf(stderr,
5756                                                 "Invalid project ID: %s\n",
5757                                                 optarg);
5758                                         ret = -1;
5759                                         goto err;
5760                                 }
5761                         }
5762                         param.fp_exclude_projid = !!neg_opt;
5763                         param.fp_check_projid = 1;
5764                         break;
5765                 case 's':
5766                         if (optarg[0] == '+') {
5767                                 param.fp_size_sign = -1;
5768                                 optarg++;
5769                         } else if (optarg[0] == '-') {
5770                                 param.fp_size_sign =  1;
5771                                 optarg++;
5772                         }
5773
5774                         ret = llapi_parse_size(optarg, &param.fp_size,
5775                                                &param.fp_size_units, 0);
5776                         if (ret) {
5777                                 fprintf(stderr, "error: bad file size '%s'\n",
5778                                         optarg);
5779                                 goto err;
5780                         }
5781                         param.fp_check_size = 1;
5782                         param.fp_exclude_size = !!neg_opt;
5783                         break;
5784                 case 'S':
5785                         if (optarg[0] == '+') {
5786                                 param.fp_stripe_size_sign = -1;
5787                                 optarg++;
5788                         } else if (optarg[0] == '-') {
5789                                 param.fp_stripe_size_sign =  1;
5790                                 optarg++;
5791                         }
5792
5793                         ret = llapi_parse_size(optarg, &param.fp_stripe_size,
5794                                                &param.fp_stripe_size_units, 0);
5795                         /* assume units of KB if too small to be valid */
5796                         if (param.fp_stripe_size < 4096)
5797                                 param.fp_stripe_size *= 1024;
5798                         if (ret) {
5799                                 fprintf(stderr, "error: bad stripe_size '%s'\n",
5800                                         optarg);
5801                                 goto err;
5802                         }
5803                         param.fp_check_stripe_size = 1;
5804                         param.fp_exclude_stripe_size = !!neg_opt;
5805                         break;
5806                 case 't':
5807                         param.fp_exclude_type = !!neg_opt;
5808                         switch (optarg[0]) {
5809                         case 'b':
5810                                 param.fp_type = S_IFBLK;
5811                                 break;
5812                         case 'c':
5813                                 param.fp_type = S_IFCHR;
5814                                 break;
5815                         case 'd':
5816                                 param.fp_type = S_IFDIR;
5817                                 break;
5818                         case 'f':
5819                                 param.fp_type = S_IFREG;
5820                                 break;
5821                         case 'l':
5822                                 param.fp_type = S_IFLNK;
5823                                 break;
5824                         case 'p':
5825                                 param.fp_type = S_IFIFO;
5826                                 break;
5827                         case 's':
5828                                 param.fp_type = S_IFSOCK;
5829                                 break;
5830                         default:
5831                                 fprintf(stderr, "%s: bad type '%s'\n",
5832                                         progname, optarg);
5833                                 ret = CMD_HELP;
5834                                 goto err;
5835                         }
5836                         break;
5837                 case LFS_FIND_PERM:
5838                         param.fp_exclude_perm = !!neg_opt;
5839                         param.fp_perm_sign = LFS_FIND_PERM_EXACT;
5840                         if (*optarg == '/') {
5841                                 param.fp_perm_sign = LFS_FIND_PERM_ANY;
5842                                 optarg++;
5843                         } else if (*optarg == '-') {
5844                                 param.fp_perm_sign = LFS_FIND_PERM_ALL;
5845                                 optarg++;
5846                         }
5847
5848                         if (str2mode_t(optarg, &param.fp_perm)) {
5849                                 fprintf(stderr, "error: invalid mode '%s'\n",
5850                                         optarg);
5851                                 ret = -1;
5852                                 goto err;
5853                         }
5854                         break;
5855                 case 'T':
5856                         if (optarg[0] == '+') {
5857                                 param.fp_mdt_count_sign = -1;
5858                                 optarg++;
5859                         } else if (optarg[0] == '-') {
5860                                 param.fp_mdt_count_sign =  1;
5861                                 optarg++;
5862                         }
5863
5864                         errno = 0;
5865                         param.fp_mdt_count = strtoul(optarg, &endptr, 0);
5866                         if (errno != 0 || *endptr != '\0' ||
5867                             param.fp_mdt_count >= UINT32_MAX) {
5868                                 fprintf(stderr, "error: bad mdt_count '%s'\n",
5869                                         optarg);
5870                                 ret = -1;
5871                                 goto err;
5872                         }
5873                         param.fp_check_mdt_count = 1;
5874                         param.fp_exclude_mdt_count = !!neg_opt;
5875                         break;
5876                 case 'z':
5877                         if (optarg[0] == '+') {
5878                                 param.fp_ext_size_sign = -1;
5879                                 optarg++;
5880                         } else if (optarg[0] == '-') {
5881                                 param.fp_ext_size_sign =  1;
5882                                 optarg++;
5883                         }
5884
5885                         ret = llapi_parse_size(optarg, &param.fp_ext_size,
5886                                                &param.fp_ext_size_units, 0);
5887                         if (ret) {
5888                                 fprintf(stderr, "error: bad ext-size '%s'\n",
5889                                         optarg);
5890                                 goto err;
5891                         }
5892                         param.fp_ext_size /= SEL_UNIT_SIZE;
5893                         param.fp_ext_size_units /= SEL_UNIT_SIZE;
5894                         param.fp_check_ext_size = 1;
5895                         param.fp_exclude_ext_size = !!neg_opt;
5896                         break;
5897                 default:
5898                         fprintf(stderr, "%s: unrecognized option '%s'\n",
5899                                 progname, argv[optind - 1]);
5900                 case 'h':
5901                         ret = CMD_HELP;
5902                         goto err;
5903                 }
5904         }
5905         if (!param.fp_verbose)
5906                 param.fp_verbose = VERBOSE_DEFAULT;
5907
5908         if (pathstart == -1) {
5909                 fprintf(stderr, "error: %s: no filename|pathname\n",
5910                         argv[0]);
5911                 ret = CMD_HELP;
5912                 goto err;
5913         } else if (pathend == -1) {
5914                 /* no options */
5915                 pathend = argc;
5916         }
5917
5918         do {
5919                 rc = llapi_find(argv[pathstart], &param);
5920                 if (rc && !ret) {
5921                         ret = rc;
5922                         pathbad = pathstart;
5923                 }
5924         } while (++pathstart < pathend);
5925
5926         if (ret)
5927                 fprintf(stderr, "%s: failed for '%s': %s\n",
5928                         progname, argv[pathbad], strerror(-rc));
5929
5930 err:
5931         if (param.fp_obd_uuid && param.fp_num_alloc_obds)
5932                 free(param.fp_obd_uuid);
5933
5934         if (param.fp_mdt_uuid && param.fp_num_alloc_mdts)
5935                 free(param.fp_mdt_uuid);
5936
5937         return ret;
5938 }
5939
5940 static int lfs_getstripe_internal(int argc, char **argv,
5941                                   struct find_param *param)
5942 {
5943         struct option long_opts[] = {
5944 /* find { .val = 'A',   .name = "atime",        .has_arg = required_argument }*/
5945 /* find { .val = 'b',   .name = "blocks",       .has_arg = required_argument }*/
5946 /* find { .val = 'B',   .name = "btime",        .has_arg = required_argument }*/
5947 /* find { .val = 'B',   .name = "Btime",        .has_arg = required_argument }*/
5948         { .val = LFS_COMP_COUNT_OPT,
5949                         .name = "comp-count",   .has_arg = no_argument },
5950         { .val = LFS_COMP_COUNT_OPT,
5951                 .name = "component-count",      .has_arg = no_argument },
5952         { .val = LFS_COMP_FLAGS_OPT,
5953                         .name = "comp-flags",   .has_arg = optional_argument },
5954         { .val = LFS_COMP_FLAGS_OPT,
5955                 .name = "component-flags",      .has_arg = optional_argument },
5956         { .val = LFS_COMP_START_OPT,
5957                         .name = "comp-start",   .has_arg = optional_argument },
5958         { .val = LFS_COMP_START_OPT,
5959                 .name = "component-start",      .has_arg = optional_argument },
5960         { .val = LFS_MIRROR_INDEX_OPT,
5961                 .name = "mirror-index",         .has_arg = required_argument },
5962         { .val = LFS_MIRROR_ID_OPT,
5963                 .name = "mirror-id",            .has_arg = required_argument },
5964         { .val = LFS_NO_FOLLOW_OPT,
5965                 .name = "no-follow",            .has_arg = no_argument },
5966         { .val = 'c',   .name = "stripe-count", .has_arg = no_argument },
5967         { .val = 'c',   .name = "stripe_count", .has_arg = no_argument },
5968 /* find { .val = 'C',   .name = "ctime",        .has_arg = required_argument }*/
5969         { .val = 'd',   .name = "directory",    .has_arg = no_argument },
5970         { .val = 'D',   .name = "default",      .has_arg = no_argument },
5971         { .val = 'E',   .name = "comp-end",     .has_arg = optional_argument },
5972         { .val = 'E',   .name = "component-end", .has_arg = optional_argument },
5973         { .val = 'F',   .name = "fid",          .has_arg = no_argument },
5974         { .val = 'g',   .name = "generation",   .has_arg = no_argument },
5975 /* find { .val = 'G',   .name = "group",        .has_arg = required_argument }*/
5976         { .val = 'h',   .name = "help",         .has_arg = no_argument },
5977 /* dirstripe { .val = 'H', .name = "mdt-hash",  .has_arg = required_argument }*/
5978         { .val = 'i',   .name = "stripe-index", .has_arg = no_argument },
5979         { .val = 'i',   .name = "stripe_index", .has_arg = no_argument },
5980         { .val = 'I',   .name = "comp-id",      .has_arg = optional_argument },
5981         { .val = 'I',   .name = "component-id", .has_arg = optional_argument },
5982 /* find { .val = 'l',   .name = "lazy",         .has_arg = no_argument }, */
5983         { .val = 'L',   .name = "layout",       .has_arg = no_argument },
5984         { .val = 'm',   .name = "mdt",          .has_arg = no_argument },
5985         { .val = 'm',   .name = "mdt-index",    .has_arg = no_argument },
5986         { .val = 'm',   .name = "mdt_index",    .has_arg = no_argument },
5987 /* find { .val = 'M',   .name = "mtime",        .has_arg = required_argument }*/
5988 /* find { .val = 'n',   .name = "name",         .has_arg = required_argument }*/
5989         { .val = 'N',   .name = "mirror-count", .has_arg = no_argument },
5990         { .val = 'O',   .name = "obd",          .has_arg = required_argument },
5991         { .val = 'O',   .name = "ost",          .has_arg = required_argument },
5992         { .val = 'p',   .name = "pool",         .has_arg = no_argument },
5993 /* find { .val = 'P',   .name = "print",        .has_arg = no_argument }, */
5994         { .val = 'q',   .name = "quiet",        .has_arg = no_argument },
5995         { .val = 'r',   .name = "recursive",    .has_arg = no_argument },
5996         { .val = 'R',   .name = "raw",          .has_arg = no_argument },
5997         { .val = 'S',   .name = "stripe-size",  .has_arg = no_argument },
5998         { .val = 'S',   .name = "stripe_size",  .has_arg = no_argument },
5999 /* find { .val = 't',   .name = "type",         .has_arg = required_argument }*/
6000 /* dirstripe { .val = 'T', .name = "mdt-count", .has_arg = required_argument }*/
6001 /* find { .val = 'u',   .name = "uid",          .has_arg = required_argument }*/
6002 /* find { .val = 'U',   .name = "user",         .has_arg = required_argument }*/
6003         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
6004 /* dirstripe { .val = 'X',.name = "max-inherit",.has_arg = required_argument }*/
6005 /* setstripe { .val = 'W', .name = "bandwidth", .has_arg = required_argument }*/
6006         { .val = 'y',   .name = "yaml",         .has_arg = no_argument },
6007         { .val = 'z',   .name = "extension-size", .has_arg = no_argument },
6008         { .val = 'z',   .name = "ext-size",     .has_arg = no_argument },
6009         { .name = NULL } };
6010         int c, rc;
6011         int neg_opt = 0;
6012         int pathstart = -1, pathend = -1;
6013         int isoption;
6014         char *end, *tmp;
6015
6016         while ((c = getopt_long(argc, argv,
6017                         "-cdDE::FghiI::LmMNoO:pqrRsSvyz",
6018                         long_opts, NULL)) != -1) {
6019                 if (neg_opt)
6020                         --neg_opt;
6021
6022                 /* '!' is part of option */
6023                 isoption = (c != 1) || (strcmp(optarg, "!") == 0);
6024                 if (!isoption && pathend != -1) {
6025                         fprintf(stderr,
6026                                 "error: %s: filename|dirname must either precede options or follow options\n",
6027                                 argv[0]);
6028                         return CMD_HELP;
6029                 }
6030                 if (!isoption && pathstart == -1)
6031                         pathstart = optind - 1;
6032                 if (isoption && pathstart != -1 && pathend == -1)
6033                         pathend = optind - 2;
6034
6035                 switch (c) {
6036                 case 1:
6037                         /* unknown: opt is "!" */
6038                         if (strcmp(optarg, "!") == 0)
6039                                 neg_opt = 2;
6040                         break;
6041                 case 'c':
6042                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6043                                 param->fp_verbose |= VERBOSE_COUNT;
6044                                 param->fp_max_depth = 0;
6045                         }
6046                         break;
6047                 case LFS_COMP_COUNT_OPT:
6048                         param->fp_verbose |= VERBOSE_COMP_COUNT;
6049                         param->fp_max_depth = 0;
6050                         break;
6051                 case LFS_COMP_FLAGS_OPT:
6052                         if (optarg) {
6053                                 rc = comp_str2flags(optarg,
6054                                                     &param->fp_comp_flags,
6055                                                     &param->fp_comp_neg_flags);
6056                                 if (rc != 0) {
6057                                         fprintf(stderr,
6058                                                 "error: %s bad component flags '%s'.\n",
6059                                                 argv[0], optarg);
6060                                         return CMD_HELP;
6061                                 }
6062                                 param->fp_check_comp_flags = 1;
6063                         } else {
6064                                 param->fp_verbose |= VERBOSE_COMP_FLAGS;
6065                                 param->fp_max_depth = 0;
6066                         }
6067                         break;
6068                 case LFS_COMP_START_OPT:
6069                         if (optarg) {
6070                                 tmp = optarg;
6071                                 if (tmp[0] == '+') {
6072                                         param->fp_comp_start_sign = -1;
6073                                         tmp++;
6074                                 } else if (tmp[0] == '-') {
6075                                         param->fp_comp_start_sign = 1;
6076                                         tmp++;
6077                                 }
6078                                 rc = llapi_parse_size(tmp,
6079                                                 &param->fp_comp_start,
6080                                                 &param->fp_comp_start_units, 0);
6081                                 if (rc != 0) {
6082                                         fprintf(stderr,
6083                                                 "error: %s bad component start '%s'.\n",
6084                                                 argv[0], tmp);
6085                                         return CMD_HELP;
6086                                 }
6087                                 param->fp_check_comp_start = 1;
6088                         } else {
6089                                 param->fp_verbose |= VERBOSE_COMP_START;
6090                                 param->fp_max_depth = 0;
6091                         }
6092                         break;
6093                 case LFS_MIRROR_INDEX_OPT: {
6094                         unsigned long int mirror_index;
6095
6096                         if (optarg[0] == '+') {
6097                                 param->fp_mirror_index_sign = -1;
6098                                 optarg++;
6099                         } else if (optarg[0] == '-') {
6100                                 param->fp_mirror_index_sign = 1;
6101                                 optarg++;
6102                         }
6103
6104                         errno = 0;
6105                         mirror_index = strtoul(optarg, &end, 0);
6106                         if (errno != 0 || *end != '\0' ||
6107                             mirror_index > UINT16_MAX || (mirror_index == 0 &&
6108                             param->fp_mirror_index_sign == 0 && neg_opt == 0)) {
6109                                 fprintf(stderr,
6110                                         "%s %s: invalid mirror index '%s'\n",
6111                                         progname, argv[0], optarg);
6112                                 return CMD_HELP;
6113                         }
6114
6115                         param->fp_mirror_index = (__u16)mirror_index;
6116
6117                         if (param->fp_mirror_id != 0) {
6118                                 fprintf(stderr,
6119                                         "%s %s: can't specify both mirror index and mirror ID\n",
6120                                         progname, argv[0]);
6121                                 return CMD_HELP;
6122                         }
6123                         param->fp_check_mirror_index = 1;
6124                         param->fp_exclude_mirror_index = !!neg_opt;
6125                         break;
6126                 }
6127                 case LFS_MIRROR_ID_OPT: {
6128                         unsigned long int mirror_id;
6129
6130                         if (optarg[0] == '+') {
6131                                 param->fp_mirror_id_sign = -1;
6132                                 optarg++;
6133                         } else if (optarg[0] == '-') {
6134                                 param->fp_mirror_id_sign = 1;
6135                                 optarg++;
6136                         }
6137
6138                         errno = 0;
6139                         mirror_id = strtoul(optarg, &end, 0);
6140                         if (errno != 0 || *end != '\0' ||
6141                             mirror_id > UINT16_MAX || (mirror_id == 0 &&
6142                             param->fp_mirror_id_sign == 0 && neg_opt == 0)) {
6143                                 fprintf(stderr,
6144                                         "%s %s: invalid mirror ID '%s'\n",
6145                                         progname, argv[0], optarg);
6146                                 return CMD_HELP;
6147                         }
6148
6149                         param->fp_mirror_id = (__u16)mirror_id;
6150
6151                         if (param->fp_mirror_index != 0) {
6152                                 fprintf(stderr,
6153                                         "%s %s: can't specify both mirror index and mirror ID\n",
6154                                         progname, argv[0]);
6155                                 return CMD_HELP;
6156                         }
6157                         param->fp_check_mirror_id = 1;
6158                         param->fp_exclude_mirror_id = !!neg_opt;
6159                         break;
6160                 }
6161                 case LFS_NO_FOLLOW_OPT:
6162                         param->fp_no_follow = true;
6163                         break;
6164                 case 'd':
6165                         param->fp_max_depth = 0;
6166                         break;
6167                 case 'D':
6168                         param->fp_get_default_lmv = 1;
6169                         break;
6170                 case 'E':
6171                         if (optarg) {
6172                                 tmp = optarg;
6173                                 if (tmp[0] == '+') {
6174                                         param->fp_comp_end_sign = -1;
6175                                         tmp++;
6176                                 } else if (tmp[0] == '-') {
6177                                         param->fp_comp_end_sign = 1;
6178                                         tmp++;
6179                                 }
6180
6181                                 if (arg_is_eof(tmp)) {
6182                                         param->fp_comp_end = LUSTRE_EOF;
6183                                         param->fp_comp_end_units = 1;
6184                                         rc = 0;
6185                                 } else {
6186                                         rc = llapi_parse_size(tmp,
6187                                                 &param->fp_comp_end,
6188                                                 &param->fp_comp_end_units, 0);
6189                                         /* assume units of KB if too small */
6190                                         if (param->fp_comp_end < 4096)
6191                                                 param->fp_comp_end *= 1024;
6192                                 }
6193                                 if (rc != 0) {
6194                                         fprintf(stderr,
6195                                                 "error: %s bad component end '%s'.\n",
6196                                                 argv[0], tmp);
6197                                         return CMD_HELP;
6198                                 }
6199                                 param->fp_check_comp_end = 1;
6200                         } else {
6201                                 param->fp_verbose |= VERBOSE_COMP_END;
6202                                 param->fp_max_depth = 0;
6203                         }
6204                         break;
6205                 case 'F':
6206                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6207                                 param->fp_verbose |= VERBOSE_DFID;
6208                                 param->fp_max_depth = 0;
6209                         }
6210                         break;
6211                 case 'g':
6212                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6213                                 param->fp_verbose |= VERBOSE_GENERATION;
6214                                 param->fp_max_depth = 0;
6215                         }
6216                         break;
6217                 case 'i':
6218                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6219                                 param->fp_verbose |= VERBOSE_STRIPE_OFFSET;
6220                                 param->fp_max_depth = 0;
6221                         }
6222                         break;
6223                 case 'I':
6224                         if (optarg) {
6225                                 param->fp_comp_id = strtoul(optarg, &end, 0);
6226                                 if (*end != '\0' || param->fp_comp_id == 0 ||
6227                                     param->fp_comp_id > LCME_ID_MAX) {
6228                                         fprintf(stderr,
6229                                                 "error: %s bad component id '%s'\n",
6230                                                 argv[0], optarg);
6231                                         return CMD_HELP;
6232                                 }
6233                                 param->fp_check_comp_id = 1;
6234                         } else {
6235                                 param->fp_max_depth = 0;
6236                                 param->fp_verbose |= VERBOSE_COMP_ID;
6237                         }
6238                         break;
6239                 case 'L':
6240                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6241                                 param->fp_verbose |= VERBOSE_PATTERN;
6242                                 param->fp_max_depth = 0;
6243                         }
6244                         break;
6245 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
6246                 case 'M':
6247                         fprintf(stderr,
6248                                 "warning: '-M' deprecated, use '--mdt-index' or '-m' instead\n");
6249 #endif
6250                 case 'm':
6251                         if (!(param->fp_verbose & VERBOSE_DETAIL))
6252                                 param->fp_max_depth = 0;
6253                         param->fp_verbose |= VERBOSE_MDTINDEX;
6254                         break;
6255                 case 'N':
6256                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6257                                 param->fp_verbose |= VERBOSE_MIRROR_COUNT;
6258                                 param->fp_max_depth = 0;
6259                         }
6260                         break;
6261                 case 'O':
6262                         if (param->fp_obd_uuid) {
6263                                 fprintf(stderr,
6264                                         "error: %s: only one obduuid allowed",
6265                                         argv[0]);
6266                                 return CMD_HELP;
6267                         }
6268                         param->fp_obd_uuid = (struct obd_uuid *)optarg;
6269                         break;
6270                 case 'p':
6271                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6272                                 param->fp_verbose |= VERBOSE_POOL;
6273                                 param->fp_max_depth = 0;
6274                         }
6275                         break;
6276                 case 'q':
6277                         param->fp_quiet++;
6278                         break;
6279                 case 'r':
6280                         param->fp_recursive = 1;
6281                         break;
6282                 case 'R':
6283                         param->fp_raw = 1;
6284                         break;
6285                 case 'S':
6286                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6287                                 param->fp_verbose |= VERBOSE_STRIPE_SIZE;
6288                                 param->fp_max_depth = 0;
6289                         }
6290                         break;
6291                 case 'v':
6292                         param->fp_verbose = VERBOSE_DEFAULT | VERBOSE_DETAIL;
6293                         break;
6294                 case 'y':
6295                         param->fp_yaml = 1;
6296                         break;
6297                 case 'z':
6298                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6299                                 param->fp_verbose |= VERBOSE_EXT_SIZE;
6300                                 param->fp_max_depth = 0;
6301                         }
6302                         break;
6303                 default:
6304                         fprintf(stderr, "%s: unrecognized option '%s'\n",
6305                                 progname, argv[optind - 1]);
6306                 case 'h':
6307                         return CMD_HELP;
6308                 }
6309         }
6310
6311         if (pathstart == -1) {
6312                 fprintf(stderr, "error: %s: no filename|pathname\n",
6313                                 argv[0]);
6314                 return CMD_HELP;
6315         } else if (pathend == -1) {
6316                 /* no options */
6317                 pathend = argc;
6318         }
6319
6320         if (pathend > argc)
6321                 return CMD_HELP;
6322
6323         if (param->fp_recursive)
6324                 param->fp_max_depth = -1;
6325         else if (param->fp_verbose & VERBOSE_DETAIL)
6326                 param->fp_max_depth = 1;
6327
6328         if (!param->fp_verbose)
6329                 param->fp_verbose = VERBOSE_DEFAULT;
6330         if (param->fp_quiet)
6331                 param->fp_verbose = VERBOSE_OBJID;
6332
6333         do {
6334                 rc = llapi_getstripe(argv[pathstart], param);
6335         } while (++pathstart < pathend && !rc);
6336
6337         if (rc)
6338                 fprintf(stderr, "error: %s failed for %s.\n",
6339                         argv[0], argv[optind - 1]);
6340         return rc;
6341 }
6342
6343 static int lfs_tgts(int argc, char **argv)
6344 {
6345         char mntdir[PATH_MAX] = {'\0'}, path[PATH_MAX] = {'\0'};
6346         struct find_param param;
6347         int index = 0, rc = 0;
6348
6349         if (argc > 2)
6350                 return CMD_HELP;
6351
6352         if (argc == 2 && !realpath(argv[1], path)) {
6353                 rc = -errno;
6354                 fprintf(stderr, "error: invalid path '%s': %s\n",
6355                         argv[1], strerror(-rc));
6356                 return rc;
6357         }
6358
6359         while (!llapi_search_mounts(path, index++, mntdir, NULL)) {
6360                 /* Check if we have a mount point */
6361                 if (mntdir[0] == '\0')
6362                         continue;
6363
6364                 memset(&param, 0, sizeof(param));
6365                 if (!strcmp(argv[0], "mdts"))
6366                         param.fp_get_lmv = 1;
6367
6368                 rc = llapi_ostlist(mntdir, &param);
6369                 if (rc) {
6370                         fprintf(stderr, "error: %s: failed on %s\n",
6371                                 argv[0], mntdir);
6372                 }
6373                 if (path[0] != '\0')
6374                         break;
6375                 memset(mntdir, 0, PATH_MAX);
6376         }
6377
6378         return rc;
6379 }
6380
6381 static int lfs_getstripe(int argc, char **argv)
6382 {
6383         struct find_param param = { 0 };
6384
6385         param.fp_max_depth = 1;
6386         return lfs_getstripe_internal(argc, argv, &param);
6387 }
6388
6389 /* functions */
6390 static int lfs_getdirstripe(int argc, char **argv)
6391 {
6392         struct find_param param = { 0 };
6393         struct option long_opts[] = {
6394         { .val = 'c',   .name = "mdt-count",     .has_arg = no_argument },
6395         { .val = 'D',   .name = "default",       .has_arg = no_argument },
6396         { .val = 'h',   .name = "help",         .has_arg = no_argument },
6397         { .val = 'H',   .name = "mdt-hash",      .has_arg = no_argument },
6398         { .val = 'i',   .name = "mdt-index",     .has_arg = no_argument },
6399         { .val = 'm',   .name = "mdt-index",     .has_arg = no_argument },
6400         { .val = 'O',   .name = "obd",           .has_arg = required_argument },
6401         { .val = 'r',   .name = "recursive",     .has_arg = no_argument },
6402         { .val = 'T',   .name = "mdt-count",     .has_arg = no_argument },
6403         { .val = 'v',   .name = "verbose",       .has_arg = no_argument },
6404         { .val = 'X',   .name = "max-inherit",   .has_arg = no_argument },
6405         { .val = 'y',   .name = "yaml",          .has_arg = no_argument },
6406         { .val = LFS_INHERIT_RR_OPT,
6407                         .name = "max-inherit-rr", .has_arg = no_argument },
6408         { .name = NULL } };
6409         int c, rc;
6410
6411         param.fp_get_lmv = 1;
6412
6413         while ((c = getopt_long(argc, argv,
6414                                 "cDhHimO:rtTvXy", long_opts, NULL)) != -1) {
6415                 switch (c) {
6416                 case 'c':
6417                 case 'T':
6418                         param.fp_verbose |= VERBOSE_COUNT;
6419                         break;
6420                 case 'D':
6421                         param.fp_get_default_lmv = 1;
6422                         break;
6423 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
6424                 case 't':
6425                         fprintf(stderr,
6426                                 "warning: '-t' deprecated, use '--mdt-hash' or '-H' instead\n");
6427                         fallthrough;
6428 #endif
6429                 case 'H':
6430                         param.fp_verbose |= VERBOSE_HASH_TYPE;
6431                         break;
6432                 case 'i':
6433                         fallthrough;
6434                 case 'm':
6435                         param.fp_verbose |= VERBOSE_STRIPE_OFFSET;
6436                         break;
6437                 case 'O':
6438                         if (param.fp_obd_uuid) {
6439                                 fprintf(stderr,
6440                                         "%s: only one obduuid allowed",
6441                                         progname);
6442                                 return CMD_HELP;
6443                         }
6444                         param.fp_obd_uuid = (struct obd_uuid *)optarg;
6445                         break;
6446                 case 'r':
6447                         param.fp_recursive = 1;
6448                         break;
6449                 case 'v':
6450                         param.fp_verbose |= VERBOSE_DETAIL;
6451                         break;
6452                 case 'X':
6453                         param.fp_verbose |= VERBOSE_INHERIT;
6454                         break;
6455                 case LFS_INHERIT_RR_OPT:
6456                         param.fp_verbose |= VERBOSE_INHERIT_RR;
6457                         break;
6458                 case 'y':
6459                         param.fp_yaml = 1;
6460                         break;
6461                 default:
6462                         fprintf(stderr, "%s: unrecognized option '%s'\n",
6463                                 progname, argv[optind - 1]);
6464                         fallthrough;
6465                 case 'h':
6466                         return CMD_HELP;
6467                 }
6468         }
6469
6470         if (optind >= argc)
6471                 return CMD_HELP;
6472
6473         if (param.fp_recursive)
6474                 param.fp_max_depth = -1;
6475
6476         if (!param.fp_verbose)
6477                 param.fp_verbose = VERBOSE_DEFAULT;
6478
6479         do {
6480                 rc = llapi_getstripe(argv[optind], &param);
6481         } while (++optind < argc && !rc);
6482
6483         if (rc)
6484                 fprintf(stderr, "error: %s failed for %s.\n",
6485                         argv[0], argv[optind - 1]);
6486         return rc;
6487 }
6488
6489 enum mntdf_flags {
6490         MNTDF_INODES    = 0x0001,
6491         MNTDF_COOKED    = 0x0002,
6492         MNTDF_LAZY      = 0x0004,
6493         MNTDF_VERBOSE   = 0x0008,
6494         MNTDF_SHOW      = 0x0010,
6495         MNTDF_DECIMAL   = 0x0020,
6496 };
6497
6498 #define COOK(value, base)                                       \
6499 ({                                                              \
6500         int radix = 0;                                          \
6501         while (value > base) {                                  \
6502                 value /= base;                                  \
6503                 radix++;                                        \
6504         }                                                       \
6505         radix;                                                  \
6506 })
6507 #define UUF     "%-20s"
6508 #define CSF     "%11s"
6509 #define CDF     "%11llu"
6510 #define HDF     "%8.1f%c"
6511 #define RSF     "%4s"
6512 #define RDF     "%3d%%"
6513
6514 static inline int obd_statfs_ratio(const struct obd_statfs *st, bool inodes)
6515 {
6516         double avail, used, ratio = 0;
6517
6518         if (inodes) {
6519                 avail = st->os_ffree;
6520                 used = st->os_files - st->os_ffree;
6521         } else {
6522                 avail = st->os_bavail;
6523                 used = st->os_blocks - st->os_bfree;
6524         }
6525         if (avail + used > 0)
6526                 ratio = used / (used + avail) * 100;
6527
6528         /* Round up to match df(1) usage percentage */
6529         return (ratio - (int)ratio) > 0 ? (int)(ratio + 1) : (int)ratio;
6530 }
6531
6532 /*
6533  * This is to identify various problem states for "lfs df" if .osn_err = true,
6534  * so only show flags reflecting those states by default. Informational states
6535  * are only shown with "-v" and use lower-case names to distinguish them.
6536  * UNUSED[12] were for "EROFS = 30" until 1.6 but are now available for use.
6537  */
6538 static struct obd_statfs_state_names {
6539         enum obd_statfs_state   osn_state;
6540         const char              osn_name;
6541         bool                    osn_err;
6542 } oss_names[] = {
6543         { .osn_state = OS_STATFS_DEGRADED,   .osn_name = 'D', .osn_err = true },
6544         { .osn_state = OS_STATFS_READONLY,   .osn_name = 'R', .osn_err = true },
6545         { .osn_state = OS_STATFS_NOPRECREATE,.osn_name = 'N', .osn_err = true },
6546         { .osn_state = OS_STATFS_UNUSED1,    .osn_name = '?', .osn_err = true },
6547         { .osn_state = OS_STATFS_UNUSED2,    .osn_name = '?', .osn_err = true },
6548         { .osn_state = OS_STATFS_ENOSPC,     .osn_name = 'S', .osn_err = true },
6549         { .osn_state = OS_STATFS_ENOINO,     .osn_name = 'I', .osn_err = true },
6550         { .osn_state = OS_STATFS_SUM,        .osn_name = 'a', /* aggregate */ },
6551         { .osn_state = OS_STATFS_NONROT,     .osn_name = 'f', /* flash */     },
6552 };
6553
6554 static int showdf(char *mntdir, struct obd_statfs *stat,
6555                   char *uuid, enum mntdf_flags flags,
6556                   char *type, int index, int rc)
6557 {
6558         long long avail, used, total;
6559         int ratio = 0;
6560         char *suffix = flags & MNTDF_DECIMAL ? "kMGTPEZY" : "KMGTPEZY";
6561         /* Note if we have >2^64 bytes/fs these buffers will need to be grown */
6562         char tbuf[3 * sizeof(__u64)];
6563         char ubuf[3 * sizeof(__u64)];
6564         char abuf[3 * sizeof(__u64)];
6565         char rbuf[3 * sizeof(__u64)];
6566
6567         if (!uuid || !stat)
6568                 return -EINVAL;
6569
6570         switch (rc) {
6571         case 0:
6572                 if (flags & MNTDF_INODES) {
6573                         avail = stat->os_ffree;
6574                         used = stat->os_files - stat->os_ffree;
6575                         total = stat->os_files;
6576                 } else {
6577                         int shift = flags & MNTDF_COOKED ? 0 : 10;
6578
6579                         avail = (stat->os_bavail * stat->os_bsize) >> shift;
6580                         used  = ((stat->os_blocks - stat->os_bfree) *
6581                                  stat->os_bsize) >> shift;
6582                         total = (stat->os_blocks * stat->os_bsize) >> shift;
6583                 }
6584
6585                 ratio = obd_statfs_ratio(stat, flags & MNTDF_INODES);
6586
6587                 if (flags & MNTDF_COOKED) {
6588                         int base = flags & MNTDF_DECIMAL ? 1000 : 1024;
6589                         double cook_val;
6590                         int i;
6591
6592                         cook_val = (double)total;
6593                         i = COOK(cook_val, base);
6594                         if (i > 0)
6595                                 snprintf(tbuf, sizeof(tbuf), HDF, cook_val,
6596                                          suffix[i - 1]);
6597                         else
6598                                 snprintf(tbuf, sizeof(tbuf), CDF, total);
6599
6600                         cook_val = (double)used;
6601                         i = COOK(cook_val, base);
6602                         if (i > 0)
6603                                 snprintf(ubuf, sizeof(ubuf), HDF, cook_val,
6604                                          suffix[i - 1]);
6605                         else
6606                                 snprintf(ubuf, sizeof(ubuf), CDF, used);
6607
6608                         cook_val = (double)avail;
6609                         i = COOK(cook_val, base);
6610                         if (i > 0)
6611                                 snprintf(abuf, sizeof(abuf), HDF, cook_val,
6612                                          suffix[i - 1]);
6613                         else
6614                                 snprintf(abuf, sizeof(abuf), CDF, avail);
6615                 } else {
6616                         snprintf(tbuf, sizeof(tbuf), CDF, total);
6617                         snprintf(ubuf, sizeof(tbuf), CDF, used);
6618                         snprintf(abuf, sizeof(tbuf), CDF, avail);
6619                 }
6620
6621                 sprintf(rbuf, RDF, ratio);
6622                 printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s",
6623                        uuid, tbuf, ubuf, abuf, rbuf, mntdir);
6624                 if (type)
6625                         printf("[%s:%d]", type, index);
6626
6627                 if (stat->os_state) {
6628                         uint32_t i;
6629
6630                         printf(" ");
6631                         for (i = 0; i < ARRAY_SIZE(oss_names); i++) {
6632                                 if (oss_names[i].osn_state & stat->os_state &&
6633                                     (oss_names[i].osn_err ||
6634                                      flags & MNTDF_VERBOSE))
6635                                         printf("%c", oss_names[i].osn_name);
6636                         }
6637                 }
6638
6639                 printf("\n");
6640                 break;
6641         case -ENODATA:
6642                 printf(UUF": inactive device\n", uuid);
6643                 break;
6644         default:
6645                 printf(UUF": %s\n", uuid, strerror(-rc));
6646                 break;
6647         }
6648
6649         return 0;
6650 }
6651
6652 struct ll_stat_type {
6653         int   st_op;
6654         char *st_name;
6655 };
6656
6657 #define LL_STATFS_MAX   LOV_MAX_STRIPE_COUNT
6658
6659 struct ll_statfs_data {
6660         int                     sd_index;
6661         struct obd_statfs       sd_st;
6662 };
6663
6664 struct ll_statfs_buf {
6665         int                     sb_count;
6666         struct ll_statfs_data   sb_buf[LL_STATFS_MAX];
6667 };
6668
6669 static int mntdf(char *mntdir, char *fsname, char *pool, enum mntdf_flags flags,
6670                  int ops, struct ll_statfs_buf *lsb)
6671 {
6672         struct obd_statfs stat_buf, sum = { .os_bsize = 1 };
6673         struct obd_uuid uuid_buf;
6674         char *poolname = NULL;
6675         struct ll_stat_type types[] = {
6676                 { .st_op = LL_STATFS_LMV,       .st_name = "MDT" },
6677                 { .st_op = LL_STATFS_LOV,       .st_name = "OST" },
6678                 { .st_name = NULL } };
6679         struct ll_stat_type *tp;
6680         __u64 ost_files = 0;
6681         __u64 ost_ffree = 0;
6682         __u32 index;
6683         __u32 type;
6684         int fd;
6685         int rc = 0;
6686         int rc2;
6687
6688         if (pool) {
6689                 poolname = strchr(pool, '.');
6690                 if (poolname) {
6691                         if (strncmp(fsname, pool, strlen(fsname))) {
6692                                 fprintf(stderr, "filesystem name incorrect\n");
6693                                 return -ENODEV;
6694                         }
6695                         poolname++;
6696                 } else
6697                         poolname = pool;
6698         }
6699
6700         fd = open(mntdir, O_RDONLY);
6701         if (fd < 0) {
6702                 rc = -errno;
6703                 fprintf(stderr, "%s: cannot open '%s': %s\n", progname, mntdir,
6704                         strerror(errno));
6705                 return rc;
6706         }
6707
6708         if (flags & MNTDF_SHOW) {
6709                 if (flags & MNTDF_INODES)
6710                         printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s\n",
6711                                "UUID", "Inodes", "IUsed", "IFree",
6712                                "IUse%", "Mounted on");
6713                 else
6714                         printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s\n",
6715                                "UUID",
6716                                flags & MNTDF_COOKED ? "bytes" : "1K-blocks",
6717                                "Used", "Available", "Use%", "Mounted on");
6718         }
6719
6720         for (tp = types; tp->st_name != NULL; tp++) {
6721                 bool have_ost = false;
6722
6723                 if (!(tp->st_op & ops))
6724                         continue;
6725
6726                 for (index = 0; index < LOV_ALL_STRIPES &&
6727                      (!lsb || lsb->sb_count < LL_STATFS_MAX); index++) {
6728                         memset(&stat_buf, 0, sizeof(struct obd_statfs));
6729                         memset(&uuid_buf, 0, sizeof(struct obd_uuid));
6730                         type = flags & MNTDF_LAZY ?
6731                                 tp->st_op | LL_STATFS_NODELAY : tp->st_op;
6732                         rc2 = llapi_obd_fstatfs(fd, type, index,
6733                                                 &stat_buf, &uuid_buf);
6734                         if (rc2 == -ENODEV)
6735                                 break;
6736                         if (rc2 == -EAGAIN)
6737                                 continue;
6738                         if (rc2 == -ENODATA) { /* Inactive device, OK. */
6739                                 if (!(flags & MNTDF_VERBOSE))
6740                                         continue;
6741                         } else if (rc2 < 0 && rc == 0) {
6742                                 rc = rc2;
6743                         }
6744
6745                         /*
6746                          * If we have OSTs then don't report MDT block counts.
6747                          * For MDT-only filesystems the expectation is that all
6748                          * layouts have a DoM component.  For filesystems with
6749                          * OSTs, files are not necessarily going to store data
6750                          * on MDTs, and MDT space is limited to a fraction of
6751                          * OST space, so don't include it in the summary.
6752                          */
6753                         if (tp->st_op == LL_STATFS_LOV && !have_ost) {
6754                                 have_ost = true;
6755                                 sum.os_blocks = 0;
6756                                 sum.os_bfree = 0;
6757                                 sum.os_bavail = 0;
6758                         }
6759
6760                         if (poolname && tp->st_op == LL_STATFS_LOV &&
6761                             llapi_search_ost(fsname, poolname,
6762                                              obd_uuid2str(&uuid_buf)) != 1)
6763                                 continue;
6764
6765                         /*
6766                          * the llapi_obd_fstatfs() call may have returned with
6767                          * an error, but if it filled in uuid_buf we will at
6768                          * lease use that to print out a message for that OBD.
6769                          * If we didn't get anything in the uuid_buf, then fill
6770                          * it in so that we can print an error message.
6771                          */
6772                         if (uuid_buf.uuid[0] == '\0')
6773                                 snprintf(uuid_buf.uuid, sizeof(uuid_buf.uuid),
6774                                          "%s%04x", tp->st_name, index);
6775                         if (!rc && lsb) {
6776                                 lsb->sb_buf[lsb->sb_count].sd_index = index;
6777                                 lsb->sb_buf[lsb->sb_count].sd_st = stat_buf;
6778                                 lsb->sb_count++;
6779                         }
6780                         if (flags & MNTDF_SHOW)
6781                                 showdf(mntdir, &stat_buf,
6782                                        obd_uuid2str(&uuid_buf), flags,
6783                                        tp->st_name, index, rc2);
6784
6785                         if (rc2)
6786                                 continue;
6787
6788                         if (tp->st_op == LL_STATFS_LMV) {
6789                                 sum.os_ffree += stat_buf.os_ffree;
6790                                 sum.os_files += stat_buf.os_files;
6791                         } else /* if (tp->st_op == LL_STATFS_LOV) */ {
6792                                 ost_files += stat_buf.os_files;
6793                                 ost_ffree += stat_buf.os_ffree;
6794                         }
6795                         sum.os_blocks += stat_buf.os_blocks *
6796                                          stat_buf.os_bsize;
6797                         sum.os_bfree  += stat_buf.os_bfree *
6798                                          stat_buf.os_bsize;
6799                         sum.os_bavail += stat_buf.os_bavail *
6800                                          stat_buf.os_bsize;
6801                 }
6802         }
6803
6804         close(fd);
6805
6806         /*
6807          * If we have _some_ OSTs, but don't have as many free objects on the
6808          * OST as inodes on the MDTs, reduce the reported number of inodes
6809          * to compensate, so that the "inodes in use" number is correct.
6810          * This should be kept in sync with ll_statfs_internal().
6811          */
6812         if (ost_files && ost_ffree < sum.os_ffree) {
6813                 sum.os_files = (sum.os_files - sum.os_ffree) + ost_ffree;
6814                 sum.os_ffree = ost_ffree;
6815         }
6816         if (flags & MNTDF_SHOW) {
6817                 printf("\n");
6818                 showdf(mntdir, &sum, "filesystem_summary:", flags, NULL, 0, 0);
6819                 printf("\n");
6820         }
6821
6822         return rc;
6823 }
6824
6825 enum {
6826         LAYOUT_INHERIT_UNSET    = -2,
6827 };
6828
6829 /* functions */
6830 static int lfs_setdirstripe(int argc, char **argv)
6831 {
6832         char *dname;
6833         struct lfs_setstripe_args lsa = { 0 };
6834         struct llapi_stripe_param *param = NULL;
6835         __u32 mdts[LMV_MAX_STRIPE_COUNT] = { 0 };
6836         char *end;
6837         int c;
6838         char *mode_opt = NULL;
6839         bool default_stripe = false;
6840         bool delete = false;
6841         bool foreign_mode = false;
6842         bool mdt_count_set = false;
6843         mode_t mode = S_IRWXU | S_IRWXG | S_IRWXO;
6844         mode_t previous_mode = 0;
6845         char *xattr = NULL;
6846         __u32 type = LU_FOREIGN_TYPE_SYMLINK, flags = 0;
6847         int max_inherit = LAYOUT_INHERIT_UNSET;
6848         int max_inherit_rr = LAYOUT_INHERIT_UNSET;
6849         struct option long_opts[] = {
6850         { .val = 'c',   .name = "count",        .has_arg = required_argument },
6851         { .val = 'c',   .name = "mdt-count",    .has_arg = required_argument },
6852         { .val = 'd',   .name = "delete",       .has_arg = no_argument },
6853         { .val = 'D',   .name = "default",      .has_arg = no_argument },
6854         { .val = 'D',   .name = "default_stripe", .has_arg = no_argument },
6855         { .val = LFS_LAYOUT_FLAGS_OPT,
6856                         .name = "flags",        .has_arg = required_argument },
6857         { .val = LFS_LAYOUT_FOREIGN_OPT,
6858                         .name = "foreign",      .has_arg = optional_argument},
6859         { .val = 'h',   .name = "help",         .has_arg = no_argument },
6860         { .val = 'H',   .name = "mdt-hash",     .has_arg = required_argument },
6861 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 17, 53, 0)
6862         { .val = 'i',   .name = "mdt-index",    .has_arg = required_argument },
6863         { .val = 'i',   .name = "mdt",          .has_arg = required_argument },
6864 #else
6865 /* find { .val = 'l',   .name = "lazy",         .has_arg = no_argument }, */
6866         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument },
6867         { .val = 'm',   .name = "mdt",          .has_arg = required_argument },
6868 #endif
6869 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
6870         { .val = 'i',   .name = "index",        .has_arg = required_argument },
6871 #endif
6872         { .val = 'o',   .name = "mode",         .has_arg = required_argument },
6873 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
6874         { .val = 't',   .name = "hash-type",    .has_arg = required_argument },
6875 #endif
6876         { .val = 'T',   .name = "mdt-count",    .has_arg = required_argument },
6877         { .val = 'x',   .name = "xattr",        .has_arg = required_argument },
6878         { .val = 'X',   .name = "max-inherit",  .has_arg = required_argument },
6879         { .val = LFS_INHERIT_RR_OPT,
6880                         .name = "max-inherit-rr", .has_arg = required_argument},
6881 /* setstripe { .val = 'y', .name = "yaml",      .has_arg = no_argument }, */
6882 /* setstripe { .val = 'W', .name = "bandwidth", .has_arg = required_argument }, */
6883         { .name = NULL } };
6884         int result = 0;
6885
6886         setstripe_args_init(&lsa);
6887
6888         while ((c = getopt_long(argc, argv, "c:dDi:hH:m:o:t:T:x:X:",
6889                                 long_opts, NULL)) >= 0) {
6890                 switch (c) {
6891                 case 0:
6892                         /* Long options. */
6893                         break;
6894                 case 'c':
6895                 case 'T':
6896                         errno = 0;
6897                         lsa.lsa_stripe_count = strtoul(optarg, &end, 0);
6898                         if (errno != 0 || *end != '\0' ||
6899                             lsa.lsa_stripe_count < -1 ||
6900                             lsa.lsa_stripe_count > LOV_MAX_STRIPE_COUNT) {
6901                                 fprintf(stderr,
6902                                         "%s: invalid stripe count '%s'\n",
6903                                         progname, optarg);
6904                                 return CMD_HELP;
6905                         }
6906                         mdt_count_set = true;
6907                         break;
6908                 case 'd':
6909                         delete = true;
6910                         default_stripe = true;
6911                         break;
6912                 case 'D':
6913                         default_stripe = true;
6914                         break;
6915                 case LFS_LAYOUT_FOREIGN_OPT:
6916                         if (optarg) {
6917                                 /* check pure numeric */
6918                                 type = strtoul(optarg, &end, 0);
6919                                 if (*end) {
6920                                         /* check name */
6921                                         type = check_foreign_type_name(optarg);
6922                                         if (type == LU_FOREIGN_TYPE_UNKNOWN) {
6923                                                 fprintf(stderr,
6924                                                         "%s %s: unknown foreign type '%s'\n",
6925                                                         progname, argv[0],
6926                                                         optarg);
6927                                                 return CMD_HELP;
6928                                         }
6929                                 } else if (type >= UINT32_MAX) {
6930                                         fprintf(stderr,
6931                                                 "%s %s: invalid foreign type '%s'\n",
6932                                                 progname, argv[0], optarg);
6933                                         return CMD_HELP;
6934                                 }
6935                         }
6936                         foreign_mode = true;
6937                         break;
6938                 case LFS_LAYOUT_FLAGS_OPT:
6939                         errno = 0;
6940                         flags = strtoul(optarg, &end, 16);
6941                         if (errno != 0 || *end != '\0' ||
6942                             flags >= UINT32_MAX) {
6943                                 fprintf(stderr,
6944                                         "%s %s: invalid hex flags '%s'\n",
6945                                         progname, argv[0], optarg);
6946                                 return CMD_HELP;
6947                         }
6948                         if (!foreign_mode) {
6949                                 fprintf(stderr,
6950                                         "%s %s: hex flags must be specified with --foreign option\n",
6951                                         progname, argv[0]);
6952                                 return CMD_HELP;
6953                         }
6954                         break;
6955 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
6956                 case 't':
6957                         fprintf(stderr,
6958                                 "warning: '--hash-type' and '-t' deprecated, use '--mdt-hash' or '-H' instead\n");
6959                         fallthrough;
6960 #endif
6961                 case 'H':
6962                         lsa.lsa_pattern = check_hashtype(optarg);
6963                         if (lsa.lsa_pattern == 0) {
6964                                 fprintf(stderr,
6965                                         "%s %s: bad directory hash type '%s'\n",
6966                                         progname, argv[0], optarg);
6967                                 return CMD_HELP;
6968                         }
6969                         break;
6970                 case 'i':
6971 #if LUSTRE_VERSION_CODE >= OBD_OCD_VERSION(2, 17, 53, 0)
6972                 case 'm':
6973 #endif
6974 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
6975                         if (strcmp(argv[optind - 1], "--index") == 0)
6976                                 fprintf(stderr,
6977                                         "%s %s: warning: '--index' deprecated, use '--mdt-index' instead\n",
6978                                         progname, argv[0]);
6979 #endif
6980                         lsa.lsa_nr_tgts = parse_targets(mdts,
6981                                                 sizeof(mdts) / sizeof(__u32),
6982                                                 lsa.lsa_nr_tgts, optarg, NULL);
6983                         if (lsa.lsa_nr_tgts < 0) {
6984                                 fprintf(stderr,
6985                                         "%s %s: invalid MDT target(s) '%s'\n",
6986                                         progname, argv[0], optarg);
6987                                 return CMD_HELP;
6988                         }
6989
6990                         lsa.lsa_tgts = mdts;
6991                         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
6992                                 lsa.lsa_stripe_off = mdts[0];
6993                         break;
6994                 case 'o':
6995                         mode_opt = optarg;
6996                         break;
6997                 case 'x':
6998                         xattr = optarg;
6999                         break;
7000                 case 'X':
7001                         errno = 0;
7002                         max_inherit = strtol(optarg, &end, 10);
7003                         if (errno != 0 || *end != '\0' || max_inherit < -2) {
7004                                 fprintf(stderr,
7005                                         "%s %s: invalid max-inherit '%s'\n",
7006                                         progname, argv[0], optarg);
7007                                 return CMD_HELP;
7008                         }
7009                         if (max_inherit == 0) {
7010                                 max_inherit = LMV_INHERIT_NONE;
7011                         } else if (max_inherit == -1) {
7012                                 max_inherit = LMV_INHERIT_UNLIMITED;
7013                         } else if (max_inherit > LMV_INHERIT_MAX) {
7014                                 fprintf(stderr,
7015                                         "%s %s: max-inherit %d exceeds maximum %u\n",
7016                                         progname, argv[0], max_inherit,
7017                                         LMV_INHERIT_MAX);
7018                                 return CMD_HELP;
7019                         }
7020                         break;
7021                 case LFS_INHERIT_RR_OPT:
7022                         if (!default_stripe) {
7023                                 fprintf(stderr,
7024                                         "%s %s: '--max-inherit-rr' must be specified with '-D'\n",
7025                                         progname, argv[0]);
7026                                 return CMD_HELP;
7027                         }
7028                         errno = 0;
7029                         max_inherit_rr = strtol(optarg, &end, 10);
7030                         if (errno != 0 || *end != '\0' || max_inherit_rr < -2) {
7031                                 fprintf(stderr,
7032                                         "%s %s: invalid max-inherit-rr '%s'\n",
7033                                         progname, argv[0], optarg);
7034                                 return CMD_HELP;
7035                         }
7036                         if (max_inherit_rr == 0) {
7037                                 max_inherit_rr = LMV_INHERIT_RR_NONE;
7038                         } else if (max_inherit_rr == -1) {
7039                                 max_inherit_rr = LMV_INHERIT_RR_UNLIMITED;
7040                         } else if (max_inherit_rr > LMV_INHERIT_RR_MAX) {
7041                                 fprintf(stderr,
7042                                         "%s %s: max-inherit-rr %d exceeds maximum %u\n",
7043                                         progname, argv[0], max_inherit_rr,
7044                                         LMV_INHERIT_RR_MAX);
7045                                 return CMD_HELP;
7046                         }
7047                         break;
7048                 default:
7049                         fprintf(stderr, "%s: unrecognized option '%s'\n",
7050                                 progname, argv[optind - 1]);
7051                         fallthrough;
7052                 case 'h':
7053                         return CMD_HELP;
7054                 }
7055         }
7056
7057         if (optind == argc) {
7058                 fprintf(stderr, "%s %s: DIR must be specified\n",
7059                         progname, argv[0]);
7060                 return CMD_HELP;
7061         }
7062
7063         if (xattr && !foreign_mode) {
7064                 /*
7065                  * only print a warning as this is armless and will be
7066                  * ignored
7067                  */
7068                 fprintf(stderr,
7069                         "%s %s: xattr has been specified for non-foreign layout\n",
7070                         progname, argv[0]);
7071         } else if (foreign_mode && !xattr) {
7072                 fprintf(stderr,
7073                         "%s %s: xattr must be provided in foreign mode\n",
7074                         progname, argv[0]);
7075                 return CMD_HELP;
7076         }
7077
7078         if (foreign_mode && (delete || default_stripe || lsa.lsa_nr_tgts ||
7079             lsa.lsa_tgts || setstripe_args_specified(&lsa))) {
7080                 fprintf(stderr,
7081                         "%s %s: only --xattr/--flags/--mode options are valid with --foreign\n",
7082                         progname, argv[0]);
7083                 return CMD_HELP;
7084         }
7085
7086         if (!delete && lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT &&
7087             lsa.lsa_stripe_count == LLAPI_LAYOUT_DEFAULT && !foreign_mode) {
7088                 /* if no parameters set, create directory on least-used MDTs */
7089                 lsa.lsa_stripe_off = LMV_OFFSET_DEFAULT;
7090                 lsa.lsa_stripe_count = 1;
7091         }
7092
7093         if (delete &&
7094             (lsa.lsa_stripe_off != LLAPI_LAYOUT_DEFAULT ||
7095              lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT)) {
7096                 fprintf(stderr,
7097                         "%s %s: cannot specify -d with -c or -i options\n",
7098                         progname, argv[0]);
7099                 return CMD_HELP;
7100         }
7101
7102         if (mode_opt) {
7103                 mode = strtoul(mode_opt, &end, 8);
7104                 if (*end != '\0') {
7105                         fprintf(stderr,
7106                                 "%s %s: bad MODE '%s'\n",
7107                                 progname, argv[0], mode_opt);
7108                         return CMD_HELP;
7109                 }
7110                 previous_mode = umask(0);
7111         }
7112
7113         /* check max-inherit and warn user in some cases */
7114         if (default_stripe &&
7115             (lsa.lsa_stripe_count < 0 || lsa.lsa_stripe_count > 1)) {
7116                 if (max_inherit == LMV_INHERIT_UNLIMITED)
7117                         fprintf(stderr,
7118                         "%s %s: unrecommended max-inherit=-1 when default stripe-count=%lld\n",
7119                         progname, argv[0], lsa.lsa_stripe_count);
7120                 else if (max_inherit > LMV_INHERIT_DEFAULT_STRIPED + 2 &&
7121                          max_inherit != LMV_INHERIT_NONE)
7122                         fprintf(stderr,
7123                                 "%s %s: unrecommended max-inherit=%d when default stripe-count=%lld\n",
7124                                 progname, argv[0], max_inherit,
7125                                 lsa.lsa_stripe_count);
7126         }
7127
7128         if (default_stripe && lsa.lsa_nr_tgts > 1 && !mdt_count_set) {
7129                 fprintf(stderr,
7130                         "%s %s: trying to create unrecommended default striped directory layout,\n"
7131                         "       '-D -i x,y,z' will stripe every new directory across all MDTs,\n"
7132                         "       add -c with the number of MDTs to do this anyway\n",
7133                         progname, argv[0]);
7134                 return CMD_HELP;
7135         }
7136
7137         if (max_inherit_rr != LAYOUT_INHERIT_UNSET &&
7138             lsa.lsa_stripe_off != LLAPI_LAYOUT_DEFAULT &&
7139             lsa.lsa_stripe_off != LMV_OFFSET_DEFAULT) {
7140                 fprintf(stderr,
7141                         "%s %s: max-inherit-rr needs mdt-index=-1, not %lld\n",
7142                         progname, argv[0], lsa.lsa_stripe_off);
7143                 return CMD_HELP;
7144         }
7145
7146         /* foreign LMV/dir case */
7147         if (foreign_mode) {
7148                 if (argc > optind + 1) {
7149                         fprintf(stderr,
7150                                 "%s %s: cannot specify multiple foreign dirs\n",
7151                                 progname, argv[0]);
7152                         return CMD_HELP;
7153                 }
7154
7155                 dname = argv[optind];
7156                 result = llapi_dir_create_foreign(dname, mode, type, flags,
7157                                                   xattr);
7158                 if (result != 0)
7159                         fprintf(stderr,
7160                                 "%s mkdir: can't create foreign dir '%s': %s\n",
7161                                 progname, dname, strerror(-result));
7162                 return result;
7163         }
7164
7165         /*
7166          * initialize stripe parameters, in case param is converted to specific,
7167          * i.e, 'lfs mkdir -i -1 -c N', always allocate space for lsp_tgts.
7168          */
7169         param = calloc(1, offsetof(typeof(*param),
7170                        lsp_tgts[lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT ?
7171                                 lsa.lsa_stripe_count : lsa.lsa_nr_tgts]));
7172         if (!param) {
7173                 fprintf(stderr,
7174                         "%s %s: cannot allocate memory for parameters: %s\n",
7175                         progname, argv[0], strerror(ENOMEM));
7176                 return CMD_HELP;
7177         }
7178
7179         /* if "lfs setdirstripe -D -i -1" is used, assume 1-stripe directory */
7180         if (default_stripe && lsa.lsa_stripe_off == LMV_OFFSET_DEFAULT &&
7181             (lsa.lsa_stripe_count == LLAPI_LAYOUT_DEFAULT ||
7182              lsa.lsa_stripe_count == 0))
7183                 lsa.lsa_stripe_count = 1;
7184         if (lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT)
7185                 param->lsp_stripe_count = lsa.lsa_stripe_count;
7186         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
7187                 param->lsp_stripe_offset = LMV_OFFSET_DEFAULT;
7188         else
7189                 param->lsp_stripe_offset = lsa.lsa_stripe_off;
7190         if (lsa.lsa_pattern != LLAPI_LAYOUT_RAID0)
7191                 param->lsp_stripe_pattern = lsa.lsa_pattern;
7192         else
7193                 param->lsp_stripe_pattern = LMV_HASH_TYPE_UNKNOWN;
7194         param->lsp_pool = lsa.lsa_pool_name;
7195         param->lsp_is_specific = false;
7196         if (max_inherit == LAYOUT_INHERIT_UNSET) {
7197                 if (lsa.lsa_stripe_count == 0 || lsa.lsa_stripe_count == 1)
7198                         max_inherit = LMV_INHERIT_DEFAULT_PLAIN;
7199                 else
7200                         max_inherit = LMV_INHERIT_DEFAULT_STRIPED;
7201         }
7202         param->lsp_max_inherit = max_inherit;
7203         if (default_stripe) {
7204
7205                 if (max_inherit_rr == LAYOUT_INHERIT_UNSET)
7206                         max_inherit_rr = LMV_INHERIT_RR_DEFAULT;
7207                 param->lsp_max_inherit_rr = max_inherit_rr;
7208         }
7209         if (strcmp(argv[0], "mkdir") == 0)
7210                 param->lsp_is_create = true;
7211         if (lsa.lsa_nr_tgts > 1) {
7212                 if (lsa.lsa_stripe_count > 0 &&
7213                     lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT &&
7214                     lsa.lsa_stripe_count != lsa.lsa_nr_tgts) {
7215                         fprintf(stderr,
7216                                 "error: %s: stripe count %lld doesn't match the number of MDTs: %d\n",
7217                                 argv[0], lsa.lsa_stripe_count,
7218                                 lsa.lsa_nr_tgts);
7219                         free(param);
7220                         return CMD_HELP;
7221                 }
7222
7223                 param->lsp_is_specific = true;
7224                 param->lsp_stripe_count = lsa.lsa_nr_tgts;
7225                 memcpy(param->lsp_tgts, mdts, sizeof(*mdts) * lsa.lsa_nr_tgts);
7226         }
7227
7228         dname = argv[optind];
7229         do {
7230                 if (default_stripe) {
7231                         result = llapi_dir_set_default_lmv(dname, param);
7232                         if (result)
7233                                 fprintf(stderr,
7234                                         "%s setdirstripe: cannot set default stripe on dir '%s': %s\n",
7235                                         progname, dname, strerror(-result));
7236                         continue;
7237                 }
7238
7239                 result = llapi_dir_create(dname, mode, param);
7240                 if (result)
7241                         fprintf(stderr,
7242                                 "%s setdirstripe: cannot create dir '%s': %s\n",
7243                                 progname, dname, strerror(-result));
7244         } while (!result && (dname = argv[++optind]));
7245
7246         if (mode_opt)
7247                 umask(previous_mode);
7248
7249         free(param);
7250         return result;
7251 }
7252
7253 /* functions */
7254 static int lfs_rmentry(int argc, char **argv)
7255 {
7256         char *dname;
7257         int   index;
7258         int   result = 0;
7259
7260         if (argc <= 1) {
7261                 fprintf(stderr, "error: %s: missing dirname\n",
7262                         argv[0]);
7263                 return CMD_HELP;
7264         }
7265
7266         index = 1;
7267         dname = argv[index];
7268         while (dname) {
7269                 result = llapi_direntry_remove(dname);
7270                 if (result) {
7271                         fprintf(stderr,
7272                                 "error: %s: remove dir entry '%s' failed\n",
7273                                 argv[0], dname);
7274                         break;
7275                 }
7276                 dname = argv[++index];
7277         }
7278         return result;
7279 }
7280
7281 static int lfs_unlink_foreign(int argc, char **argv)
7282 {
7283         char *name;
7284         int   index;
7285         int   result = 0;
7286
7287         if (argc <= 1) {
7288                 fprintf(stderr, "error: %s: missing pathname\n",
7289                         argv[0]);
7290                 return CMD_HELP;
7291         }
7292
7293         index = 1;
7294         name = argv[index];
7295         while (name != NULL) {
7296                 result = llapi_unlink_foreign(name);
7297                 if (result) {
7298                         fprintf(stderr,
7299                                 "error: %s: unlink foreign entry '%s' failed\n",
7300                                 argv[0], name);
7301                         break;
7302                 }
7303                 name = argv[++index];
7304         }
7305         return result;
7306 }
7307
7308 static int lfs_mv(int argc, char **argv)
7309 {
7310         struct lmv_user_md lmu = { LMV_USER_MAGIC };
7311         struct find_param param = {
7312                 .fp_max_depth = -1,
7313                 .fp_mdt_index = -1,
7314         };
7315         char *end;
7316         int c;
7317         int rc = 0;
7318         struct option long_opts[] = {
7319         { .val = 'm',   .name = "mdt",          .has_arg = required_argument },
7320         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument },
7321         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
7322         { .name = NULL } };
7323
7324         while ((c = getopt_long(argc, argv, "m:M:v", long_opts, NULL)) != -1) {
7325                 switch (c) {
7326 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
7327                 case 'M':
7328                         fprintf(stderr,
7329                                 "warning: '-M' deprecated, use '--mdt-index' or '-m' instead\n");
7330 #endif
7331                 case 'm':
7332                         errno = 0;
7333                         lmu.lum_stripe_offset = strtoul(optarg, &end, 0);
7334                         if (errno != 0 || *end != '\0' ||
7335                             lmu.lum_stripe_offset >= UINT32_MAX) {
7336                                 fprintf(stderr, "%s mv: bad MDT index '%s'\n",
7337                                         progname, optarg);
7338                                 return CMD_HELP;
7339                         }
7340                         break;
7341                 case 'v':
7342                         param.fp_verbose = VERBOSE_DETAIL;
7343                         break;
7344                 default:
7345                         fprintf(stderr, "%s mv: unrecognized option '%s'\n",
7346                                 progname, argv[optind - 1]);
7347                         return CMD_HELP;
7348                 }
7349         }
7350
7351         if (lmu.lum_stripe_offset == LMV_OFFSET_DEFAULT) {
7352                 fprintf(stderr, "%s mv: MDT index must be specified\n",
7353                         progname);
7354                 return CMD_HELP;
7355         }
7356
7357         if (optind >= argc) {
7358                 fprintf(stderr, "%s mv: DIR must be specified\n", progname);
7359                 return CMD_HELP;
7360         }
7361
7362         lmu.lum_hash_type = LMV_HASH_TYPE_UNKNOWN;
7363
7364         /* initialize migrate mdt parameters */
7365         param.fp_lmv_md = &lmu;
7366         param.fp_migrate = 1;
7367         rc = llapi_migrate_mdt(argv[optind], &param);
7368         if (rc != 0)
7369                 fprintf(stderr, "%s mv: cannot migrate '%s' to MDT%04x: %s\n",
7370                         progname, argv[optind], lmu.lum_stripe_offset,
7371                         strerror(-rc));
7372         return rc;
7373 }
7374
7375 static int lfs_osts(int argc, char **argv)
7376 {
7377         return lfs_tgts(argc, argv);
7378 }
7379
7380 static int lfs_mdts(int argc, char **argv)
7381 {
7382         return lfs_tgts(argc, argv);
7383 }
7384
7385 static int lfs_df(int argc, char **argv)
7386 {
7387         char mntdir[PATH_MAX] = {'\0'}, path[PATH_MAX] = {'\0'};
7388         enum mntdf_flags flags = MNTDF_SHOW;
7389         int ops = LL_STATFS_LMV | LL_STATFS_LOV;
7390         int c, rc = 0, rc1 = 0, index = 0, arg_idx = 0;
7391         char fsname[PATH_MAX] = "", *pool_name = NULL;
7392         struct option long_opts[] = {
7393         { .val = 'h',   .name = "human-readable", .has_arg = no_argument },
7394         { .val = 'H',   .name = "si",           .has_arg = no_argument },
7395         { .val = 'i',   .name = "inodes",       .has_arg = no_argument },
7396         { .val = 'l',   .name = "lazy",         .has_arg = no_argument },
7397         { .val = 'p',   .name = "pool",         .has_arg = required_argument },
7398         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
7399         { .name = NULL} };
7400
7401         while ((c = getopt_long(argc, argv, "hHilp:v", long_opts, NULL)) != -1) {
7402                 switch (c) {
7403                 case 'h':
7404                         flags = (flags & ~MNTDF_DECIMAL) | MNTDF_COOKED;
7405                         break;
7406                 case 'H':
7407                         flags |= MNTDF_COOKED | MNTDF_DECIMAL;
7408                         break;
7409                 case 'i':
7410                         flags |= MNTDF_INODES;
7411                         break;
7412                 case 'l':
7413                         flags |= MNTDF_LAZY;
7414                         break;
7415                 case 'p':
7416                         pool_name = optarg;
7417                         break;
7418                 case 'v':
7419                         flags |= MNTDF_VERBOSE;
7420                         break;
7421                 default:
7422                         fprintf(stderr, "%s: unrecognized option '%s'\n",
7423                                 progname, argv[optind - 1]);
7424                         return CMD_HELP;
7425                 }
7426         }
7427
7428         /* Handle case where path is not specified */
7429         if (optind == argc) {
7430                 while (!llapi_search_mounts(path, index++, mntdir, fsname)) {
7431                         /* Check if we have a mount point */
7432                         if (mntdir[0] == '\0')
7433                                 continue;
7434
7435                         rc = mntdf(mntdir, fsname, pool_name, flags, ops, NULL);
7436                         if (rc || path[0] != '\0')
7437                                 break;
7438
7439                         fsname[0] = '\0'; /* avoid matching in next loop */
7440                         mntdir[0] = '\0'; /* avoid matching in next loop */
7441                         path[0] = '\0'; /* clean for next loop */
7442                 }
7443                 return rc;
7444         }
7445
7446         /* Loop through all the remaining arguments. These are Lustre FS
7447          * paths.
7448          */
7449         for (arg_idx = optind; arg_idx <= argc - 1; arg_idx++) {
7450                 bool valid = false;
7451
7452                 fsname[0] = '\0'; /* start clean */
7453                 mntdir[0] = '\0'; /* start clean */
7454                 path[0] = '\0';   /* start clean */
7455
7456                 /* path does not exists at all */
7457                 if (!realpath(argv[arg_idx], path)) {
7458                         rc = -errno;
7459                         fprintf(stderr, "error: invalid path '%s': %s\n",
7460                                 argv[arg_idx], strerror(-rc));
7461                         /* save first seen error */
7462                         if (!rc1)
7463                                 rc1 = rc;
7464
7465                         continue;
7466                 }
7467
7468                 /* path exists but may not be a Lustre filesystem */
7469                 while (!llapi_search_mounts(path, index++, mntdir, fsname)) {
7470                         /* Check if we have a mount point */
7471                         if (mntdir[0] == '\0')
7472                                 continue;
7473
7474                         rc = mntdf(mntdir, fsname, pool_name, flags, ops, NULL);
7475                         if (rc || path[0] != '\0') {
7476                                 valid = true;
7477
7478                                 /* save first seen error */
7479                                 if (!rc1)
7480                                         rc1 = rc;
7481                                 break;
7482                         }
7483                 }
7484
7485                 if (!valid) {
7486                         llapi_printf(LLAPI_MSG_ERROR,
7487                                      "%s:%s Not a Lustre filesystem\n",
7488                                      argv[0], argv[arg_idx]);
7489                         /* save first seen error */
7490                         if (!rc1)
7491                                 rc1 = -EOPNOTSUPP;
7492                 }
7493         }
7494
7495         return rc1;
7496 }
7497
7498 static int print_instance(const char *mntdir, char *buf, size_t buflen,
7499                           bool opt_instance, bool opt_fsname, bool opt_mntdir)
7500 {
7501         int rc = 0;
7502
7503         if (opt_fsname == opt_instance) { /* both true or both false */
7504                 rc = llapi_getname(mntdir, buf, buflen);
7505         } else if (opt_fsname) {
7506                 /*
7507                  * llapi_search_mounts() fills @buf with fsname, but that is not
7508                  * called if explicit paths are specified on the command-line
7509                  */
7510                 if (buf[0] == '\0')
7511                         rc = llapi_get_fsname(mntdir, buf, buflen);
7512         } else /* if (opt_instance) */ {
7513                 rc = llapi_get_instance(mntdir, buf, buflen);
7514         }
7515
7516         if (rc < 0) {
7517                 fprintf(stderr, "cannot get instance for '%s': %s\n",
7518                         mntdir, strerror(-rc));
7519                 return rc;
7520         }
7521
7522         if (opt_mntdir)
7523                 printf("%s %s\n", buf, mntdir);
7524         else
7525                 printf("%s\n", buf);
7526
7527         return 0;
7528 }
7529
7530 static int lfs_getname(int argc, char **argv)
7531 {
7532         struct option long_opts[] = {
7533         { .val = 'h',   .name = "help",         .has_arg = no_argument },
7534         { .val = 'i',   .name = "instance",     .has_arg = no_argument },
7535         { .val = 'n',   .name = "fsname",       .has_arg = no_argument },
7536         { .name = NULL} };
7537         bool opt_instance = false, opt_fsname = false;
7538         char fsname[PATH_MAX] = "";
7539         int rc = 0, rc2, c;
7540
7541         while ((c = getopt_long(argc, argv, "hin", long_opts, NULL)) != -1) {
7542                 switch (c) {
7543                 case 'i':
7544                         opt_instance = true;
7545                         break;
7546                 case 'n':
7547                         opt_fsname = true;
7548                         break;
7549                 default:
7550                         fprintf(stderr, "%s: unrecognized option '%s'\n",
7551                                 progname, argv[optind - 1]);
7552                         fallthrough;
7553                 case 'h':
7554                         return CMD_HELP;
7555                 }
7556         }
7557
7558         if (optind == argc) { /* no paths specified, get all paths. */
7559                 char mntdir[PATH_MAX] = "", path[PATH_MAX] = "";
7560                 int index = 0;
7561
7562                 while (!llapi_search_mounts(path, index++, mntdir, fsname)) {
7563                         rc2 = print_instance(mntdir, fsname, sizeof(fsname),
7564                                              opt_instance, opt_fsname, true);
7565                         if (!rc)
7566                                 rc = rc2;
7567                         path[0] = fsname[0] = mntdir[0] = '\0';
7568                 }
7569         } else { /* paths specified, only attempt to search these. */
7570                 bool opt_mntdir;
7571
7572                 /* if only one path is given, print only requested info */
7573                 opt_mntdir = argc - optind > 1 || (opt_instance == opt_fsname);
7574
7575                 for (; optind < argc; optind++) {
7576                         rc2 = print_instance(argv[optind], fsname,
7577                                              sizeof(fsname), opt_instance,
7578                                              opt_fsname, opt_mntdir);
7579                         if (!rc)
7580                                 rc = rc2;
7581                         fsname[0] = '\0';
7582                 }
7583         }
7584
7585         return rc;
7586 }
7587
7588 static int lfs_check(int argc, char **argv)
7589 {
7590         char mntdir[PATH_MAX] = {'\0'}, path[PATH_MAX] = {'\0'};
7591         int num_types = 1;
7592         char *obd_types[3];
7593         char obd_type1[4];
7594         char obd_type2[4];
7595         char obd_type3[4];
7596         int rc;
7597
7598         if (argc < 2 || argc > 3) {
7599                 fprintf(stderr, "%s check: server type must be specified\n",
7600                         progname);
7601                 return CMD_HELP;
7602         }
7603
7604         obd_types[0] = obd_type1;
7605         obd_types[1] = obd_type2;
7606         obd_types[2] = obd_type3;
7607
7608         if (strcmp(argv[1], "osts") == 0) {
7609                 strcpy(obd_types[0], "osc");
7610         } else if (strcmp(argv[1], "mdts") == 0 ||
7611                    strcmp(argv[1], "mds") == 0) {
7612                 strcpy(obd_types[0], "mdc");
7613         } else if (strcmp(argv[1], "mgts") == 0) {
7614                 strcpy(obd_types[0], "mgc");
7615         } else if (strcmp(argv[1], "all") == 0 ||
7616                    strcmp(argv[1], "servers") == 0) {
7617                 num_types = 3;
7618                 strcpy(obd_types[0], "osc");
7619                 strcpy(obd_types[1], "mdc");
7620                 strcpy(obd_types[2], "mgc");
7621         } else {
7622                 fprintf(stderr, "%s check: unrecognized option '%s'\n",
7623                         progname, argv[1]);
7624                 return CMD_HELP;
7625         }
7626
7627         if (argc >= 3 && !realpath(argv[2], path)) {
7628                 rc = -errno;
7629                 fprintf(stderr, "error: invalid path '%s': %s\n",
7630                         argv[2], strerror(-rc));
7631                 return rc;
7632         }
7633
7634         rc = llapi_search_mounts(path, 0, mntdir, NULL);
7635         if (rc < 0 || mntdir[0] == '\0') {
7636                 fprintf(stderr,
7637                         "%s check: cannot find mounted Lustre filesystem: %s\n",
7638                         progname, (rc < 0) ? strerror(-rc) : strerror(ENODEV));
7639                 return rc;
7640         }
7641
7642         rc = llapi_target_check(num_types, obd_types, path);
7643         if (rc)
7644                 fprintf(stderr, "%s check: cannot check target '%s': %s\n",
7645                         progname, argv[1], strerror(-rc));
7646
7647         return rc;
7648 }
7649
7650 #ifdef HAVE_SYS_QUOTA_H
7651 #define ADD_OVERFLOW(a, b) \
7652                      ((((a) + (b)) < (a)) ? \
7653                       ((a) = ULONG_MAX) : ((a) = (a) + (b)))
7654
7655 /* Convert format time string "XXwXXdXXhXXmXXs" into seconds value
7656  * returns the value or ULONG_MAX on integer overflow or incorrect format
7657  * Notes:
7658  *        1. the order of specifiers is arbitrary (may be: 5w3s or 3s5w)
7659  *        2. specifiers may be encountered multiple times (2s3s is 5 seconds)
7660  *        3. empty integer value is interpreted as 0
7661  */
7662 static unsigned long str2sec(const char *timestr)
7663 {
7664         const char spec[] = "smhdw";
7665         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
7666         unsigned long val = 0;
7667         char *tail;
7668
7669         if (strpbrk(timestr, spec) == NULL) {
7670                 /*
7671                  * no specifiers inside the time string,
7672                  * should treat it as an integer value
7673                  */
7674                 val = strtoul(timestr, &tail, 10);
7675                 return *tail ? ULONG_MAX : val;
7676         }
7677
7678         /* format string is XXwXXdXXhXXmXXs */
7679         while (*timestr) {
7680                 unsigned long v;
7681                 int ind;
7682                 char *ptr;
7683
7684                 v = strtoul(timestr, &tail, 10);
7685                 if (v == ULONG_MAX || *tail == '\0')
7686                         /*
7687                          * value too large (ULONG_MAX or more)
7688                          * or missing specifier
7689                          */
7690                         goto error;
7691
7692                 ptr = strchr(spec, *tail);
7693                 if (!ptr)
7694                         /* unknown specifier */
7695                         goto error;
7696
7697                 ind = ptr - spec;
7698
7699                 /* check if product will overflow the type */
7700                 if (!(v < ULONG_MAX / mult[ind]))
7701                         goto error;
7702
7703                 ADD_OVERFLOW(val, mult[ind] * v);
7704                 if (val == ULONG_MAX)
7705                         goto error;
7706
7707                 timestr = tail + 1;
7708         }
7709
7710         return val;
7711
7712 error:
7713         return ULONG_MAX;
7714 }
7715
7716 #define ARG2ULL(nr, str, def_units)                                     \
7717 do {                                                                    \
7718         unsigned long long limit, units = def_units;                    \
7719         int rc;                                                         \
7720                                                                         \
7721         rc = llapi_parse_size(str, &limit, &units, 1);                  \
7722         if (rc < 0) {                                                   \
7723                 fprintf(stderr, "%s: invalid limit '%s'\n",             \
7724                         progname, str);                                 \
7725                 return CMD_HELP;                                        \
7726         }                                                               \
7727         nr = limit;                                                     \
7728 } while (0)
7729
7730 static inline int has_times_option(int argc, char **argv)
7731 {
7732         int i;
7733
7734         for (i = 1; i < argc; i++)
7735                 if (!strcmp(argv[i], "-t"))
7736                         return 1;
7737
7738         return 0;
7739 }
7740
7741 static inline int lfs_verify_poolarg(char *pool)
7742 {
7743         if (strnlen(optarg, LOV_MAXPOOLNAME + 1) > LOV_MAXPOOLNAME) {
7744                 fprintf(stderr,
7745                         "Pool name '%.*s' is longer than %d\n",
7746                         LOV_MAXPOOLNAME, pool, LOV_MAXPOOLNAME);
7747                 return 1;
7748         }
7749         return 0;
7750 }
7751
7752 /* special grace time, only notify the user when its quota is over soft limit
7753  * but doesn't block new writes until the hard limit is reached.
7754  */
7755 #define NOTIFY_GRACE            "notify"
7756 #define NOTIFY_GRACE_TIME       LQUOTA_GRACE_MASK
7757
7758 #ifndef toqb
7759 static inline __u64 lustre_stoqb(size_t space)
7760 {
7761         return (space + QIF_DQBLKSIZE - 1) >> QIF_DQBLKSIZE_BITS;
7762 }
7763 #else
7764 #define lustre_stoqb   toqb
7765 #endif
7766
7767 int lfs_setquota_times(int argc, char **argv, struct if_quotactl *qctl)
7768 {
7769         int c, rc;
7770         char *mnt, *obd_type = (char *)qctl->obd_type;
7771         struct obd_dqblk *dqb = &qctl->qc_dqblk;
7772         struct obd_dqinfo *dqi = &qctl->qc_dqinfo;
7773         struct option long_opts[] = {
7774         { .val = 'b',   .name = "block-grace",  .has_arg = required_argument },
7775         { .val = 'g',   .name = "group",        .has_arg = no_argument },
7776         { .val = 'h',   .name = "help",         .has_arg = no_argument },
7777         { .val = 'i',   .name = "inode-grace",  .has_arg = required_argument },
7778         { .val = 'p',   .name = "projid",       .has_arg = no_argument },
7779         { .val = 't',   .name = "times",        .has_arg = no_argument },
7780         { .val = 'u',   .name = "user",         .has_arg = no_argument },
7781         { .val = LFS_POOL_OPT,
7782                         .name = "pool",         .has_arg = required_argument },
7783         { .name = NULL } };
7784         int qtype;
7785
7786         qctl->qc_cmd  = LUSTRE_Q_SETINFO;
7787         qctl->qc_type = ALLQUOTA;
7788
7789         while ((c = getopt_long(argc, argv, "b:ghi:ptu",
7790                                 long_opts, NULL)) != -1) {
7791                 switch (c) {
7792                 case 'u':
7793                         qtype = USRQUOTA;
7794                         goto quota_type;
7795                 case 'g':
7796                         qtype = GRPQUOTA;
7797                         goto quota_type;
7798                 case 'p':
7799                         qtype = PRJQUOTA;
7800 quota_type:
7801                         if (qctl->qc_type != ALLQUOTA) {
7802                                 fprintf(stderr,
7803                                         "%s: -u/g/p cannot be used more than once\n",
7804                                         progname);
7805                                 return CMD_HELP;
7806                         }
7807                         qctl->qc_type = qtype;
7808                         break;
7809                 case 'b':
7810                         if (strncmp(optarg, NOTIFY_GRACE,
7811                                     strlen(NOTIFY_GRACE)) == 0) {
7812                                 dqi->dqi_bgrace = NOTIFY_GRACE_TIME;
7813                         } else {
7814                                 dqi->dqi_bgrace = str2sec(optarg);
7815                                 if (dqi->dqi_bgrace >= NOTIFY_GRACE_TIME) {
7816                                         fprintf(stderr,
7817                                                 "%s: bad block-grace: %s\n",
7818                                                 progname, optarg);
7819                                         return CMD_HELP;
7820                                 }
7821                         }
7822                         dqb->dqb_valid |= QIF_BTIME;
7823                         break;
7824                 case 'i':
7825                         if (strncmp(optarg, NOTIFY_GRACE,
7826                                     strlen(NOTIFY_GRACE)) == 0) {
7827                                 dqi->dqi_igrace = NOTIFY_GRACE_TIME;
7828                         } else {
7829                                 dqi->dqi_igrace = str2sec(optarg);
7830                                 if (dqi->dqi_igrace >= NOTIFY_GRACE_TIME) {
7831                                         fprintf(stderr,
7832                                                 "%s: bad inode-grace: %s\n",
7833                                                 progname, optarg);
7834                                         return CMD_HELP;
7835                                 }
7836                         }
7837                         dqb->dqb_valid |= QIF_ITIME;
7838                         break;
7839                 case 't': /* Yes, of course! */
7840                         break;
7841                 case LFS_POOL_OPT:
7842                         if (lfs_verify_poolarg(optarg))
7843                                 return -1;
7844                         strncpy(qctl->qc_poolname, optarg, LOV_MAXPOOLNAME);
7845                         qctl->qc_cmd  = LUSTRE_Q_SETINFOPOOL;
7846                         break;
7847                 /* getopt prints error message for us when opterr != 0 */
7848                 default:
7849                         fprintf(stderr, "%s: unrecognized option '%s'\n",
7850                                 progname, argv[optind - 1]);
7851                         fallthrough;
7852                 case 'h':
7853                         return CMD_HELP;
7854                 }
7855         }
7856
7857         if (qctl->qc_type == ALLQUOTA) {
7858                 fprintf(stderr, "%s: neither -u, -g nor -p specified\n",
7859                         progname);
7860                 return CMD_HELP;
7861         }
7862
7863         if (optind != argc - 1) {
7864                 fprintf(stderr, "%s: unexpected parameter '%s'\n",
7865                         progname, argv[optind + 1]);
7866                 return CMD_HELP;
7867         }
7868
7869         mnt = argv[optind];
7870         rc = llapi_quotactl(mnt, qctl);
7871         if (rc) {
7872                 if (*obd_type)
7873                         fprintf(stderr, "%s %s ", obd_type,
7874                                 obd_uuid2str(&qctl->obd_uuid));
7875                 fprintf(stderr, "setquota failed: %s\n", strerror(-rc));
7876                 return rc;
7877         }
7878
7879         return 0;
7880 }
7881
7882 static int lfs_reset_quota(char *mnt, struct if_quotactl *qctl)
7883 {
7884         struct if_quotactl tmp_qctl;
7885         int index, md_count, dt_count;
7886         int wait_phase = 0, wait_index = 0, wait_count = 0;
7887         int rc, rc2;
7888
7889         /* reset the quota ID, the existing quota setting will be returned */
7890         rc = llapi_quotactl(mnt, qctl);
7891         if (rc)
7892                 return rc;
7893
7894         /* sanity check */
7895         if ((qctl->qc_dqblk.dqb_valid & QIF_LIMITS) != QIF_LIMITS) {
7896                 fprintf(stderr,
7897                         "the existing quota settings are not returned!\n");
7898                 return -EINVAL;
7899         }
7900
7901         rc = llapi_get_obd_count(mnt, &md_count, 1);
7902         if (rc) {
7903                 fprintf(stderr, "can not get mdt count: %s\n", strerror(-rc));
7904                 return rc;
7905         }
7906
7907         rc = llapi_get_obd_count(mnt, &dt_count, 0);
7908         if (rc) {
7909                 fprintf(stderr, "can not get ost count: %s\n", strerror(-rc));
7910                 return rc;
7911         }
7912
7913         memset(&tmp_qctl, 0, sizeof(tmp_qctl));
7914         tmp_qctl.qc_type = qctl->qc_type;
7915         tmp_qctl.qc_id = qctl->qc_id;
7916         tmp_qctl.qc_cmd = LUSTRE_Q_GETQUOTA;
7917
7918 retry:
7919         if (wait_phase == 0) {
7920                 for (index = wait_index; index < md_count; index++) {
7921                         tmp_qctl.qc_idx = index;
7922                         tmp_qctl.qc_valid = QC_MDTIDX;
7923                         rc = llapi_quotactl(mnt, &tmp_qctl);
7924                         if (rc == -ENODEV || rc == -ENODATA)
7925                                 continue;
7926                         if (rc) {
7927                                 fprintf(stderr, "quotactl mdt%d failed: %s\n",
7928                                         index, strerror(-rc));
7929                                 break;
7930                         }
7931                         /* check whether the md quota grant is reset */
7932                         if (tmp_qctl.qc_dqblk.dqb_valid & QIF_LIMITS &&
7933                             tmp_qctl.qc_dqblk.dqb_ihardlimit != 0)
7934                                 break;
7935                 }
7936
7937                 if (index < md_count) {
7938                         wait_phase = 0;
7939                         wait_index = index;
7940                         goto wait;
7941                 }
7942         } else {
7943                 for (index = wait_index; index < dt_count; index++) {
7944                         tmp_qctl.qc_idx = index;
7945                         tmp_qctl.qc_valid = QC_OSTIDX;
7946                         rc = llapi_quotactl(mnt, &tmp_qctl);
7947                         if (rc == -ENODEV || rc == -ENODATA)
7948                                 continue;
7949                         if (rc) {
7950                                 fprintf(stderr, "quotactl mdt%d failed: %s\n",
7951                                         index, strerror(-rc));
7952                                 break;
7953                         }
7954                         /* check whether the dt quota grant is reset */
7955                         if (tmp_qctl.qc_dqblk.dqb_valid & QIF_LIMITS &&
7956                             tmp_qctl.qc_dqblk.dqb_bhardlimit != 0)
7957                                 break;
7958                 }
7959
7960                 if (index < dt_count) {
7961                         wait_phase = 1;
7962                         wait_index = index;
7963                         goto wait;
7964                 }
7965         }
7966
7967         if (wait_phase == 0) {
7968                 wait_phase = 1;
7969                 goto retry;
7970         }
7971
7972         goto out;
7973
7974 wait:
7975         if (rc || wait_count > 30) {
7976                 fprintf(stderr, "fail to reset the quota ID %d on OBDs\n",
7977                         qctl->qc_id);
7978                 goto out;
7979         }
7980
7981         wait_count++;
7982         sleep(1);
7983         fprintf(stdout, "wait %d seconds for OBDs to reset the quota ID %u\n",
7984                 wait_count, qctl->qc_id);
7985         goto retry;
7986
7987
7988 out:
7989         /* restore the quota setting */
7990         if (qctl->qc_dqblk.dqb_isoftlimit == 0 &&
7991             qctl->qc_dqblk.dqb_ihardlimit == 0 &&
7992             qctl->qc_dqblk.dqb_bsoftlimit == 0 &&
7993             qctl->qc_dqblk.dqb_bhardlimit == 0)
7994                 return rc;
7995
7996         memcpy(&tmp_qctl, qctl, sizeof(tmp_qctl));
7997         tmp_qctl.qc_cmd = LUSTRE_Q_SETQUOTA;
7998         rc2 = llapi_quotactl(mnt, &tmp_qctl);
7999         if (!rc2)
8000                 return rc;
8001
8002         fprintf(stderr,
8003                 "fail to restore the quota setting: %s, please restore it manually by\n  lfs setquota %s %d",
8004                 strerror(-rc2),
8005                 qctl->qc_type == USRQUOTA ? "-u" :
8006                                 (qctl->qc_type == GRPQUOTA ? "-g" : "-p"),
8007                 qctl->qc_id);
8008
8009         if (qctl->qc_dqblk.dqb_isoftlimit != 0)
8010                 fprintf(stderr, " -i %llu",
8011                         (unsigned long long)qctl->qc_dqblk.dqb_isoftlimit);
8012         if (qctl->qc_dqblk.dqb_ihardlimit != 0)
8013                 fprintf(stderr, " -I %llu",
8014                         (unsigned long long)qctl->qc_dqblk.dqb_ihardlimit);
8015         if (qctl->qc_dqblk.dqb_bsoftlimit != 0)
8016                 fprintf(stderr, " -b %llu",
8017                         (unsigned long long)qctl->qc_dqblk.dqb_bsoftlimit);
8018         if (qctl->qc_dqblk.dqb_bhardlimit != 0)
8019                 fprintf(stderr, " -B %llu",
8020                         (unsigned long long)qctl->qc_dqblk.dqb_bhardlimit);
8021
8022         fprintf(stderr, " %s\n", mnt);
8023         if (!rc)
8024                 rc = rc2;
8025
8026         return rc;
8027 }
8028
8029 #define BSLIMIT (1 << 0)
8030 #define BHLIMIT (1 << 1)
8031 #define ISLIMIT (1 << 2)
8032 #define IHLIMIT (1 << 3)
8033
8034 int lfs_setquota(int argc, char **argv)
8035 {
8036         int c, rc = 0;
8037         struct if_quotactl *qctl;
8038         char *mnt, *obd_type;
8039         struct obd_dqblk *dqb;
8040         struct option long_opts[] = {
8041         { .val = 'b',   .name = "block-softlimit",
8042                                                 .has_arg = required_argument },
8043         { .val = 'B',   .name = "block-hardlimit",
8044                                                 .has_arg = required_argument },
8045         { .val = 'd',   .name = "default",      .has_arg = no_argument },
8046         { .val = LFS_SETQUOTA_DELETE,
8047                         .name = "delete",       .has_arg = no_argument },
8048         { .val = 'g',   .name = "group",        .has_arg = required_argument },
8049         { .val = 'G',   .name = "default-grp",  .has_arg = no_argument },
8050         { .val = 'h',   .name = "help",         .has_arg = no_argument },
8051         { .val = 'i',   .name = "inode-softlimit",
8052                                                 .has_arg = required_argument },
8053         { .val = 'I',   .name = "inode-hardlimit",
8054                                                 .has_arg = required_argument },
8055         { .val = 'p',   .name = "projid",       .has_arg = required_argument },
8056         { .val = 'P',   .name = "default-prj",  .has_arg = no_argument },
8057         { .val = 'r',   .name = "reset",        .has_arg = no_argument },
8058         { .val = 'u',   .name = "user",         .has_arg = required_argument },
8059         { .val = 'U',   .name = "default-usr",  .has_arg = no_argument },
8060         { .val = LFS_POOL_OPT,
8061                         .name = "pool",         .has_arg = required_argument },
8062         { .name = NULL } };
8063         unsigned int limit_mask = 0;
8064         bool use_default = false;
8065         int qtype, qctl_len;
8066
8067         qctl_len = sizeof(*qctl) + LOV_MAXPOOLNAME + 1;
8068         qctl = malloc(qctl_len);
8069         if (!qctl)
8070                 return -ENOMEM;
8071
8072         memset(qctl, 0, qctl_len);
8073         obd_type = (char *)qctl->obd_type;
8074         dqb = &qctl->qc_dqblk;
8075
8076         if (has_times_option(argc, argv)) {
8077                 rc = lfs_setquota_times(argc, argv, qctl);
8078                 goto out;
8079         }
8080
8081         qctl->qc_cmd  = LUSTRE_Q_SETQUOTA;
8082         qctl->qc_type = ALLQUOTA; /* ALLQUOTA makes no sense for setquota,
8083                                    * so it can be used as a marker that qc_type
8084                                    * isn't reinitialized from command line
8085                                    */
8086         while ((c = getopt_long(argc, argv, "b:B:dDg:Ghi:I:p:Pru:U",
8087                 long_opts, NULL)) != -1) {
8088                 switch (c) {
8089                 case 'U':
8090                         qctl->qc_cmd = LUSTRE_Q_SETDEFAULT;
8091                         qtype = USRQUOTA;
8092                         qctl->qc_id = 0;
8093                         goto quota_type_def;
8094                 case 'u':
8095                         qtype = USRQUOTA;
8096                         rc = name2uid(&qctl->qc_id, optarg);
8097                         goto quota_type;
8098                 case 'G':
8099                         qctl->qc_cmd = LUSTRE_Q_SETDEFAULT;
8100                         qtype = GRPQUOTA;
8101                         qctl->qc_id = 0;
8102                         goto quota_type_def;
8103                 case 'g':
8104                         qtype = GRPQUOTA;
8105                         rc = name2gid(&qctl->qc_id, optarg);
8106                         goto quota_type;
8107                 case 'P':
8108                         qctl->qc_cmd = LUSTRE_Q_SETDEFAULT;
8109                         qtype = PRJQUOTA;
8110                         qctl->qc_id = 0;
8111                         goto quota_type_def;
8112                 case 'p':
8113                         qtype = PRJQUOTA;
8114                         rc = name2projid(&qctl->qc_id, optarg);
8115 quota_type:
8116                         if (rc) {
8117                                 if (str2quotaid(&qctl->qc_id, optarg)) {
8118                                         fprintf(stderr,
8119                                                 "%s setquota: invalid id '%s'\n",
8120                                                 progname, optarg);
8121                                         rc = -1;
8122                                         goto out;
8123                                 }
8124                         }
8125
8126                         if (qctl->qc_id == 0) {
8127                                 fprintf(stderr,
8128                                         "%s setquota: can't set quota for root usr/group/project.\n",
8129                                         progname);
8130                                 rc = -1;
8131                                 goto out;
8132                         }
8133
8134 quota_type_def:
8135                         if (qctl->qc_type != ALLQUOTA) {
8136                                 fprintf(stderr,
8137                                         "%s setquota: only one of -u, -U, -g, -G, -p or -P may be specified\n",
8138                                         progname);
8139                                 rc = CMD_HELP;
8140                                 goto out;
8141                         }
8142                         qctl->qc_type = qtype;
8143                         break;
8144 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
8145                 case 'd':
8146                         fprintf(stderr,
8147                                 "%s setquota: '-d' deprecated, use '-D' or '--default'\n",
8148                                 progname);
8149                         fallthrough;
8150 #endif
8151                 case 'D':
8152                         use_default = true;
8153                         qctl->qc_cmd = LUSTRE_Q_SETDEFAULT;
8154                         break;
8155                 case LFS_SETQUOTA_DELETE:
8156                         qctl->qc_cmd = LUSTRE_Q_DELETEQID;
8157                         break;
8158                 case 'b':
8159                         ARG2ULL(dqb->dqb_bsoftlimit, optarg, 1024);
8160                         dqb->dqb_bsoftlimit >>= 10;
8161                         limit_mask |= BSLIMIT;
8162                         if (dqb->dqb_bsoftlimit &&
8163                             dqb->dqb_bsoftlimit <= 1024) /* <= 1M? */
8164                                 fprintf(stderr,
8165                                         "%s setquota: warning: block softlimit '%llu' smaller than minimum qunit size\nSee '%s help setquota' or Lustre manual for details\n",
8166                                         progname,
8167                                         (unsigned long long)dqb->dqb_bsoftlimit,
8168                                         progname);
8169                         break;
8170                 case 'B':
8171                         ARG2ULL(dqb->dqb_bhardlimit, optarg, 1024);
8172                         dqb->dqb_bhardlimit >>= 10;
8173                         limit_mask |= BHLIMIT;
8174                         if (dqb->dqb_bhardlimit &&
8175                             dqb->dqb_bhardlimit <= 1024) /* <= 1M? */
8176                                 fprintf(stderr,
8177                                         "%s setquota: warning: block hardlimit '%llu' smaller than minimum qunit size\n"
8178                                         "See '%s help setquota' or Lustre manual for details\n",
8179                                         progname,
8180                                         (unsigned long long)dqb->dqb_bhardlimit,
8181                                         progname);
8182                         break;
8183                 case 'i':
8184                         ARG2ULL(dqb->dqb_isoftlimit, optarg, 1);
8185                         limit_mask |= ISLIMIT;
8186                         if (dqb->dqb_isoftlimit &&
8187                             dqb->dqb_isoftlimit <= 1024) /* <= 1K inodes? */
8188                                 fprintf(stderr,
8189                                         "%s setquota: warning: inode softlimit '%llu' smaller than minimum qunit size\nSee '%s help setquota' or Lustre manual for details\n",
8190                                         progname,
8191                                         (unsigned long long)dqb->dqb_isoftlimit,
8192                                         progname);
8193                         break;
8194                 case 'I':
8195                         ARG2ULL(dqb->dqb_ihardlimit, optarg, 1);
8196                         limit_mask |= IHLIMIT;
8197                         if (dqb->dqb_ihardlimit &&
8198                             dqb->dqb_ihardlimit <= 1024) /* <= 1K inodes? */
8199                                 fprintf(stderr,
8200                                         "%s setquota: warning: inode hardlimit '%llu' smaller than minimum qunit size\nSee '%s help setquota' or Lustre manual for details\n",
8201                                         progname,
8202                                         (unsigned long long)dqb->dqb_ihardlimit,
8203                                         progname);
8204                         break;
8205                 case LFS_POOL_OPT:
8206                         if (lfs_verify_poolarg(optarg)) {
8207                                 rc = -1;
8208                                 goto out;
8209                         }
8210                         strncpy(qctl->qc_poolname, optarg, LOV_MAXPOOLNAME);
8211                         qctl->qc_cmd = qctl->qc_cmd == LUSTRE_Q_SETDEFAULT ?
8212                                                 LUSTRE_Q_SETDEFAULT_POOL :
8213                                                 LUSTRE_Q_SETQUOTAPOOL;
8214                         break;
8215                 case 'r':
8216                         qctl->qc_cmd = LUSTRE_Q_RESETQID;
8217                         break;
8218                 default:
8219                         fprintf(stderr,
8220                                 "%s setquota: unrecognized option '%s'\n",
8221                                 progname, argv[optind - 1]);
8222                         fallthrough;
8223                 case 'h':
8224                         rc = CMD_HELP;
8225                         goto out;
8226                 }
8227         }
8228
8229         if (qctl->qc_type == ALLQUOTA) {
8230                 fprintf(stderr,
8231                         "%s setquota: either -u or -g must be specified\n",
8232                         progname);
8233                 rc = CMD_HELP;
8234                 goto out;
8235         }
8236
8237         if (!use_default && qctl->qc_cmd != LUSTRE_Q_DELETEQID &&
8238             qctl->qc_cmd != LUSTRE_Q_RESETQID && limit_mask == 0) {
8239                 fprintf(stderr,
8240                         "%s setquota: at least one limit must be specified\n",
8241                         progname);
8242                 rc = CMD_HELP;
8243                 goto out;
8244         }
8245
8246         if ((use_default || qctl->qc_cmd == LUSTRE_Q_DELETEQID ||
8247              qctl->qc_cmd == LUSTRE_Q_RESETQID) && limit_mask != 0) {
8248                 fprintf(stderr,
8249                         "%s setquota: limits should not be specified when using default quota, deleting or resetting quota ID\n",
8250                         progname);
8251                 rc = CMD_HELP;
8252                 goto out;
8253         }
8254
8255         if (use_default && qctl->qc_id == 0) {
8256                 fprintf(stderr,
8257                         "%s setquota: can not set default quota for root user/group/project\n",
8258                         progname);
8259                 rc = CMD_HELP;
8260                 goto out;
8261         }
8262
8263         if ((qctl->qc_cmd == LUSTRE_Q_DELETEQID ||
8264              qctl->qc_cmd == LUSTRE_Q_RESETQID)  && qctl->qc_id == 0) {
8265                 fprintf(stderr,
8266                         "%s setquota: can not delete or reset root user/group/project\n",
8267                         progname);
8268                 rc = CMD_HELP;
8269                 goto out;
8270         }
8271
8272         if (optind != argc - 1) {
8273                 fprintf(stderr,
8274                         "%s setquota: filesystem not specified or unexpected argument '%s'\n",
8275                         progname, argv[optind]);
8276                 rc = CMD_HELP;
8277                 goto out;
8278         }
8279
8280         mnt = argv[optind];
8281
8282         if (use_default) {
8283                 dqb->dqb_bhardlimit = 0;
8284                 dqb->dqb_bsoftlimit = 0;
8285                 dqb->dqb_ihardlimit = 0;
8286                 dqb->dqb_isoftlimit = 0;
8287                 dqb->dqb_itime = 0;
8288                 dqb->dqb_btime = 0;
8289                 dqb->dqb_valid |= QIF_LIMITS | QIF_TIMES;
8290                 /* do not set inode limits for Pool Quotas */
8291                 if (qctl->qc_cmd  == LUSTRE_Q_SETDEFAULT_POOL)
8292                         dqb->dqb_valid ^= QIF_ILIMITS | QIF_ITIME;
8293         } else if ((!(limit_mask & BHLIMIT) ^ !(limit_mask & BSLIMIT)) ||
8294                    (!(limit_mask & IHLIMIT) ^ !(limit_mask & ISLIMIT))) {
8295                 /* sigh, we can't just set blimits/ilimits */
8296                 struct if_quotactl *tmp_qctl;
8297
8298                 tmp_qctl = calloc(1, sizeof(*qctl) + LOV_MAXPOOLNAME + 1);
8299                 if (!tmp_qctl)
8300                         goto out;
8301
8302                 if (qctl->qc_cmd == LUSTRE_Q_SETQUOTAPOOL) {
8303                         tmp_qctl->qc_cmd = LUSTRE_Q_GETQUOTAPOOL;
8304                         strncpy(tmp_qctl->qc_poolname, qctl->qc_poolname,
8305                                 LOV_MAXPOOLNAME);
8306                 } else {
8307                         tmp_qctl->qc_cmd  = LUSTRE_Q_GETQUOTA;
8308                 }
8309                 tmp_qctl->qc_type = qctl->qc_type;
8310                 tmp_qctl->qc_id = qctl->qc_id;
8311
8312                 rc = llapi_quotactl(mnt, tmp_qctl);
8313                 if (rc < 0) {
8314                         free(tmp_qctl);
8315                         goto out;
8316                 }
8317
8318                 if (!(limit_mask & BHLIMIT))
8319                         dqb->dqb_bhardlimit = tmp_qctl->qc_dqblk.dqb_bhardlimit;
8320                 if (!(limit_mask & BSLIMIT))
8321                         dqb->dqb_bsoftlimit = tmp_qctl->qc_dqblk.dqb_bsoftlimit;
8322                 if (!(limit_mask & IHLIMIT))
8323                         dqb->dqb_ihardlimit = tmp_qctl->qc_dqblk.dqb_ihardlimit;
8324                 if (!(limit_mask & ISLIMIT))
8325                         dqb->dqb_isoftlimit = tmp_qctl->qc_dqblk.dqb_isoftlimit;
8326
8327                 /* Keep grace times if we have got no softlimit arguments */
8328                 if ((limit_mask & BHLIMIT) && !(limit_mask & BSLIMIT)) {
8329                         dqb->dqb_valid |= QIF_BTIME;
8330                         dqb->dqb_btime = tmp_qctl->qc_dqblk.dqb_btime;
8331                 }
8332
8333                 if ((limit_mask & IHLIMIT) && !(limit_mask & ISLIMIT)) {
8334                         dqb->dqb_valid |= QIF_ITIME;
8335                         dqb->dqb_itime = tmp_qctl->qc_dqblk.dqb_itime;
8336                 }
8337                 free(tmp_qctl);
8338         }
8339
8340         dqb->dqb_valid |= (limit_mask & (BHLIMIT | BSLIMIT)) ? QIF_BLIMITS : 0;
8341         dqb->dqb_valid |= (limit_mask & (IHLIMIT | ISLIMIT)) ? QIF_ILIMITS : 0;
8342
8343         if (qctl->qc_cmd == LUSTRE_Q_RESETQID)
8344                 rc = lfs_reset_quota(mnt, qctl);
8345         else
8346                 rc = llapi_quotactl(mnt, qctl);
8347
8348         if (rc) {
8349                 if (*obd_type)
8350                         fprintf(stderr,
8351                                 "%s setquota: cannot quotactl '%s' '%s': %s\n",
8352                                 progname, obd_type,
8353                                 obd_uuid2str(&qctl->obd_uuid), strerror(-rc));
8354                 else
8355                         fprintf(stderr,
8356                                 "%s setquota: quotactl failed: %s\n",
8357                                 progname, strerror(-rc));
8358         }
8359 out:
8360         if (rc)
8361                 fprintf(stderr, "setquota failed: %s\n", strerror(-rc));
8362
8363         free(qctl);
8364         return rc;
8365 }
8366
8367 /* Converts seconds value into format string
8368  * result is returned in buf
8369  * Notes:
8370  *        1. result is in descenting order: 1w2d3h4m5s
8371  *        2. zero fields are not filled (except for p. 3): 5d1s
8372  *        3. zero seconds value is presented as "0s"
8373  */
8374 static char *__sec2str(time_t seconds, char *buf)
8375 {
8376         const char spec[] = "smhdw";
8377         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
8378         unsigned long c;
8379         char *tail = buf;
8380         int i;
8381
8382         for (i = ARRAY_SIZE(mult) - 1 ; i >= 0; i--) {
8383                 c = seconds / mult[i];
8384
8385                 if (c > 0 || (i == 0 && buf == tail))
8386                         tail += scnprintf(tail, 40-(tail-buf), "%lu%c", c,
8387                                           spec[i]);
8388
8389                 seconds %= mult[i];
8390         }
8391
8392         return tail;
8393 }
8394
8395 static void sec2str(time_t seconds, char *buf, int rc)
8396 {
8397         char *tail = buf;
8398
8399         if (rc)
8400                 *tail++ = '[';
8401
8402         tail = __sec2str(seconds, tail);
8403
8404         if (rc && tail - buf < 39) {
8405                 *tail++ = ']';
8406                 *tail++ = 0;
8407         }
8408 }
8409
8410 static void diff2str(time_t seconds, char *buf, time_t now)
8411 {
8412         buf[0] = 0;
8413         if (!seconds)
8414                 return;
8415         if (seconds <= now) {
8416                 strcpy(buf, "expired");
8417                 return;
8418         }
8419         __sec2str(seconds - now, buf);
8420 }
8421
8422 static void print_quota_title(char *name, struct if_quotactl *qctl,
8423                               bool human_readable, bool show_default)
8424 {
8425         if (show_default) {
8426                 printf("Disk default %s quota:\n", qtype_name(qctl->qc_type));
8427                 printf("%15s %8s%8s%8s %8s%8s%8s\n",
8428                        "Filesystem", "bquota", "blimit", "bgrace",
8429                        "iquota", "ilimit", "igrace");
8430         } else {
8431                 printf("Disk quotas for %s %s (%cid %u):\n",
8432                        qtype_name(qctl->qc_type), name,
8433                        *qtype_name(qctl->qc_type), qctl->qc_id);
8434                 printf("%15s%8s %7s%8s%8s%8s %7s%8s%8s\n",
8435                        "Filesystem", human_readable ? "used" : "kbytes",
8436                        "quota", "limit", "grace",
8437                        "files", "quota", "limit", "grace");
8438         }
8439 }
8440
8441 static void kbytes2str(__u64 num, char *buf, int buflen, bool h)
8442 {
8443         if (!h) {
8444                 snprintf(buf, buflen, "%ju", (uintmax_t)num);
8445         } else {
8446                 if (num >> 40)
8447                         snprintf(buf, buflen, "%5.4gP",
8448                                  (double)num / ((__u64)1 << 40));
8449                 else if (num >> 30)
8450                         snprintf(buf, buflen, "%5.4gT",
8451                                  (double)num / (1 << 30));
8452                 else if (num >> 20)
8453                         snprintf(buf, buflen, "%5.4gG",
8454                                  (double)num / (1 << 20));
8455                 else if (num >> 10)
8456                         snprintf(buf, buflen, "%5.4gM",
8457                                  (double)num / (1 << 10));
8458                 else
8459                         snprintf(buf, buflen, "%ju%s", (uintmax_t)num, "k");
8460         }
8461 }
8462
8463 #ifdef HAVE_NATIVE_CLIENT
8464 /* In the current Lustre implementation, the grace time is either the time
8465  * or the timestamp to be used after some quota ID exceeds the soft limt,
8466  * 48 bits should be enough, its high 16 bits can be used as quota flags.
8467  */
8468 #define LQUOTA_GRACE_BITS       48
8469 #define LQUOTA_GRACE_MASK       ((1ULL << LQUOTA_GRACE_BITS) - 1)
8470 #define LQUOTA_GRACE_MAX        LQUOTA_GRACE_MASK
8471 #define LQUOTA_GRACE(t)         (t & LQUOTA_GRACE_MASK)
8472 #define LQUOTA_FLAG(t)          (t >> LQUOTA_GRACE_BITS)
8473 #define LQUOTA_GRACE_FLAG(t, f) ((__u64)t | (__u64)f << LQUOTA_GRACE_BITS)
8474 #endif
8475
8476 #define STRBUF_LEN      24
8477 static void print_quota(char *mnt, struct if_quotactl *qctl, int type,
8478                         int rc, bool h, bool show_default)
8479 {
8480         time_t now;
8481
8482         time(&now);
8483
8484         if (qctl->qc_cmd == LUSTRE_Q_GETQUOTA || qctl->qc_cmd == Q_GETOQUOTA ||
8485             qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL ||
8486             qctl->qc_cmd == LUSTRE_Q_GETDEFAULT ||
8487             qctl->qc_cmd == LUSTRE_Q_GETDEFAULT_POOL) {
8488                 int bover = 0, iover = 0;
8489                 struct obd_dqblk *dqb = &qctl->qc_dqblk;
8490                 char numbuf[3][STRBUF_LEN + 2]; /* 2 for brackets or wildcard */
8491                 char timebuf[40];
8492                 char strbuf[STRBUF_LEN];
8493
8494                 dqb->dqb_btime &= LQUOTA_GRACE_MASK;
8495                 dqb->dqb_itime &= LQUOTA_GRACE_MASK;
8496
8497                 if (dqb->dqb_bhardlimit &&
8498                     lustre_stoqb(dqb->dqb_curspace) >= dqb->dqb_bhardlimit) {
8499                         bover = 1;
8500                 } else if (dqb->dqb_bsoftlimit && dqb->dqb_btime) {
8501                         if (dqb->dqb_btime > now)
8502                                 bover = 2;
8503                         else
8504                                 bover = 3;
8505                 }
8506
8507                 if (dqb->dqb_ihardlimit &&
8508                     dqb->dqb_curinodes >= dqb->dqb_ihardlimit) {
8509                         iover = 1;
8510                 } else if (dqb->dqb_isoftlimit && dqb->dqb_itime) {
8511                         if (dqb->dqb_itime > now)
8512                                 iover = 2;
8513                         else
8514                                 iover = 3;
8515                 }
8516
8517                 if (strlen(mnt) > 15)
8518                         printf("%s\n%15s", mnt, "");
8519                 else
8520                         printf("%15s", mnt);
8521
8522                 if (show_default)
8523                         snprintf(timebuf, sizeof(timebuf), "%llu",
8524                                  (unsigned long long)dqb->dqb_btime);
8525                 else if (bover)
8526                         diff2str(dqb->dqb_btime, timebuf, now);
8527
8528                 kbytes2str(lustre_stoqb(dqb->dqb_curspace),
8529                            strbuf, sizeof(strbuf), h);
8530                 if (rc == -EREMOTEIO)
8531                         sprintf(numbuf[0], "%s*", strbuf);
8532                 else
8533                         sprintf(numbuf[0], (dqb->dqb_valid & QIF_SPACE) ?
8534                                 "%s" : "[%s]", strbuf);
8535
8536                 kbytes2str(dqb->dqb_bsoftlimit, strbuf, sizeof(strbuf), h);
8537                 if (type == QC_GENERAL)
8538                         sprintf(numbuf[1], (dqb->dqb_valid & QIF_BLIMITS) ?
8539                                 "%s" : "[%s]", strbuf);
8540                 else
8541                         sprintf(numbuf[1], "%s", "-");
8542
8543                 kbytes2str(dqb->dqb_bhardlimit, strbuf, sizeof(strbuf), h);
8544                 sprintf(numbuf[2], (dqb->dqb_valid & QIF_BLIMITS) ?
8545                         "%s" : "[%s]", strbuf);
8546
8547                 if (show_default)
8548                         printf(" %6s %7s %7s", numbuf[1], numbuf[2], timebuf);
8549                 else
8550                         printf(" %7s%c %6s %7s %7s",
8551                                numbuf[0], bover ? '*' : ' ', numbuf[1],
8552                                numbuf[2], bover > 1 ? timebuf : "-");
8553
8554                 if (show_default)
8555                         snprintf(timebuf, sizeof(timebuf), "%llu",
8556                                  (unsigned long long)dqb->dqb_itime);
8557                 else if (iover)
8558                         diff2str(dqb->dqb_itime, timebuf, now);
8559
8560                 snprintf(numbuf[0], sizeof(numbuf),
8561                          (dqb->dqb_valid & QIF_INODES) ? "%ju" : "[%ju]",
8562                          (uintmax_t)dqb->dqb_curinodes);
8563
8564                 if (type == QC_GENERAL)
8565                         sprintf(numbuf[1], (dqb->dqb_valid & QIF_ILIMITS) ?
8566                                 "%ju" : "[%ju]",
8567                                 (uintmax_t)dqb->dqb_isoftlimit);
8568                 else
8569                         sprintf(numbuf[1], "%s", "-");
8570
8571                 sprintf(numbuf[2], (dqb->dqb_valid & QIF_ILIMITS) ?
8572                         "%ju" : "[%ju]", (uintmax_t)dqb->dqb_ihardlimit);
8573
8574                 if (show_default)
8575                         printf(" %6s %7s %7s", numbuf[1], numbuf[2], timebuf);
8576                 else if (type != QC_OSTIDX)
8577                         printf(" %7s%c %6s %7s %7s",
8578                                numbuf[0], iover ? '*' : ' ', numbuf[1],
8579                                numbuf[2], iover > 1 ? timebuf : "-");
8580                 else
8581                         printf(" %7s %7s %7s %7s", "-", "-", "-", "-");
8582                 printf("\n");
8583         } else if (qctl->qc_cmd == LUSTRE_Q_GETINFO || LUSTRE_Q_GETINFOPOOL ||
8584                    qctl->qc_cmd == Q_GETOINFO) {
8585                 char bgtimebuf[40];
8586                 char igtimebuf[40];
8587
8588                 if (qctl->qc_dqinfo.dqi_bgrace == NOTIFY_GRACE_TIME)
8589                         strncpy(bgtimebuf, NOTIFY_GRACE, 40);
8590                 else
8591                         sec2str(qctl->qc_dqinfo.dqi_bgrace, bgtimebuf, rc);
8592                 if (qctl->qc_dqinfo.dqi_igrace == NOTIFY_GRACE_TIME)
8593                         strncpy(igtimebuf, NOTIFY_GRACE, 40);
8594                 else
8595                         sec2str(qctl->qc_dqinfo.dqi_igrace, igtimebuf, rc);
8596
8597                 printf("Block grace time: %s; Inode grace time: %s\n",
8598                        bgtimebuf, igtimebuf);
8599         }
8600 }
8601
8602 static int tgt_name2index(const char *tgtname, unsigned int *idx)
8603 {
8604         char *dash, *endp;
8605
8606         /* format is "lustre-OST0001" */
8607         dash = memchr(tgtname, '-', LUSTRE_MAXFSNAME + 1);
8608         if (!dash) {
8609                 fprintf(stderr, "wrong tgtname format '%s'\n", tgtname);
8610                 return -EINVAL;
8611         }
8612         dash += 4;
8613
8614         *idx = strtoul(dash, &endp, 16);
8615         if (*idx > 0xffff) {
8616                 fprintf(stderr, "wrong index %s\n", tgtname);
8617                 return -ERANGE;
8618         }
8619
8620         return 0;
8621 }
8622
8623 static int print_obd_quota(char *mnt, struct if_quotactl *qctl, int is_mdt,
8624                            bool h, __u64 *total)
8625 {
8626         int rc = 0, rc1 = 0, count = 0, i = 0;
8627         char **list = NULL, *buffer = NULL;
8628         __u32 valid = qctl->qc_valid;
8629
8630         if (qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL && is_mdt)
8631                 return 0;
8632
8633         /* Is it correct for the case OST0000, OST0002, OST0003 -
8634          * we will ask OST0001 that is absent and won't ask OST0003? */
8635         rc = llapi_get_obd_count(mnt, &count, is_mdt);
8636         if (rc) {
8637                 fprintf(stderr, "can not get %s count: %s\n",
8638                         is_mdt ? "mdt" : "ost", strerror(-rc));
8639                 return rc;
8640         }
8641
8642         if (qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL) {
8643                 char fname[PATH_MAX];
8644                 char fsname[LUSTRE_MAXFSNAME + 1];
8645                 int bufsize = sizeof(struct obd_uuid) * count;
8646
8647                 rc = llapi_search_fsname(mnt, fsname);
8648                 if (rc) {
8649                         fprintf(stderr, "cannot get fsname for mountpoint %s\n",
8650                                 mnt);
8651                         goto out;
8652                 }
8653                 buffer = malloc(bufsize + sizeof(*list) * count);
8654                 if (!buffer)
8655                         return -ENOMEM;
8656                 list = (char **)(buffer + bufsize);
8657                 snprintf(fname, PATH_MAX, "%s.%s", fsname, qctl->qc_poolname);
8658                 count = llapi_get_poolmembers(fname, list, count,
8659                                               buffer, bufsize);
8660                 if (count <= 0)
8661                         goto out;
8662         }
8663
8664         for (i = 0; i < count; i++) {
8665                 if (qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL) {
8666                         unsigned int index;
8667
8668                         if (tgt_name2index(list[i], &index))
8669                                 continue;
8670                         qctl->qc_idx = index;
8671                 } else {
8672                         qctl->qc_idx = i;
8673                 }
8674
8675                 qctl->qc_valid = is_mdt ? QC_MDTIDX : QC_OSTIDX;
8676                 rc = llapi_quotactl(mnt, qctl);
8677                 if (rc) {
8678                         /* It is remote client case. */
8679                         if (rc == -EOPNOTSUPP) {
8680                                 rc = 0;
8681                                 goto out;
8682                         }
8683
8684                         /* no target for this index yet */
8685                         if (rc == -ENODEV) {
8686                                 rc = 0;
8687                                 continue;
8688                         }
8689
8690                         /* inactive target */
8691                         if (rc == -ENODATA) {
8692                                 char name[UUID_MAX+8];
8693
8694                                 snprintf(name, sizeof(name), "%s[inact]",
8695                                         obd_uuid2str(&qctl->obd_uuid));
8696                                 memset(&qctl->qc_dqinfo, 0,
8697                                        sizeof(qctl->qc_dqinfo));
8698                                 memset(&qctl->qc_dqblk, 0,
8699                                        sizeof(qctl->qc_dqblk));
8700                                 print_quota(name, qctl, qctl->qc_valid, 0, h,
8701                                             false);
8702                                 rc = 0;
8703                                 continue;
8704                         }
8705
8706                         if (!rc1)
8707                                 rc1 = rc;
8708                         fprintf(stderr, "quotactl %s%d failed.\n",
8709                                 is_mdt ? "mdt" : "ost", qctl->qc_idx);
8710                         continue;
8711                 }
8712
8713                 print_quota(obd_uuid2str(&qctl->obd_uuid), qctl,
8714                             qctl->qc_valid, 0, h, false);
8715                 *total += is_mdt ? qctl->qc_dqblk.dqb_ihardlimit :
8716                                    qctl->qc_dqblk.dqb_bhardlimit;
8717         }
8718 out:
8719         if (buffer)
8720                 free(buffer);
8721         qctl->qc_valid = valid;
8722         return rc ? : rc1;
8723 }
8724
8725 static int get_print_quota(char *mnt, char *name, struct if_quotactl *qctl,
8726                            int verbose, int quiet, bool human_readable,
8727                            bool show_default)
8728 {
8729         int rc1 = 0, rc2 = 0, rc3 = 0;
8730         char *obd_type = (char *)qctl->obd_type;
8731         char *obd_uuid = (char *)qctl->obd_uuid.uuid;
8732         __u64 total_ialloc = 0, total_balloc = 0;
8733         bool use_default_for_blk = false;
8734         bool use_default_for_file = false;
8735         int inacc;
8736
8737         rc1 = llapi_quotactl(mnt, qctl);
8738         if (rc1 < 0) {
8739                 switch (rc1) {
8740                 case -ESRCH:
8741                         fprintf(stderr, "%s quotas are not enabled.\n",
8742                                 qtype_name(qctl->qc_type));
8743                         goto out;
8744                 case -EPERM:
8745                         fprintf(stderr, "Permission denied.\n");
8746                 case -ENODEV:
8747                 case -ENOENT:
8748                         /* We already got error message. */
8749                         goto out;
8750                 default:
8751                         fprintf(stderr, "Unexpected quotactl error: %s\n",
8752                                 strerror(-rc1));
8753                 }
8754         }
8755
8756         if (!show_default && qctl->qc_id == 0) {
8757                 qctl->qc_dqblk.dqb_bhardlimit = 0;
8758                 qctl->qc_dqblk.dqb_bsoftlimit = 0;
8759                 qctl->qc_dqblk.dqb_ihardlimit = 0;
8760                 qctl->qc_dqblk.dqb_isoftlimit = 0;
8761                 qctl->qc_dqblk.dqb_btime = 0;
8762                 qctl->qc_dqblk.dqb_itime = 0;
8763                 qctl->qc_dqblk.dqb_valid |= QIF_LIMITS | QIF_TIMES;
8764         }
8765
8766         if (qctl->qc_dqblk.dqb_valid & QIF_BTIME &&
8767             LQUOTA_FLAG(qctl->qc_dqblk.dqb_btime) & LQUOTA_FLAG_DEFAULT) {
8768                 use_default_for_blk = true;
8769                 qctl->qc_dqblk.dqb_btime &= LQUOTA_GRACE_MASK;
8770         }
8771
8772         if (qctl->qc_dqblk.dqb_valid & QIF_ITIME &&
8773             LQUOTA_FLAG(qctl->qc_dqblk.dqb_itime) & LQUOTA_FLAG_DEFAULT) {
8774                 use_default_for_file = true;
8775                 qctl->qc_dqblk.dqb_itime &= LQUOTA_GRACE_MASK;
8776         }
8777
8778         if ((qctl->qc_cmd == LUSTRE_Q_GETQUOTA ||
8779              qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL ||
8780              qctl->qc_cmd == LUSTRE_Q_GETDEFAULT_POOL ||
8781              qctl->qc_cmd == LUSTRE_Q_GETDEFAULT) && !quiet)
8782                 print_quota_title(name, qctl, human_readable, show_default);
8783
8784         if (rc1 && *obd_type)
8785                 fprintf(stderr, "%s %s ", obd_type, obd_uuid);
8786
8787         if (qctl->qc_valid != QC_GENERAL)
8788                 mnt = "";
8789
8790         inacc = (qctl->qc_cmd == LUSTRE_Q_GETQUOTA ||
8791                  qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL) &&
8792                 ((qctl->qc_dqblk.dqb_valid & (QIF_LIMITS|QIF_USAGE)) !=
8793                  (QIF_LIMITS|QIF_USAGE));
8794
8795         print_quota(mnt, qctl, QC_GENERAL, rc1, human_readable, show_default);
8796
8797         if (!show_default && verbose &&
8798             qctl->qc_valid == QC_GENERAL && qctl->qc_cmd != LUSTRE_Q_GETINFO &&
8799             qctl->qc_cmd != LUSTRE_Q_GETINFOPOOL) {
8800                 char strbuf[STRBUF_LEN];
8801
8802                 rc2 = print_obd_quota(mnt, qctl, 1, human_readable,
8803                                       &total_ialloc);
8804                 rc3 = print_obd_quota(mnt, qctl, 0, human_readable,
8805                                       &total_balloc);
8806                 kbytes2str(total_balloc, strbuf, sizeof(strbuf),
8807                            human_readable);
8808                 printf("Total allocated inode limit: %ju, total allocated block limit: %s\n",
8809                        (uintmax_t)total_ialloc, strbuf);
8810         }
8811
8812         if (use_default_for_blk)
8813                 printf("%cid %u is using default block quota setting\n",
8814                        *qtype_name(qctl->qc_type), qctl->qc_id);
8815
8816         if (use_default_for_file)
8817                 printf("%cid %u is using default file quota setting\n",
8818                        *qtype_name(qctl->qc_type), qctl->qc_id);
8819
8820         if (rc1 || rc2 || rc3 || inacc)
8821                 printf("Some errors happened when getting quota info. Some devices may be not working or deactivated. The data in \"[]\" is inaccurate.\n");
8822 out:
8823         if (rc1)
8824                 return rc1;
8825         if (rc2)
8826                 return rc2;
8827         if (rc3)
8828                 return rc3;
8829         if (inacc)
8830                 return -EIO;
8831
8832         return 0;
8833 }
8834
8835 static int lfs_project(int argc, char **argv)
8836 {
8837         int ret = 0, err = 0, c, i;
8838         struct project_handle_control phc = { 0 };
8839         enum lfs_project_ops_t op;
8840
8841         phc.newline = true;
8842         phc.assign_projid = false;
8843         /* default action */
8844         op = LFS_PROJECT_LIST;
8845
8846         while ((c = getopt(argc, argv, "p:cCsdkr0")) != -1) {
8847                 switch (c) {
8848                 case 'c':
8849                         if (op != LFS_PROJECT_LIST) {
8850                                 fprintf(stderr,
8851                                         "%s: cannot specify '-c' '-C' '-s' together\n",
8852                                         progname);
8853                                 return CMD_HELP;
8854                         }
8855
8856                         op = LFS_PROJECT_CHECK;
8857                         break;
8858                 case 'C':
8859                         if (op != LFS_PROJECT_LIST) {
8860                                 fprintf(stderr,
8861                                         "%s: cannot specify '-c' '-C' '-s' together\n",
8862                                         progname);
8863                                 return CMD_HELP;
8864                         }
8865
8866                         op = LFS_PROJECT_CLEAR;
8867                         break;
8868                 case 's':
8869                         if (op != LFS_PROJECT_LIST) {
8870                                 fprintf(stderr,
8871                                         "%s: cannot specify '-c' '-C' '-s' together\n",
8872                                         progname);
8873                                 return CMD_HELP;
8874                         }
8875
8876                         phc.set_inherit = true;
8877                         op = LFS_PROJECT_SET;
8878                         break;
8879                 case 'd':
8880                         phc.dironly = true;
8881                         break;
8882                 case 'k':
8883                         phc.keep_projid = true;
8884                         break;
8885                 case 'r':
8886                         phc.recursive = true;
8887                         break;
8888                 case 'p':
8889                         if (str2quotaid(&phc.projid, optarg)) {
8890                                 fprintf(stderr,
8891                                         "Invalid project ID: %s\n",
8892                                         optarg);
8893                                 return CMD_HELP;
8894                         }
8895
8896                         phc.assign_projid = true;
8897
8898                         break;
8899                 case '0':
8900                         phc.newline = false;
8901                         break;
8902                 default:
8903                         fprintf(stderr, "%s: invalid option '%c'\n",
8904                                 progname, optopt);
8905                         return CMD_HELP;
8906                 }
8907         }
8908
8909         if (phc.assign_projid && op == LFS_PROJECT_LIST) {
8910                 op = LFS_PROJECT_SET;
8911                 phc.set_projid = true;
8912         } else if (phc.assign_projid && op == LFS_PROJECT_SET) {
8913                 phc.set_projid = true;
8914         }
8915
8916         switch (op) {
8917         case LFS_PROJECT_CHECK:
8918                 if (phc.keep_projid) {
8919                         fprintf(stderr,
8920                                 "%s: '-k' is useless together with '-c'\n",
8921                                 progname);
8922                         return CMD_HELP;
8923                 }
8924                 break;
8925         case LFS_PROJECT_CLEAR:
8926                 if (!phc.newline) {
8927                         fprintf(stderr,
8928                                 "%s: '-0' is useless together with '-C'\n",
8929                                 progname);
8930                         return CMD_HELP;
8931                 }
8932                 if (phc.assign_projid) {
8933                         fprintf(stderr,
8934                                 "%s: '-p' is useless together with '-C'\n",
8935                                 progname);
8936                         return CMD_HELP;
8937                 }
8938                 break;
8939         case LFS_PROJECT_SET:
8940                 if (!phc.newline) {
8941                         fprintf(stderr,
8942                                 "%s: '-0' is useless together with '-s'\n",
8943                                 progname);
8944                         return CMD_HELP;
8945                 }
8946                 if (phc.keep_projid) {
8947                         fprintf(stderr,
8948                                 "%s: '-k' is useless together with '-s'\n",
8949                                 progname);
8950                         return CMD_HELP;
8951                 }
8952                 break;
8953         default:
8954                 if (!phc.newline) {
8955                         fprintf(stderr,
8956                                 "%s: '-0' is useless for list operations\n",
8957                                 progname);
8958                         return CMD_HELP;
8959                 }
8960                 break;
8961         }
8962
8963         argv += optind;
8964         argc -= optind;
8965         if (argc == 0) {
8966                 fprintf(stderr, "%s: missing file or directory target(s)\n",
8967                         progname);
8968                 return CMD_HELP;
8969         }
8970
8971         for (i = 0; i < argc; i++) {
8972                 switch (op) {
8973                 case LFS_PROJECT_CHECK:
8974                         err = lfs_project_check(argv[i], &phc);
8975                         break;
8976                 case LFS_PROJECT_LIST:
8977                         err = lfs_project_list(argv[i], &phc);
8978                         break;
8979                 case LFS_PROJECT_CLEAR:
8980                         err = lfs_project_clear(argv[i], &phc);
8981                         break;
8982                 case LFS_PROJECT_SET:
8983                         err = lfs_project_set(argv[i], &phc);
8984                         break;
8985                 default:
8986                         break;
8987                 }
8988                 if (err && !ret)
8989                         ret = err;
8990         }
8991
8992         return ret;
8993 }
8994
8995 static int lfs_quota(int argc, char **argv)
8996 {
8997         int c;
8998         char *mnt, *name = NULL;
8999         struct if_quotactl *qctl;
9000         char *obd_uuid;
9001         int rc = 0, rc1 = 0, verbose = 0, quiet = 0;
9002         __u32 valid = QC_GENERAL, idx = 0;
9003         bool human_readable = false;
9004         bool show_default = false;
9005         int qtype;
9006         bool show_pools = false;
9007         struct option long_opts[] = {
9008         { .val = LFS_POOL_OPT, .name = "pool", .has_arg = optional_argument },
9009         { .name = NULL } };
9010         char **poollist = NULL;
9011         char *buf = NULL;
9012         int poolcount, i;
9013
9014         qctl = calloc(1, sizeof(*qctl) + LOV_MAXPOOLNAME + 1);
9015         if (!qctl)
9016                 return -ENOMEM;
9017
9018         qctl->qc_cmd = LUSTRE_Q_GETQUOTA;
9019         qctl->qc_type = ALLQUOTA;
9020         obd_uuid = (char *)qctl->obd_uuid.uuid;
9021
9022         while ((c = getopt_long(argc, argv, "gGi:I:o:pPqtuUvh",
9023                 long_opts, NULL)) != -1) {
9024                 switch (c) {
9025                 case 'U':
9026                         show_default = true;
9027                 case 'u':
9028                         qtype = USRQUOTA;
9029                         goto quota_type;
9030                 case 'G':
9031                         show_default = true;
9032                 case 'g':
9033                         qtype = GRPQUOTA;
9034                         goto quota_type;
9035                 case 'P':
9036                         show_default = true;
9037                 case 'p':
9038                         qtype = PRJQUOTA;
9039 quota_type:
9040                         if (qctl->qc_type != ALLQUOTA) {
9041                                 fprintf(stderr,
9042                                         "%s quota: only one of -u, -g, or -p may be specified\n",
9043                                         progname);
9044                                 rc = CMD_HELP;
9045                                 goto out;
9046                         }
9047                         qctl->qc_type = qtype;
9048                         break;
9049                 case 't':
9050                         qctl->qc_cmd = LUSTRE_Q_GETINFO;
9051                         break;
9052                 case 'o':
9053                         valid = qctl->qc_valid = QC_UUID;
9054                         snprintf(obd_uuid, sizeof(*obd_uuid), "%s", optarg);
9055                         break;
9056                 case 'i':
9057                         valid = qctl->qc_valid = QC_MDTIDX;
9058                         idx = qctl->qc_idx = atoi(optarg);
9059                         if (idx == 0 && *optarg != '0') {
9060                                 fprintf(stderr,
9061                                         "%s quota: invalid MDT index '%s'\n",
9062                                         progname, optarg);
9063                                 rc = CMD_HELP;
9064                                 goto out;
9065                         }
9066                         break;
9067                 case 'I':
9068                         valid = qctl->qc_valid = QC_OSTIDX;
9069                         idx = qctl->qc_idx = atoi(optarg);
9070                         if (idx == 0 && *optarg != '0') {
9071                                 fprintf(stderr,
9072                                         "%s quota: invalid OST index '%s'\n",
9073                                         progname, optarg);
9074                                 rc = CMD_HELP;
9075                                 goto out;
9076                         }
9077                         break;
9078                 case 'v':
9079                         verbose = 1;
9080                         break;
9081                 case 'q':
9082                         quiet = 1;
9083                         break;
9084                 case 'h':
9085                         human_readable = true;
9086                         break;
9087                 case LFS_POOL_OPT:
9088                         if ((!optarg) && (argv[optind] != NULL) &&
9089                                 (argv[optind][0] != '-') &&
9090                                 (argv[optind][0] != '/')) {
9091                                 optarg = argv[optind++];
9092                                 if (lfs_verify_poolarg(optarg)) {
9093                                         rc = -EINVAL;
9094                                         goto out;
9095                                 }
9096                                 strncpy(qctl->qc_poolname, optarg,
9097                                         LOV_MAXPOOLNAME);
9098                                 if (qctl->qc_cmd == LUSTRE_Q_GETINFO)
9099                                         qctl->qc_cmd = LUSTRE_Q_GETINFOPOOL;
9100                                 else
9101                                         qctl->qc_cmd = LUSTRE_Q_GETQUOTAPOOL;
9102                                 break;
9103                         }
9104
9105                         /* optarg is NULL */
9106                         show_pools = true;
9107                         qctl->qc_cmd = LUSTRE_Q_GETQUOTAPOOL;
9108                         break;
9109                 default:
9110                         fprintf(stderr, "%s quota: unrecognized option '%s'\n",
9111                                 progname, argv[optind - 1]);
9112                         rc = CMD_HELP;
9113                         goto out;
9114                 }
9115         }
9116
9117         /* current uid/gid info for "lfs quota /path/to/lustre/mount" */
9118         if ((qctl->qc_cmd == LUSTRE_Q_GETQUOTA ||
9119              qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL) &&
9120              qctl->qc_type == ALLQUOTA &&
9121              optind == argc - 1 && !show_default) {
9122                 qctl->qc_idx = idx;
9123
9124                 for (qtype = USRQUOTA; qtype <= GRPQUOTA; qtype++) {
9125                         qctl->qc_type = qtype;
9126                         qctl->qc_valid = valid;
9127                         if (qtype == USRQUOTA) {
9128                                 qctl->qc_id = geteuid();
9129                                 rc = uid2name(&name, qctl->qc_id);
9130                         } else {
9131                                 qctl->qc_id = getegid();
9132                                 rc = gid2name(&name, qctl->qc_id);
9133                                 memset(&qctl->qc_dqblk, 0,
9134                                        sizeof(qctl->qc_dqblk));
9135                         }
9136                         if (rc)
9137                                 name = "<unknown>";
9138                         mnt = argv[optind];
9139                         rc1 = get_print_quota(mnt, name, qctl, verbose, quiet,
9140                                               human_readable, show_default);
9141                         if (rc1 && !rc)
9142                                 rc = rc1;
9143                 }
9144                 goto out;
9145         /* lfs quota -u username /path/to/lustre/mount */
9146         } else if (qctl->qc_cmd == LUSTRE_Q_GETQUOTA ||
9147                    qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL) {
9148                 /* options should be followed by u/g-name and mntpoint */
9149                 if ((!show_default && optind + 2 != argc) ||
9150                     (show_default && optind + 1 != argc) ||
9151                     qctl->qc_type == ALLQUOTA) {
9152                         fprintf(stderr,
9153                                 "%s quota: name and mount point must be specified\n",
9154                                 progname);
9155                         rc = CMD_HELP;
9156                         goto out;
9157                 }
9158
9159                 if (!show_default) {
9160                         name = argv[optind++];
9161                         switch (qctl->qc_type) {
9162                         case USRQUOTA:
9163                                 rc = name2uid(&qctl->qc_id, name);
9164                                 break;
9165                         case GRPQUOTA:
9166                                 rc = name2gid(&qctl->qc_id, name);
9167                                 break;
9168                         case PRJQUOTA:
9169                                 rc = name2projid(&qctl->qc_id, name);
9170                                 break;
9171                         default:
9172                                 rc = -ENOTSUP;
9173                                 break;
9174                         }
9175                 } else {
9176                         qctl->qc_valid = QC_GENERAL;
9177                         qctl->qc_cmd = qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL ?
9178                                         LUSTRE_Q_GETDEFAULT_POOL :
9179                                         LUSTRE_Q_GETDEFAULT;
9180                         qctl->qc_id = 0;
9181                 }
9182
9183                 if (rc) {
9184                         if (str2quotaid(&qctl->qc_id, name)) {
9185                                 fprintf(stderr, "%s quota: invalid id '%s'\n",
9186                                         progname, name);
9187                                 rc = CMD_HELP;
9188                                 goto out;
9189                         }
9190                 }
9191         } else if (optind + 1 != argc || qctl->qc_type == ALLQUOTA) {
9192                 fprintf(stderr, "%s quota: missing quota info argument(s)\n",
9193                         progname);
9194                 rc = CMD_HELP;
9195                 goto out;
9196         }
9197
9198         mnt = argv[optind];
9199         if (show_pools) {
9200                 char *p;
9201
9202                 i = 0;
9203                 rc = llapi_get_poolbuf(mnt, &buf, &poollist, &poolcount);
9204                 if (rc)
9205                         goto out;
9206
9207                 for (i = 0; i < poolcount; i++) {
9208                         p = memchr(poollist[i], '.', MAXNAMLEN);
9209                         if (!p) {
9210                                 fprintf(stderr, "bad string format %.*s\n",
9211                                         MAXNAMLEN, poollist[i]);
9212                                 rc = -EINVAL;
9213                                 goto out;
9214                         }
9215                         p++;
9216                         printf("Quotas for pool: %s\n", p);
9217                         strncpy(qctl->qc_poolname, p, LOV_MAXPOOLNAME);
9218                         rc = get_print_quota(mnt, name, qctl, verbose, quiet,
9219                                              human_readable, show_default);
9220                         if (rc)
9221                                 break;
9222                 }
9223                 goto out;
9224         }
9225
9226         rc = get_print_quota(mnt, name, qctl, verbose, quiet,
9227                              human_readable, show_default);
9228 out:
9229         free(buf);
9230         free(qctl);
9231         return rc;
9232 }
9233 #endif /* HAVE_SYS_QUOTA_H! */
9234
9235 static int flushctx_ioctl(char *mp)
9236 {
9237         int fd, rc;
9238
9239         fd = open(mp, O_RDONLY);
9240         if (fd == -1) {
9241                 fprintf(stderr, "flushctx: error open %s: %s\n",
9242                         mp, strerror(errno));
9243                 return -1;
9244         }
9245
9246         rc = ioctl(fd, LL_IOC_FLUSHCTX);
9247         if (rc == -1)
9248                 fprintf(stderr, "flushctx: error ioctl %s: %s\n",
9249                         mp, strerror(errno));
9250
9251         close(fd);
9252         return rc;
9253 }
9254
9255 static int lfs_flushctx(int argc, char **argv)
9256 {
9257         int     kdestroy = 0, reap = 0, c;
9258         char    mntdir[PATH_MAX] = {'\0'};
9259         int     index = 0;
9260         int     rc = 0;
9261
9262         while ((c = getopt(argc, argv, "kr")) != -1) {
9263                 switch (c) {
9264                 case 'k':
9265                         kdestroy = 1;
9266                         break;
9267                 case 'r':
9268                         reap = 1;
9269                         break;
9270                 default:
9271                         fprintf(stderr,
9272                                 "error: %s: option '-%c' unrecognized\n",
9273                                 argv[0], c);
9274                         return CMD_HELP;
9275                 }
9276         }
9277
9278         if (kdestroy) {
9279                 rc = system("kdestroy > /dev/null");
9280                 if (rc) {
9281                         rc = WEXITSTATUS(rc);
9282                         fprintf(stderr,
9283                                 "error destroying tickets: %d, continuing\n",
9284                                 rc);
9285                 }
9286         }
9287
9288         if (optind >= argc) {
9289                 /* flush for all mounted lustre fs. */
9290                 while (!llapi_search_mounts(NULL, index++, mntdir, NULL)) {
9291                         /* Check if we have a mount point */
9292                         if (mntdir[0] == '\0')
9293                                 continue;
9294
9295                         if (flushctx_ioctl(mntdir))
9296                                 rc = -1;
9297
9298                         mntdir[0] = '\0'; /* avoid matching in next loop */
9299                 }
9300         } else {
9301                 /* flush fs as specified */
9302                 while (optind < argc) {
9303                         if (flushctx_ioctl(argv[optind++]))
9304                                 rc = -1;
9305                 }
9306         }
9307
9308         if (reap) {
9309                 rc = system("keyctl reap > /dev/null");
9310                 if (rc != 0) {
9311                         rc = WEXITSTATUS(rc);
9312                         fprintf(stderr, "error reaping keyring: %d\n", rc);
9313                 }
9314         }
9315
9316         return rc;
9317 }
9318
9319 static int lfs_changelog(int argc, char **argv)
9320 {
9321         void *changelog_priv;
9322         struct changelog_rec *rec;
9323         long long startrec = 0, endrec = 0;
9324         char *mdd;
9325         struct option long_opts[] = {
9326                 { .val = 'f', .name = "follow", .has_arg = no_argument },
9327                 { .name = NULL } };
9328         char short_opts[] = "f";
9329         int rc, follow = 0;
9330
9331         while ((rc = getopt_long(argc, argv, short_opts,
9332                 long_opts, NULL)) != -1) {
9333                 switch (rc) {
9334                 case 'f':
9335                         follow++;
9336                         break;
9337                 default:
9338                         fprintf(stderr,
9339                                 "%s changelog: unrecognized option '%s'\n",
9340                                 progname, argv[optind - 1]);
9341                         return CMD_HELP;
9342                 }
9343         }
9344         if (optind >= argc) {
9345                 fprintf(stderr, "%s changelog: mdtname must be specified\n",
9346                         progname);
9347                 return CMD_HELP;
9348         }
9349
9350         mdd = argv[optind++];
9351         if (argc > optind) {
9352                 errno = 0;
9353                 startrec = strtoll(argv[optind++], NULL, 10);
9354                 if (errno != 0 || startrec < 0) {
9355                         fprintf(stderr,
9356                                 "%s changelog: bad startrec\n",
9357                                 progname);
9358                         return CMD_HELP;
9359                 }
9360         }
9361
9362         if (argc > optind) {
9363                 errno = 0;
9364                 endrec = strtoll(argv[optind++], NULL, 10);
9365                 if (errno != 0 || endrec < 0) {
9366                         fprintf(stderr,
9367                                 "%s changelog: bad endrec\n",
9368                                 progname);
9369                         return CMD_HELP;
9370                 }
9371         }
9372
9373         rc = llapi_changelog_start(&changelog_priv,
9374                                    CHANGELOG_FLAG_BLOCK |
9375                                    CHANGELOG_FLAG_JOBID |
9376                                    CHANGELOG_FLAG_EXTRA_FLAGS |
9377                                    (follow ? CHANGELOG_FLAG_FOLLOW : 0),
9378                                    mdd, startrec);
9379         if (rc < 0) {
9380                 fprintf(stderr, "%s changelog: cannot start changelog: %s\n",
9381                         progname, strerror(errno = -rc));
9382                 return rc;
9383         }
9384
9385         rc = llapi_changelog_set_xflags(changelog_priv,
9386                                         CHANGELOG_EXTRA_FLAG_UIDGID |
9387                                         CHANGELOG_EXTRA_FLAG_NID |
9388                                         CHANGELOG_EXTRA_FLAG_OMODE |
9389                                         CHANGELOG_EXTRA_FLAG_XATTR);
9390         if (rc < 0) {
9391                 fprintf(stderr,
9392                         "%s changelog: cannot set xflags for changelog: %s\n",
9393                         progname, strerror(errno = -rc));
9394                 return rc;
9395         }
9396
9397         while ((rc = llapi_changelog_recv(changelog_priv, &rec)) == 0) {
9398                 time_t secs;
9399                 struct tm ts;
9400
9401                 if (endrec && rec->cr_index > endrec) {
9402                         llapi_changelog_free(&rec);
9403                         break;
9404                 }
9405                 if (rec->cr_index < startrec) {
9406                         llapi_changelog_free(&rec);
9407                         continue;
9408                 }
9409
9410                 secs = rec->cr_time >> 30;
9411                 gmtime_r(&secs, &ts);
9412                 printf("%ju %02d%-5s %02d:%02d:%02d.%09d %04d.%02d.%02d "
9413                        "0x%x t="DFID, (uintmax_t)rec->cr_index, rec->cr_type,
9414                        changelog_type2str(rec->cr_type),
9415                        ts.tm_hour, ts.tm_min, ts.tm_sec,
9416                        (int)(rec->cr_time & ((1 << 30) - 1)),
9417                        ts.tm_year + 1900, ts.tm_mon + 1, ts.tm_mday,
9418                        rec->cr_flags & CLF_FLAGMASK, PFID(&rec->cr_tfid));
9419
9420                 if (rec->cr_flags & CLF_JOBID) {
9421                         struct changelog_ext_jobid *jid =
9422                                 changelog_rec_jobid(rec);
9423
9424                         if (jid->cr_jobid[0] != '\0')
9425                                 printf(" j=%s", jid->cr_jobid);
9426                 }
9427
9428                 if (rec->cr_flags & CLF_EXTRA_FLAGS) {
9429                         struct changelog_ext_extra_flags *ef =
9430                                 changelog_rec_extra_flags(rec);
9431
9432                         printf(" ef=0x%llx",
9433                                (unsigned long long)ef->cr_extra_flags);
9434
9435                         if (ef->cr_extra_flags & CLFE_UIDGID) {
9436                                 struct changelog_ext_uidgid *uidgid =
9437                                         changelog_rec_uidgid(rec);
9438
9439                                 printf(" u=%llu:%llu",
9440                                        (unsigned long long)uidgid->cr_uid,
9441                                        (unsigned long long)uidgid->cr_gid);
9442                         }
9443                         if (ef->cr_extra_flags & CLFE_NID) {
9444                                 struct changelog_ext_nid *nid =
9445                                         changelog_rec_nid(rec);
9446
9447                                 printf(" nid=%s",
9448                                        libcfs_nid2str(nid->cr_nid));
9449                         }
9450
9451                         if (ef->cr_extra_flags & CLFE_OPEN) {
9452                                 struct changelog_ext_openmode *omd =
9453                                         changelog_rec_openmode(rec);
9454                                 char mode[] = "---";
9455
9456                                 /* exec mode must be exclusive */
9457                                 if (omd->cr_openflags & MDS_FMODE_EXEC) {
9458                                         mode[2] = 'x';
9459                                 } else {
9460                                         if (omd->cr_openflags & MDS_FMODE_READ)
9461                                                 mode[0] = 'r';
9462                                         if (omd->cr_openflags &
9463                                             (MDS_FMODE_WRITE |
9464                                              MDS_OPEN_TRUNC |
9465                                              MDS_OPEN_APPEND))
9466                                                 mode[1] = 'w';
9467                                 }
9468
9469                                 if (strcmp(mode, "---") != 0)
9470                                         printf(" m=%s", mode);
9471                         }
9472
9473                         if (ef->cr_extra_flags & CLFE_XATTR) {
9474                                 struct changelog_ext_xattr *xattr =
9475                                         changelog_rec_xattr(rec);
9476
9477                                 if (xattr->cr_xattr[0] != '\0')
9478                                         printf(" x=%s", xattr->cr_xattr);
9479                         }
9480                 }
9481
9482                 if (!fid_is_zero(&rec->cr_pfid))
9483                         printf(" p="DFID, PFID(&rec->cr_pfid));
9484                 if (rec->cr_namelen)
9485                         printf(" %.*s", rec->cr_namelen,
9486                                changelog_rec_name(rec));
9487
9488                 if (rec->cr_flags & CLF_RENAME) {
9489                         struct changelog_ext_rename *rnm =
9490                                 changelog_rec_rename(rec);
9491
9492                         if (!fid_is_zero(&rnm->cr_sfid))
9493                                 printf(" s="DFID" sp="DFID" %.*s",
9494                                        PFID(&rnm->cr_sfid),
9495                                        PFID(&rnm->cr_spfid),
9496                                        (int)changelog_rec_snamelen(rec),
9497                                        changelog_rec_sname(rec));
9498                 }
9499                 printf("\n");
9500
9501                 llapi_changelog_free(&rec);
9502         }
9503
9504         llapi_changelog_fini(&changelog_priv);
9505
9506         if (rc < 0)
9507                 fprintf(stderr, "%s changelog: cannot access changelog: %s\n",
9508                         progname, strerror(errno = -rc));
9509
9510         return (rc == 1 ? 0 : rc);
9511 }
9512
9513 static int lfs_changelog_clear(int argc, char **argv)
9514 {
9515         long long endrec;
9516         int rc;
9517
9518         if (argc != 4)
9519                 return CMD_HELP;
9520
9521         errno = 0;
9522         endrec = strtoll(argv[3], NULL, 10);
9523         if (errno != 0 || endrec < 0) {
9524                 fprintf(stderr,
9525                         "%s: bad endrec '%s'\n",
9526                         argv[0], argv[3]);
9527                 return CMD_HELP;
9528         }
9529
9530         rc = llapi_changelog_clear(argv[1], argv[2], endrec);
9531
9532         if (rc == -EINVAL)
9533                 fprintf(stderr, "%s: record out of range: %llu\n",
9534                         argv[0], endrec);
9535         else if (rc == -ENOENT)
9536                 fprintf(stderr, "%s: no changelog user: %s\n",
9537                         argv[0], argv[2]);
9538         else if (rc)
9539                 fprintf(stderr, "%s error: %s\n", argv[0],
9540                         strerror(-rc));
9541
9542         if (rc)
9543                 errno = -rc;
9544
9545         return rc;
9546 }
9547
9548 static void rstripc(char *str, int c)
9549 {
9550         char *end = str + strlen(str);
9551
9552         for (; str < end && end[-1] == c; --end)
9553                 end[-1] = '\0';
9554 }
9555
9556 static int lfs_fid2path(int argc, char **argv)
9557 {
9558         struct option long_opts[] = {
9559                 { .val = 'c',   .name = "cur",  .has_arg = no_argument },
9560                 { .val = 'c',   .name = "current",      .has_arg = no_argument },
9561                 { .val = 'c',   .name = "print-link",   .has_arg = no_argument },
9562                 { .val = 'f',   .name = "print-fid",    .has_arg = no_argument },
9563                 { .val = 'l',   .name = "link", .has_arg = required_argument },
9564                 { .name = NULL } };
9565         char short_opts[] = "cfl:pr:";
9566         bool print_link = false;
9567         bool print_fid = false;
9568         bool print_mnt_dir;
9569         char mnt_dir[PATH_MAX] = "";
9570         int mnt_fd = -1;
9571         char *path_or_fsname;
9572         long long recno = -1;
9573         int linkno = -1;
9574         char *endptr = NULL;
9575         int rc = 0;
9576         int c;
9577         int i;
9578
9579         while ((c = getopt_long(argc, argv, short_opts, long_opts, NULL)) != -1) {
9580                 switch (c) {
9581                 case 'c':
9582                         print_link = true;
9583                         break;
9584                 case 'f':
9585                         print_fid = true;
9586                         break;
9587                 case 'l':
9588                         errno = 0;
9589                         linkno = strtol(optarg, &endptr, 10);
9590                         if (errno != 0 || *endptr != '\0' || linkno < 0) {
9591                                 fprintf(stderr,
9592                                         "%s fid2path: invalid linkno '%s'\n",
9593                                         progname, optarg);
9594                                 return CMD_HELP;
9595                         }
9596                         break;
9597                 case 'r':
9598                         /* recno is something to do with changelogs
9599                          * that was never implemented. We just pass it
9600                          * through for the MDT to ignore.
9601                          */
9602                         errno = 0;
9603                         recno = strtoll(optarg, &endptr, 10);
9604                         if (errno != 0 || *endptr != '\0' || recno < 0) {
9605                                 fprintf(stderr,
9606                                         "%s fid2path: invalid recno '%s'\n",
9607                                         progname, optarg);
9608                                 return CMD_HELP;
9609                         }
9610                         break;
9611                 default:
9612                         fprintf(stderr,
9613                                 "%s fid2path: unrecognized option '%s'\n",
9614                                 progname, argv[optind - 1]);
9615                         return CMD_HELP;
9616                 }
9617         }
9618
9619         if (argc - optind < 2) {
9620                 fprintf(stderr,
9621                         "Usage: %s fid2path FSNAME|ROOT FID...\n",
9622                         progname);
9623                 return CMD_HELP;
9624         }
9625
9626         path_or_fsname = argv[optind];
9627
9628         if (*path_or_fsname == '/') {
9629                 print_mnt_dir = true;
9630                 rc = llapi_search_mounts(path_or_fsname, 0, mnt_dir, NULL);
9631         } else {
9632                 print_mnt_dir = false;
9633                 rc = llapi_search_rootpath(mnt_dir, path_or_fsname);
9634         }
9635
9636         if (rc < 0) {
9637                 fprintf(stderr,
9638                         "%s fid2path: cannot resolve mount point for '%s': %s\n",
9639                         progname, path_or_fsname, strerror(-rc));
9640                 goto out;
9641         }
9642
9643         mnt_fd = open(mnt_dir, O_RDONLY | O_DIRECTORY);
9644         if (mnt_fd < 0) {
9645                 fprintf(stderr,
9646                         "%s fid2path: cannot open mount point for '%s': %s\n",
9647                         progname, path_or_fsname, strerror(-rc));
9648                 goto out;
9649         }
9650
9651         /* Strip trailing slashes from mnt_dir. */
9652         rstripc(mnt_dir + 1, '/');
9653
9654         for (i = optind + 1; i < argc; i++) {
9655                 const char *fid_str = argv[i];
9656                 struct lu_fid fid;
9657                 int rc2;
9658
9659                 rc2 = llapi_fid_parse(fid_str, &fid, NULL);
9660                 if (rc2 < 0) {
9661                         fprintf(stderr,
9662                                 "%s fid2path: invalid FID '%s'\n",
9663                                 progname, fid_str);
9664                         if (rc == 0)
9665                                 rc = rc2;
9666
9667                         continue;
9668                 }
9669
9670                 int linktmp = (linkno >= 0) ? linkno : 0;
9671                 while (1) {
9672                         int oldtmp = linktmp;
9673                         long long rectmp = recno;
9674                         char path_buf[PATH_MAX];
9675
9676                         rc2 = llapi_fid2path_at(mnt_fd, &fid,
9677                                 path_buf, sizeof(path_buf), &rectmp, &linktmp);
9678                         if (rc2 < 0) {
9679                                 fprintf(stderr,
9680                                         "%s fid2path: cannot find %s %s: %s\n",
9681                                         progname, path_or_fsname, fid_str,
9682                                         strerror(-rc2));
9683                                 if (rc == 0)
9684                                         rc = rc2;
9685                                 break;
9686                         }
9687
9688                         if (print_fid)
9689                                 printf("%s ", fid_str);
9690
9691                         if (print_link)
9692                                 printf("%d ", linktmp);
9693
9694                         /* You may think this looks wrong or weird (and it is!)
9695                          * but we are actually trying to preserve the old quirky
9696                          * behaviors (enforced by our old quirky tests!) that
9697                          * make lfs so much fun to work on:
9698                          *
9699                          *   lustre 0x200000007:0x1:0x0 => "/"
9700                          *   /mnt/lustre 0x200000007:0x1:0x0 => "/mnt/lustre//"
9701                          *
9702                          * Note that llapi_fid2path() returns "" for the root
9703                          * FID. */
9704
9705                         printf("%s%s%s\n",
9706                                print_mnt_dir ? mnt_dir : "",
9707                                (print_mnt_dir || *path_buf == '\0') ? "/" : "",
9708                                path_buf);
9709
9710                         if (linkno >= 0)
9711                                 /* specified linkno */
9712                                 break;
9713
9714                         if (oldtmp == linktmp)
9715                                 /* no more links */
9716                                 break;
9717                 }
9718         }
9719 out:
9720         if (!(mnt_fd < 0))
9721                 close(mnt_fd);
9722
9723         return rc;
9724 }
9725
9726 static int lfs_path2fid(int argc, char **argv)
9727 {
9728         struct option long_opts[] = {
9729                 { .val = 'p', .name = "parents", .has_arg = no_argument },
9730                 { .name = NULL } };
9731         char            **path;
9732         const char        short_opts[] = "p";
9733         const char       *sep = "";
9734         struct lu_fid     fid;
9735         int               rc = 0;
9736         bool              show_parents = false;
9737
9738         while ((rc = getopt_long(argc, argv, short_opts,
9739                                  long_opts, NULL)) != -1) {
9740                 switch (rc) {
9741                 case 'p':
9742                         show_parents = true;
9743                         break;
9744                 default:
9745                         fprintf(stderr,
9746                                 "%s path2fid: unrecognized option '%s'\n",
9747                                 progname, argv[optind - 1]);
9748                         return CMD_HELP;
9749                 }
9750         }
9751
9752         if (optind > argc - 1) {
9753                 fprintf(stderr, "%s path2fid: FILE... must be specified\n",
9754                         progname);
9755                 return CMD_HELP;
9756         } else if (optind < argc - 1) {
9757                 sep = ": ";
9758         }
9759
9760         rc = 0;
9761         for (path = argv + optind; *path != NULL; path++) {
9762                 int err = 0;
9763
9764                 if (!show_parents) {
9765                         err = llapi_path2fid(*path, &fid);
9766                         if (!err)
9767                                 printf("%s%s"DFID"\n",
9768                                        *sep != '\0' ? *path : "", sep,
9769                                        PFID(&fid));
9770                 } else {
9771                         char            name[NAME_MAX + 1];
9772                         unsigned int    linkno = 0;
9773
9774                         while ((err = llapi_path2parent(*path, linkno, &fid,
9775                                                 name, sizeof(name))) == 0) {
9776                                 if (*sep != '\0' && linkno == 0)
9777                                         printf("%s%s", *path, sep);
9778
9779                                 printf("%s"DFID"/%s", linkno != 0 ? "\t" : "",
9780                                        PFID(&fid), name);
9781                                 linkno++;
9782                         }
9783
9784                         /* err == -ENODATA is end-of-loop */
9785                         if (linkno > 0 && err == -ENODATA) {
9786                                 printf("\n");
9787                                 err = 0;
9788                         }
9789                 }
9790
9791                 if (err) {
9792                         fprintf(stderr,
9793                                 "%s path2fid: cannot get %sfid for '%s': %s\n",
9794                                 progname, show_parents ? "parent " : "", *path,
9795                                 strerror(-err));
9796                         if (rc == 0) {
9797                                 rc = err;
9798                                 errno = -err;
9799                         }
9800                 }
9801         }
9802
9803         return rc;
9804 }
9805
9806 #define MAX_ERRNO       4095
9807 #define IS_ERR_VALUE(x) ((unsigned long)(x) >= (unsigned long)-MAX_ERRNO)
9808
9809 static int lfs_rmfid_and_show_errors(const char *device, struct fid_array *fa)
9810 {
9811         int rc, rc2, k;
9812
9813         rc = llapi_rmfid(device, fa);
9814         if (rc < 0) {
9815                 fprintf(stderr, "%s rmfid: cannot remove FIDs: %s\n",
9816                         progname, strerror(-rc));
9817                 return rc;
9818         }
9819
9820         for (k = 0; k < fa->fa_nr; k++) {
9821                 rc2 = (__s32)fa->fa_fids[k].f_ver;
9822                 if (!IS_ERR_VALUE(rc2))
9823                         continue;
9824
9825                 if (rc == 0)
9826                         rc = rc2;
9827
9828                 fa->fa_fids[k].f_ver = 0;
9829                 fprintf(stderr, "%s rmfid: cannot remove "DFID": %s\n",
9830                         progname, PFID(&fa->fa_fids[k]), strerror(-rc2));
9831         }
9832
9833         return rc;
9834 }
9835
9836 static int lfs_rmfid(int argc, char **argv)
9837 {
9838         char *fidstr, *device;
9839         int rc = 0, rc2, nr;
9840         struct fid_array *fa;
9841
9842         if (optind > argc - 1) {
9843                 fprintf(stderr, "%s rmfid: missing dirname\n", progname);
9844                 return CMD_HELP;
9845         }
9846
9847         device = argv[optind++];
9848
9849         nr = argc - optind;
9850         fa = malloc(offsetof(struct fid_array, fa_fids[nr + 1]));
9851         if (!fa)
9852                 return -ENOMEM;
9853
9854         fa->fa_nr = 0;
9855         rc = 0;
9856         while (optind < argc) {
9857                 int found;
9858
9859                 fidstr = argv[optind++];
9860                 while (*fidstr == '[')
9861                         fidstr++;
9862                 found = sscanf(fidstr, SFID, RFID(&fa->fa_fids[fa->fa_nr]));
9863                 if (found != 3) {
9864                         fprintf(stderr, "unrecognized FID: %s\n",
9865                                 argv[optind - 1]);
9866                         exit(1);
9867                 }
9868                 fa->fa_nr++;
9869                 if (fa->fa_nr == OBD_MAX_FIDS_IN_ARRAY) {
9870                         /* start another batch */
9871                         rc2 = lfs_rmfid_and_show_errors(device, fa);
9872                         if (rc2 && !rc)
9873                                 rc = rc2;
9874                         fa->fa_nr = 0;
9875                 }
9876         }
9877         if (fa->fa_nr) {
9878                 rc2 = lfs_rmfid_and_show_errors(device, fa);
9879                 if (rc2 && !rc)
9880                         rc = rc2;
9881         }
9882
9883         return rc;
9884 }
9885
9886 static int lfs_data_version(int argc, char **argv)
9887 {
9888         int data_version_flags = LL_DV_RD_FLUSH; /* Read by default */
9889         __u64 data_version;
9890         char *path;
9891         int fd;
9892         int rc;
9893         int c;
9894
9895         if (argc < 2) {
9896                 fprintf(stderr, "%s: FILE must be specified\n",
9897                         progname);
9898                 return CMD_HELP;
9899         }
9900
9901         while ((c = getopt(argc, argv, "hnrw")) != -1) {
9902                 switch (c) {
9903                 case 'n':
9904                         data_version_flags = 0;
9905                         break;
9906                 case 'r':
9907                         data_version_flags |= LL_DV_RD_FLUSH;
9908                         break;
9909                 case 'w':
9910                         data_version_flags |= LL_DV_WR_FLUSH;
9911                         break;
9912                 default:
9913                         fprintf(stderr,
9914                                 "%s data_version: unrecognized option '%s'\n",
9915                                 progname, argv[optind - 1]);
9916                         fallthrough;
9917                 case 'h':
9918                         return CMD_HELP;
9919                 }
9920         }
9921         if (optind == argc) {
9922                 fprintf(stderr, "%s data_version: FILE must be specified\n",
9923                         progname);
9924                 return CMD_HELP;
9925         }
9926
9927         path = argv[optind];
9928         fd = open(path, O_RDONLY);
9929         if (fd < 0) {
9930                 rc = -errno;
9931                 fprintf(stderr, "%s data_version: cannot open file '%s': %s\n",
9932                         progname, path, strerror(-rc));
9933                 return rc;
9934         }
9935
9936         rc = llapi_get_data_version(fd, &data_version, data_version_flags);
9937         if (rc < 0)
9938                 fprintf(stderr,
9939                         "%s data_version: cannot get version for '%s': %s\n",
9940                         progname, path, strerror(-rc));
9941         else
9942                 printf("%ju" "\n", (uintmax_t)data_version);
9943
9944         close(fd);
9945         return rc;
9946 }
9947
9948 static int lfs_hsm_state(int argc, char **argv)
9949 {
9950         int rc;
9951         int i = 1;
9952         char *path;
9953         struct hsm_user_state hus;
9954
9955         if (argc < 2)
9956                 return CMD_HELP;
9957
9958         do {
9959                 path = argv[i];
9960
9961                 rc = llapi_hsm_state_get(path, &hus);
9962                 if (rc) {
9963                         fprintf(stderr, "can't get hsm state for %s: %s\n",
9964                                 path, strerror(errno = -rc));
9965                         return rc;
9966                 }
9967
9968                 /* Display path name and status flags */
9969                 printf("%s: (0x%08x)", path, hus.hus_states);
9970
9971                 if (hus.hus_states & HS_RELEASED)
9972                         printf(" released");
9973                 if (hus.hus_states & HS_EXISTS)
9974                         printf(" exists");
9975                 if (hus.hus_states & HS_DIRTY)
9976                         printf(" dirty");
9977                 if (hus.hus_states & HS_ARCHIVED)
9978                         printf(" archived");
9979                 /* Display user-settable flags */
9980                 if (hus.hus_states & HS_NORELEASE)
9981                         printf(" never_release");
9982                 if (hus.hus_states & HS_NOARCHIVE)
9983                         printf(" never_archive");
9984                 if (hus.hus_states & HS_LOST)
9985                         printf(" lost_from_hsm");
9986
9987                 if (hus.hus_archive_id != 0)
9988                         printf(", archive_id:%d", hus.hus_archive_id);
9989                 printf("\n");
9990
9991         } while (++i < argc);
9992
9993         return 0;
9994 }
9995
9996 #define LFS_HSM_SET   0
9997 #define LFS_HSM_CLEAR 1
9998
9999 /**
10000  * Generic function to set or clear HSM flags.
10001  * Used by hsm_set and hsm_clear.
10002  *
10003  * @mode  if LFS_HSM_SET, set the flags, if LFS_HSM_CLEAR, clear the flags.
10004  */
10005 static int lfs_hsm_change_flags(int argc, char **argv, int mode)
10006 {
10007         struct option long_opts[] = {
10008         { .val = 'A',   .name = "archived",     .has_arg = no_argument },
10009         { .val = 'a',   .name = "noarchive",    .has_arg = no_argument },
10010         { .val = 'd',   .name = "dirty",        .has_arg = no_argument },
10011         { .val = 'e',   .name = "exists",       .has_arg = no_argument },
10012         { .val = 'h',   .name = "help",         .has_arg = no_argument },
10013         { .val = 'i',   .name = "archive-id",   .has_arg = required_argument },
10014         { .val = 'l',   .name = "lost",         .has_arg = no_argument },
10015         { .val = 'r',   .name = "norelease",    .has_arg = no_argument },
10016         { .name = NULL } };
10017         __u64 mask = 0;
10018         int c, rc;
10019         char *path;
10020         __u32 archive_id = 0;
10021         char *end = NULL;
10022
10023         if (argc < 3)
10024                 return CMD_HELP;
10025
10026         while ((c = getopt_long(argc, argv, "aAdehi:lr",
10027                                 long_opts, NULL)) != -1) {
10028                 switch (c) {
10029                 case 'l':
10030                         mask |= HS_LOST;
10031                         break;
10032                 case 'a':
10033                         mask |= HS_NOARCHIVE;
10034                         break;
10035                 case 'A':
10036                         mask |= HS_ARCHIVED;
10037                         break;
10038                 case 'r':
10039                         mask |= HS_NORELEASE;
10040                         break;
10041                 case 'd':
10042                         mask |= HS_DIRTY;
10043                         break;
10044                 case 'e':
10045                         mask |= HS_EXISTS;
10046                         break;
10047                 case 'i':
10048                         errno = 0;
10049                         archive_id = strtol(optarg, &end, 10);
10050                         if (errno != 0 || *end != '\0' || archive_id < 0) {
10051                                 fprintf(stderr,
10052                                         "%s: invalid archive_id: '%s'\n",
10053                                         progname, end);
10054                                 return CMD_HELP;
10055                         }
10056                         break;
10057                 default:
10058                         fprintf(stderr, "%s: unrecognized option '%s'\n",
10059                                 progname, argv[optind - 1]);
10060                         fallthrough;
10061                 case 'h':
10062                         return CMD_HELP;
10063                 }
10064         }
10065
10066         /* User should have specified a flag */
10067         if (mask == 0)
10068                 return CMD_HELP;
10069
10070         while (optind < argc) {
10071                 path = argv[optind];
10072
10073                 /* If mode == 0, this means we apply the mask. */
10074                 if (mode == LFS_HSM_SET)
10075                         rc = llapi_hsm_state_set(path, mask, 0, archive_id);
10076                 else
10077                         rc = llapi_hsm_state_set(path, 0, mask, 0);
10078
10079                 if (rc != 0) {
10080                         fprintf(stderr, "Can't change hsm flags for %s: %s\n",
10081                                 path, strerror(errno = -rc));
10082                         return rc;
10083                 }
10084                 optind++;
10085         }
10086
10087         return 0;
10088 }
10089
10090 static int lfs_hsm_action(int argc, char **argv)
10091 {
10092         int                              rc;
10093         int                              i = 1;
10094         char                            *path;
10095         struct hsm_current_action        hca;
10096         struct hsm_extent                he;
10097         enum hsm_user_action             hua;
10098         enum hsm_progress_states         hps;
10099
10100         if (argc < 2)
10101                 return CMD_HELP;
10102
10103         do {
10104                 path = argv[i];
10105
10106                 rc = llapi_hsm_current_action(path, &hca);
10107                 if (rc) {
10108                         fprintf(stderr, "can't get hsm action for %s: %s\n",
10109                                 path, strerror(errno = -rc));
10110                         return rc;
10111                 }
10112                 he = hca.hca_location;
10113                 hua = hca.hca_action;
10114                 hps = hca.hca_state;
10115
10116                 printf("%s: %s", path, hsm_user_action2name(hua));
10117
10118                 /* Skip file without action */
10119                 if (hca.hca_action == HUA_NONE) {
10120                         printf("\n");
10121                         continue;
10122                 }
10123
10124                 printf(" %s ", hsm_progress_state2name(hps));
10125
10126                 if ((hps == HPS_RUNNING) &&
10127                     (hua == HUA_ARCHIVE || hua == HUA_RESTORE))
10128                         printf("(%llu bytes moved)\n",
10129                                (unsigned long long)he.length);
10130                 else if ((he.offset + he.length) == LUSTRE_EOF)
10131                         printf("(from %llu to EOF)\n",
10132                                (unsigned long long)he.offset);
10133                 else
10134                         printf("(from %llu to %llu)\n",
10135                                (unsigned long long)he.offset,
10136                                (unsigned long long)(he.offset + he.length));
10137
10138         } while (++i < argc);
10139
10140         return 0;
10141 }
10142
10143 static int lfs_hsm_set(int argc, char **argv)
10144 {
10145         return lfs_hsm_change_flags(argc, argv, LFS_HSM_SET);
10146 }
10147
10148 static int lfs_hsm_clear(int argc, char **argv)
10149 {
10150         return lfs_hsm_change_flags(argc, argv, LFS_HSM_CLEAR);
10151 }
10152
10153 /**
10154  * Check file state and return its fid, to be used by lfs_hsm_request().
10155  *
10156  * \param[in]     file      Path to file to check
10157  * \param[in,out] fid       Pointer to allocated lu_fid struct.
10158  * \param[in,out] last_dev  Pointer to last device id used.
10159  *
10160  * \return 0 on success.
10161  */
10162 static int lfs_hsm_prepare_file(const char *file, struct lu_fid *fid,
10163                                 dev_t *last_dev)
10164 {
10165         struct stat     st;
10166         int             rc;
10167
10168         rc = lstat(file, &st);
10169         if (rc) {
10170                 fprintf(stderr, "Cannot stat %s: %s\n", file, strerror(errno));
10171                 return -errno;
10172         }
10173         /*
10174          * Checking for regular file as archiving as posix copytool
10175          * rejects archiving files other than regular files
10176          */
10177         if (!S_ISREG(st.st_mode)) {
10178                 fprintf(stderr, "error: \"%s\" is not a regular file\n", file);
10179                 return CMD_HELP;
10180         }
10181         /* A request should be ... */
10182         if (*last_dev != st.st_dev && *last_dev != 0) {
10183                 fprintf(stderr,
10184                         "All files should be on the same filesystem: %s\n",
10185                         file);
10186                 return -EINVAL;
10187         }
10188         *last_dev = st.st_dev;
10189
10190         rc = llapi_path2fid(file, fid);
10191         if (rc) {
10192                 fprintf(stderr, "Cannot read FID of %s: %s\n",
10193                         file, strerror(-rc));
10194                 return rc;
10195         }
10196         return 0;
10197 }
10198
10199 /* Fill an HSM HUR item with a given file name.
10200  *
10201  * If mntpath is set, then the filename is actually a FID, and no
10202  * lookup on the filesystem will be performed.
10203  *
10204  * \param[in]  hur         the user request to fill
10205  * \param[in]  idx         index of the item inside the HUR to fill
10206  * \param[in]  mntpath     mountpoint of Lustre
10207  * \param[in]  fname       filename (if mtnpath is NULL)
10208  *                         or FID (if mntpath is set)
10209  * \param[in]  last_dev    pointer to last device id used
10210  *
10211  * \retval 0 on success
10212  * \retval CMD_HELP or a negative errno on error
10213  */
10214 static int fill_hur_item(struct hsm_user_request *hur, unsigned int idx,
10215                          const char *mntpath, const char *fname,
10216                          dev_t *last_dev)
10217 {
10218         struct hsm_user_item *hui = &hur->hur_user_item[idx];
10219         int rc;
10220
10221         hui->hui_extent.length = -1;
10222
10223         if (mntpath) {
10224                 rc = llapi_fid_parse(fname, &hui->hui_fid, NULL);
10225                 if (rc)
10226                         fprintf(stderr, "hsm: '%s' is not a valid FID\n",
10227                                 fname);
10228         } else {
10229                 rc = lfs_hsm_prepare_file(fname, &hui->hui_fid, last_dev);
10230         }
10231
10232         if (rc == 0)
10233                 hur->hur_request.hr_itemcount++;
10234
10235         return rc;
10236 }
10237
10238 static int lfs_hsm_request(int argc, char **argv, int action)
10239 {
10240         struct option long_opts[] = {
10241         { .val = 'a',   .name = "archive",      .has_arg = required_argument },
10242         { .val = 'D',   .name = "data",         .has_arg = required_argument },
10243         { .val = 'h',   .name = "help",         .has_arg = no_argument },
10244         { .val = 'l',   .name = "filelist",     .has_arg = required_argument },
10245         { .val = 'm',   .name = "mntpath",      .has_arg = required_argument },
10246         { .name = NULL } };
10247         dev_t last_dev = 0;
10248         struct hsm_user_request *hur, *oldhur;
10249         int c, i;
10250         size_t len;
10251         int nbfile;
10252         char *line = NULL;
10253         char *filelist = NULL;
10254         char fullpath[PATH_MAX];
10255         char *opaque = NULL;
10256         int opaque_len = 0;
10257         int archive_id = 0;
10258         FILE *fp;
10259         int nbfile_alloc = 0;
10260         char *some_file = NULL;
10261         char *mntpath = NULL;
10262         int rc;
10263
10264         if (argc < 2)
10265                 return CMD_HELP;
10266
10267         while ((c = getopt_long(argc, argv, "a:D:hl:m:",
10268                                 long_opts, NULL)) != -1) {
10269                 switch (c) {
10270                 case 'l':
10271                         filelist = optarg;
10272                         break;
10273                 case 'D':
10274                         opaque = optarg;
10275                         break;
10276                 case 'a':
10277                         if (action != HUA_ARCHIVE &&
10278                             action != HUA_REMOVE) {
10279                                 fprintf(stderr,
10280                                         "error: -a is supported only when archiving or removing\n");
10281                                 return CMD_HELP;
10282                         }
10283                         archive_id = atoi(optarg);
10284                         break;
10285                 case 'm':
10286                         if (!some_file) {
10287                                 mntpath = optarg;
10288                                 some_file = strdup(optarg);
10289                         }
10290                         break;
10291                 default:
10292                         fprintf(stderr, "%s: unrecognized option '%s'\n",
10293                                 progname, argv[optind - 1]);
10294                         fallthrough;
10295                 case 'h':
10296                         return CMD_HELP;
10297                 }
10298         }
10299
10300         /* All remaining args are files, so we have at least nbfile */
10301         nbfile = argc - optind;
10302
10303         if ((nbfile == 0) && (!filelist))
10304                 return CMD_HELP;
10305
10306         if (opaque)
10307                 opaque_len = strlen(opaque);
10308
10309         /*
10310          * Alloc the request structure with enough place to store all files
10311          * from command line.
10312          */
10313         hur = llapi_hsm_user_request_alloc(nbfile, opaque_len);
10314         if (!hur) {
10315                 fprintf(stderr, "Cannot create the request: %s\n",
10316                         strerror(errno));
10317                 return errno;
10318         }
10319         nbfile_alloc = nbfile;
10320
10321         hur->hur_request.hr_action = action;
10322         hur->hur_request.hr_archive_id = archive_id;
10323         hur->hur_request.hr_flags = 0;
10324
10325         /* All remaining args are files, add them */
10326         if (nbfile != 0 && some_file == NULL)
10327                 some_file = strdup(argv[optind]);
10328
10329         for (i = 0; i < nbfile; i++) {
10330                 rc = fill_hur_item(hur, i, mntpath, argv[optind + i],
10331                                    &last_dev);
10332                 if (rc)
10333                         goto out_free;
10334         }
10335
10336         /* from here stop using nb_file, use hur->hur_request.hr_itemcount */
10337
10338         /* If a filelist was specified, read the filelist from it. */
10339         if (filelist) {
10340                 fp = fopen(filelist, "r");
10341                 if (!fp) {
10342                         fprintf(stderr, "Cannot read the file list %s: %s\n",
10343                                 filelist, strerror(errno));
10344                         rc = -errno;
10345                         goto out_free;
10346                 }
10347
10348                 while ((rc = getline(&line, &len, fp)) != -1) {
10349                         /*
10350                          * If allocated buffer was too small, get something
10351                          * larger
10352                          */
10353                         if (nbfile_alloc <= hur->hur_request.hr_itemcount) {
10354                                 ssize_t size;
10355
10356                                 nbfile_alloc = nbfile_alloc * 2 + 1;
10357                                 oldhur = hur;
10358                                 hur = llapi_hsm_user_request_alloc(nbfile_alloc,
10359                                                                    opaque_len);
10360                                 if (!hur) {
10361                                         fprintf(stderr,
10362                                                 "hsm: cannot allocate the request: %s\n",
10363                                                 strerror(errno));
10364                                         hur = oldhur;
10365                                         rc = -errno;
10366                                         fclose(fp);
10367                                         goto out_free;
10368                                 }
10369                                 size = hur_len(oldhur);
10370                                 if (size < 0) {
10371                                         fprintf(stderr,
10372                                                 "hsm: cannot allocate %u files + %u bytes data\n",
10373                                                 oldhur->hur_request.hr_itemcount,
10374                                                 oldhur->hur_request.hr_data_len);
10375                                         free(hur);
10376                                         hur = oldhur;
10377                                         rc = -E2BIG;
10378                                         fclose(fp);
10379                                         goto out_free;
10380                                 }
10381                                 memcpy(hur, oldhur, size);
10382                                 free(oldhur);
10383                         }
10384
10385                         /* Chop CR */
10386                         if (line[strlen(line) - 1] == '\n')
10387                                 line[strlen(line) - 1] = '\0';
10388
10389                         rc = fill_hur_item(hur, hur->hur_request.hr_itemcount,
10390                                            mntpath, line, &last_dev);
10391                         if (rc) {
10392                                 fclose(fp);
10393                                 goto out_free;
10394                         }
10395
10396                         if (!some_file) {
10397                                 some_file = line;
10398                                 line = NULL;
10399                         }
10400                 }
10401
10402                 rc = fclose(fp);
10403                 free(line);
10404         }
10405
10406         /* If a --data was used, add it to the request */
10407         hur->hur_request.hr_data_len = opaque_len;
10408         if (opaque)
10409                 memcpy(hur_data(hur), opaque, opaque_len);
10410
10411         /* Send the HSM request */
10412         if (realpath(some_file, fullpath) == NULL) {
10413                 fprintf(stderr, "Could not find path '%s': %s\n",
10414                         some_file, strerror(errno));
10415         }
10416         rc = llapi_hsm_request(fullpath, hur);
10417         if (rc) {
10418                 fprintf(stderr, "Cannot send HSM request (use of %s): %s\n",
10419                         some_file, strerror(-rc));
10420                 goto out_free;
10421         }
10422
10423 out_free:
10424         free(some_file);
10425         free(hur);
10426         return rc;
10427 }
10428
10429 static int lfs_hsm_archive(int argc, char **argv)
10430 {
10431         return lfs_hsm_request(argc, argv, HUA_ARCHIVE);
10432 }
10433
10434 static int lfs_hsm_restore(int argc, char **argv)
10435 {
10436         return lfs_hsm_request(argc, argv, HUA_RESTORE);
10437 }
10438
10439 static int lfs_hsm_release(int argc, char **argv)
10440 {
10441         return lfs_hsm_request(argc, argv, HUA_RELEASE);
10442 }
10443
10444 static int lfs_hsm_remove(int argc, char **argv)
10445 {
10446         return lfs_hsm_request(argc, argv, HUA_REMOVE);
10447 }
10448
10449 static int lfs_hsm_cancel(int argc, char **argv)
10450 {
10451         return lfs_hsm_request(argc, argv, HUA_CANCEL);
10452 }
10453
10454 static int lfs_swap_layouts(int argc, char **argv)
10455 {
10456         if (argc != 3)
10457                 return CMD_HELP;
10458
10459         return llapi_swap_layouts(argv[1], argv[2], 0, 0,
10460                                   SWAP_LAYOUTS_KEEP_MTIME |
10461                                   SWAP_LAYOUTS_KEEP_ATIME);
10462 }
10463
10464 static const char *const ladvise_names[] = LU_LADVISE_NAMES;
10465
10466 static const char *const lock_mode_names[] = LOCK_MODE_NAMES;
10467
10468 int lfs_get_mode(const char *string)
10469 {
10470         enum lock_mode_user mode;
10471
10472         for (mode = 0; mode < ARRAY_SIZE(lock_mode_names); mode++) {
10473                 if (lock_mode_names[mode] == NULL)
10474                         continue;
10475                 if (strcasecmp(string, lock_mode_names[mode]) == 0)
10476                         return mode;
10477         }
10478
10479         return -EINVAL;
10480 }
10481
10482 static enum lu_ladvise_type lfs_get_ladvice(const char *string)
10483 {
10484         enum lu_ladvise_type advice;
10485
10486         for (advice = 0;
10487              advice < ARRAY_SIZE(ladvise_names); advice++) {
10488                 if (ladvise_names[advice] == NULL)
10489                         continue;
10490                 if (strcmp(string, ladvise_names[advice]) == 0)
10491                         return advice;
10492         }
10493
10494         return LU_LADVISE_INVALID;
10495 }
10496
10497 static int lfs_ladvise(int argc, char **argv)
10498 {
10499         struct option long_opts[] = {
10500         { .val = 'a',   .name = "advice",       .has_arg = required_argument },
10501         { .val = 'b',   .name = "background",   .has_arg = no_argument },
10502         { .val = 'e',   .name = "end",          .has_arg = required_argument },
10503         { .val = 'h',   .name = "help",         .has_arg = no_argument },
10504         { .val = 'l',   .name = "length",       .has_arg = required_argument },
10505         { .val = 'm',   .name = "mode",         .has_arg = required_argument },
10506         { .val = 's',   .name = "start",        .has_arg = required_argument },
10507         { .val = 'u',   .name = "unset",        .has_arg = no_argument },
10508         { .name = NULL } };
10509         struct llapi_lu_ladvise advice;
10510         enum lu_ladvise_type advice_type = LU_LADVISE_INVALID;
10511         unsigned long long start = 0;
10512         unsigned long long end = LUSTRE_EOF;
10513         unsigned long long length = 0;
10514         unsigned long long size_units;
10515         unsigned long long flags = 0;
10516         int c, fd, rc = 0;
10517         const char *path;
10518         int mode = 0;
10519
10520         optind = 0;
10521         while ((c = getopt_long(argc, argv, "a:be:hl:m:s:u",
10522                                 long_opts, NULL)) != -1) {
10523                 switch (c) {
10524                 case 'a':
10525                         advice_type = lfs_get_ladvice(optarg);
10526                         if (advice_type == LU_LADVISE_INVALID) {
10527                                 fprintf(stderr,
10528                                         "%s: invalid advice type '%s'\n",
10529                                         progname, optarg);
10530                                 fprintf(stderr, "Valid types:");
10531
10532                                 for (advice_type = 0;
10533                                      advice_type < ARRAY_SIZE(ladvise_names);
10534                                      advice_type++) {
10535                                         if (ladvise_names[advice_type] == NULL)
10536                                                 continue;
10537                                         fprintf(stderr, " %s",
10538                                                 ladvise_names[advice_type]);
10539                                 }
10540                                 fprintf(stderr, "\n");
10541
10542                                 return CMD_HELP;
10543                         }
10544                         break;
10545                 case 'b':
10546                         flags |= LF_ASYNC;
10547                         break;
10548                 case 'u':
10549                         flags |= LF_UNSET;
10550                         break;
10551                 case 'e':
10552                         size_units = 1;
10553                         rc = llapi_parse_size(optarg, &end,
10554                                               &size_units, 0);
10555                         if (rc) {
10556                                 fprintf(stderr, "%s: bad end offset '%s'\n",
10557                                         argv[0], optarg);
10558                                 return CMD_HELP;
10559                         }
10560                         break;
10561                 case 's':
10562                         size_units = 1;
10563                         rc = llapi_parse_size(optarg, &start,
10564                                               &size_units, 0);
10565                         if (rc) {
10566                                 fprintf(stderr,
10567                                         "%s: bad start offset '%s'\n",
10568                                         argv[0], optarg);
10569                                 return CMD_HELP;
10570                         }
10571                         break;
10572                 case 'l':
10573                         size_units = 1;
10574                         rc = llapi_parse_size(optarg, &length,
10575                                               &size_units, 0);
10576                         if (rc) {
10577                                 fprintf(stderr, "%s: bad length '%s'\n",
10578                                         argv[0], optarg);
10579                                 return CMD_HELP;
10580                         }
10581                         break;
10582                 case 'm':
10583                         mode = lfs_get_mode(optarg);
10584                         if (mode < 0) {
10585                                 fprintf(stderr,
10586                                         "%s: bad mode '%s', valid modes are READ or WRITE\n",
10587                                         argv[0], optarg);
10588                                 return CMD_HELP;
10589                         }
10590                         break;
10591                 default:
10592                         fprintf(stderr, "%s: unrecognized option '%s'\n",
10593                                 progname, argv[optind - 1]);
10594                         fallthrough;
10595                 case 'h':
10596                         return CMD_HELP;
10597                 }
10598         }
10599
10600         if (advice_type == LU_LADVISE_INVALID) {
10601                 fprintf(stderr, "%s: please give an advice type\n", argv[0]);
10602                 fprintf(stderr, "Valid types:");
10603                 for (advice_type = 0; advice_type < ARRAY_SIZE(ladvise_names);
10604                      advice_type++) {
10605                         if (ladvise_names[advice_type] == NULL)
10606                                 continue;
10607                         fprintf(stderr, " %s", ladvise_names[advice_type]);
10608                 }
10609                 fprintf(stderr, "\n");
10610                 return CMD_HELP;
10611         }
10612
10613         if (advice_type == LU_LADVISE_LOCKNOEXPAND) {
10614                 fprintf(stderr,
10615                         "%s: Lock no expand advice is a per file descriptor advice, so when called from lfs, it does nothing.\n",
10616                         argv[0]);
10617                 return CMD_HELP;
10618         }
10619
10620         if (argc <= optind) {
10621                 fprintf(stderr, "%s: please give one or more file names\n",
10622                         argv[0]);
10623                 return CMD_HELP;
10624         }
10625
10626         if (end != LUSTRE_EOF && length != 0 && end != start + length) {
10627                 fprintf(stderr, "%s: conflicting arguments of -l and -e\n",
10628                         argv[0]);
10629                 return CMD_HELP;
10630         }
10631
10632         if (end == LUSTRE_EOF && length != 0)
10633                 end = start + length;
10634
10635         if (end <= start) {
10636                 fprintf(stderr, "%s: range [%llu, %llu] is invalid\n",
10637                         argv[0], start, end);
10638                 return CMD_HELP;
10639         }
10640
10641         if (advice_type != LU_LADVISE_LOCKAHEAD && mode != 0) {
10642                 fprintf(stderr, "%s: mode is only valid with lockahead\n",
10643                         argv[0]);
10644                 return CMD_HELP;
10645         }
10646
10647         if (advice_type == LU_LADVISE_LOCKAHEAD && mode == 0) {
10648                 fprintf(stderr, "%s: mode is required with lockahead\n",
10649                         argv[0]);
10650                 return CMD_HELP;
10651         }
10652
10653         while (optind < argc) {
10654                 int rc2;
10655
10656                 path = argv[optind++];
10657
10658                 fd = open(path, O_RDONLY);
10659                 if (fd < 0) {
10660                         fprintf(stderr, "%s: cannot open file '%s': %s\n",
10661                                 argv[0], path, strerror(errno));
10662                         rc2 = -errno;
10663                         goto next;
10664                 }
10665
10666                 advice.lla_start = start;
10667                 advice.lla_end = end;
10668                 advice.lla_advice = advice_type;
10669                 advice.lla_value1 = 0;
10670                 advice.lla_value2 = 0;
10671                 advice.lla_value3 = 0;
10672                 advice.lla_value4 = 0;
10673                 if (advice_type == LU_LADVISE_LOCKAHEAD) {
10674                         advice.lla_lockahead_mode = mode;
10675                         advice.lla_peradvice_flags = flags;
10676                 }
10677
10678                 rc2 = llapi_ladvise(fd, flags, 1, &advice);
10679                 close(fd);
10680                 if (rc2 < 0) {
10681                         fprintf(stderr,
10682                                 "%s: cannot give advice '%s' to file '%s': %s\n",
10683                                 argv[0], ladvise_names[advice_type],
10684                                 path, strerror(errno));
10685
10686                         goto next;
10687                 }
10688
10689 next:
10690                 if (rc == 0 && rc2 < 0)
10691                         rc = rc2;
10692         }
10693         return rc;
10694 }
10695
10696 static const char *const heat_names[] = LU_HEAT_NAMES;
10697
10698 static int lfs_heat_get(int argc, char **argv)
10699 {
10700         struct lu_heat *heat;
10701         int rc = 0, rc2;
10702         char *path;
10703         int fd;
10704         int i;
10705
10706         if (argc <= 1)
10707                 return CMD_HELP;
10708
10709         heat = calloc(sizeof(*heat) + sizeof(__u64) * OBD_HEAT_COUNT, 1);
10710         if (!heat) {
10711                 fprintf(stderr, "%s: memory allocation failed\n", argv[0]);
10712                 return -ENOMEM;
10713         }
10714
10715         optind = 1;
10716         while (optind < argc) {
10717                 path = argv[optind++];
10718
10719                 fd = open(path, O_RDONLY);
10720                 if (fd < 0) {
10721                         fprintf(stderr, "%s: cannot open file '%s': %s\n",
10722                                 argv[0], path, strerror(errno));
10723                         rc2 = -errno;
10724                         goto next;
10725                 }
10726
10727                 heat->lh_count = OBD_HEAT_COUNT;
10728                 rc2 = llapi_heat_get(fd, heat);
10729                 close(fd);
10730                 if (rc2 < 0) {
10731                         fprintf(stderr,
10732                                 "%s: cannot get heat of file '%s': %s\n",
10733                                 argv[0], path, strerror(errno));
10734                         goto next;
10735                 }
10736
10737                 printf("flags: %x\n", heat->lh_flags);
10738                 for (i = 0; i < heat->lh_count; i++)
10739                         printf("%s: %llu\n", heat_names[i],
10740                                (unsigned long long)heat->lh_heat[i]);
10741 next:
10742                 if (rc == 0 && rc2 < 0)
10743                         rc = rc2;
10744         }
10745
10746         free(heat);
10747         return rc;
10748 }
10749
10750 static int lfs_heat_set(int argc, char **argv)
10751 {
10752         struct option long_opts[] = {
10753         { .val = 'c',   .name = "clear",        .has_arg = no_argument },
10754         { .val = 'h',   .name = "help",         .has_arg = no_argument },
10755         { .val = 'o',   .name = "off",          .has_arg = no_argument },
10756         { .val = 'O',   .name = "on",           .has_arg = no_argument },
10757         { .name = NULL } };
10758         enum lu_heat_flag flags = 0;
10759         int rc = 0, rc2;
10760         char *path;
10761         int fd;
10762         int c;
10763
10764         if (argc <= 1)
10765                 return CMD_HELP;
10766
10767         optind = 0;
10768         while ((c = getopt_long(argc, argv, "choO", long_opts, NULL)) != -1) {
10769                 switch (c) {
10770                 case 'c':
10771                         flags |= LU_HEAT_FLAG_CLEAR;
10772                         break;
10773                 case 'o':
10774                         flags |= LU_HEAT_FLAG_CLEAR;
10775                         flags |= LU_HEAT_FLAG_OFF;
10776                         break;
10777                 case 'O':
10778                         flags &= ~LU_HEAT_FLAG_OFF;
10779                         break;
10780                 default:
10781                         fprintf(stderr, "%s: unrecognized option '%s'\n",
10782                                 progname, argv[optind - 1]);
10783                         fallthrough;
10784                 case 'h':
10785                         return CMD_HELP;
10786                 }
10787         }
10788
10789         if (argc <= optind) {
10790                 fprintf(stderr, "%s: please give one or more file names\n",
10791                         argv[0]);
10792                 return CMD_HELP;
10793         }
10794
10795         while (optind < argc) {
10796                 path = argv[optind++];
10797
10798                 fd = open(path, O_RDONLY);
10799                 if (fd < 0) {
10800                         fprintf(stderr, "%s: cannot open file '%s': %s\n",
10801                                 argv[0], path, strerror(errno));
10802                         rc2 = -errno;
10803                         goto next;
10804                 }
10805
10806                 rc2 = llapi_heat_set(fd, flags);
10807                 close(fd);
10808                 if (rc2 < 0) {
10809                         fprintf(stderr,
10810                                 "%s: cannot setflags heat of file '%s': %s\n",
10811                                 argv[0], path, strerror(errno));
10812                         goto next;
10813                 }
10814 next:
10815                 if (rc == 0 && rc2 < 0)
10816                         rc = rc2;
10817         }
10818         return rc;
10819 }
10820
10821 /**
10822  * The input string contains a comma delimited list of component ids and
10823  * ranges, for example "1,2-4,7".
10824  */
10825 static int parse_mirror_ids(__u16 *ids, int size, char *arg)
10826 {
10827         bool end_of_loop = false;
10828         char *ptr = NULL;
10829         int nr = 0;
10830         int rc;
10831
10832         if (!arg)
10833                 return -EINVAL;
10834
10835         while (!end_of_loop) {
10836                 int start_index;
10837                 int end_index;
10838                 int i;
10839                 char *endptr = NULL;
10840
10841                 rc = -EINVAL;
10842                 ptr = strchrnul(arg, ',');
10843                 end_of_loop = *ptr == '\0';
10844                 *ptr = '\0';
10845
10846                 start_index = strtol(arg, &endptr, 0);
10847                 if (endptr == arg) /* no data at all */
10848                         break;
10849                 if (*endptr != '-' && *endptr != '\0') /* has invalid data */
10850                         break;
10851                 if (start_index < 0)
10852                         break;
10853
10854                 end_index = start_index;
10855                 if (*endptr == '-') {
10856                         end_index = strtol(endptr + 1, &endptr, 0);
10857                         if (*endptr != '\0')
10858                                 break;
10859                         if (end_index < start_index)
10860                                 break;
10861                 }
10862
10863                 for (i = start_index; i <= end_index && size > 0; i++) {
10864                         int j;
10865
10866                         /* remove duplicate */
10867                         for (j = 0; j < nr; j++) {
10868                                 if (ids[j] == i)
10869                                         break;
10870                         }
10871                         if (j == nr) { /* no duplicate */
10872                                 ids[nr++] = i;
10873                                 --size;
10874                         }
10875                 }
10876
10877                 if (size == 0 && i < end_index)
10878                         break;
10879
10880                 *ptr = ',';
10881                 arg = ++ptr;
10882                 rc = 0;
10883         }
10884         if (!end_of_loop && ptr)
10885                 *ptr = ',';
10886
10887         return rc < 0 ? rc : nr;
10888 }
10889
10890 /**
10891  * struct verify_mirror_id - Mirror id to be verified.
10892  * @mirror_id:   A specified mirror id.
10893  * @is_valid_id: @mirror_id is valid or not in the mirrored file.
10894  */
10895 struct verify_mirror_id {
10896         __u16 mirror_id;
10897         bool is_valid_id;
10898 };
10899
10900 /**
10901  * compare_mirror_ids() - Compare mirror ids.
10902  * @layout: Mirror component list.
10903  * @cbdata: Callback data in verify_mirror_id structure.
10904  *
10905  * This is a callback function called by llapi_layout_comp_iterate()
10906  * to compare the specified mirror id with the one in the current
10907  * component of @layout. If they are the same, then the specified
10908  * mirror id is valid.
10909  *
10910  * Return: a negative error code on failure or
10911  *         LLAPI_LAYOUT_ITER_CONT: Proceed iteration
10912  *         LLAPI_LAYOUT_ITER_STOP: Stop iteration
10913  */
10914 static inline
10915 int compare_mirror_ids(struct llapi_layout *layout, void *cbdata)
10916 {
10917         struct verify_mirror_id *mirror_id_cbdata =
10918                                  (struct verify_mirror_id *)cbdata;
10919         uint32_t mirror_id;
10920         int rc = 0;
10921
10922         rc = llapi_layout_mirror_id_get(layout, &mirror_id);
10923         if (rc < 0) {
10924                 rc = -errno;
10925                 fprintf(stderr,
10926                         "%s: llapi_layout_mirror_id_get failed: %s.\n",
10927                         progname, strerror(errno));
10928                 return rc;
10929         }
10930
10931         if (mirror_id_cbdata->mirror_id == mirror_id) {
10932                 mirror_id_cbdata->is_valid_id = true;
10933                 return LLAPI_LAYOUT_ITER_STOP;
10934         }
10935
10936         return LLAPI_LAYOUT_ITER_CONT;
10937 }
10938
10939 /**
10940  * verify_mirror_ids() - Verify specified mirror ids.
10941  * @fname:      Mirrored file name.
10942  * @mirror_ids: Specified mirror ids to be verified.
10943  * @ids_nr:     Number of specified mirror ids.
10944  *
10945  * This function verifies that specified @mirror_ids are valid
10946  * in the mirrored file @fname.
10947  *
10948  * Return: 0 on success or a negative error code on failure.
10949  */
10950 static inline
10951 int verify_mirror_ids(const char *fname, __u16 *mirror_ids, int ids_nr)
10952 {
10953         struct llapi_layout *layout = NULL;
10954         struct verify_mirror_id mirror_id_cbdata = { 0 };
10955         struct stat stbuf;
10956         uint32_t flr_state;
10957         int i;
10958         int fd;
10959         int rc = 0;
10960         int rc2 = 0;
10961
10962         if (ids_nr <= 0)
10963                 return -EINVAL;
10964
10965         if (stat(fname, &stbuf) < 0) {
10966                 fprintf(stderr, "%s: cannot stat file '%s': %s.\n",
10967                         progname, fname, strerror(errno));
10968                 rc = -errno;
10969                 goto error;
10970         }
10971
10972         if (!S_ISREG(stbuf.st_mode)) {
10973                 fprintf(stderr, "%s: '%s' is not a regular file.\n",
10974                         progname, fname);
10975                 rc = -EINVAL;
10976                 goto error;
10977         }
10978
10979         fd = open(fname, O_DIRECT | O_RDONLY);
10980         if (fd < 0) {
10981                 fprintf(stderr, "%s: cannot open '%s': %s.\n",
10982                         progname, fname, strerror(errno));
10983                 rc = -errno;
10984                 goto error;
10985         }
10986
10987         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
10988         if (rc < 0) {
10989                 fprintf(stderr, "%s: '%s' llapi_lease_acquire failed: %s.\n",
10990                         progname, fname, strerror(errno));
10991                 goto close_fd;
10992         }
10993
10994         layout = llapi_layout_get_by_fd(fd, 0);
10995         if (!layout) {
10996                 fprintf(stderr, "%s: '%s' llapi_layout_get_by_fd failed: %s.\n",
10997                         progname, fname, strerror(errno));
10998                 rc = -errno;
10999                 llapi_lease_release(fd);
11000                 goto close_fd;
11001         }
11002
11003         rc = llapi_layout_flags_get(layout, &flr_state);
11004         if (rc < 0) {
11005                 fprintf(stderr, "%s: '%s' llapi_layout_flags_get failed: %s.\n",
11006                         progname, fname, strerror(errno));
11007                 rc = -errno;
11008                 goto free_layout;
11009         }
11010
11011         flr_state &= LCM_FL_FLR_MASK;
11012         switch (flr_state) {
11013         case LCM_FL_NONE:
11014                 rc = -EINVAL;
11015                 fprintf(stderr, "%s: '%s' file state error: %s.\n",
11016                         progname, fname, llapi_layout_flags_string(flr_state));
11017                 goto free_layout;
11018         default:
11019                 break;
11020         }
11021
11022         rc2 = 0;
11023         for (i = 0; i < ids_nr; i++) {
11024                 mirror_id_cbdata.mirror_id = mirror_ids[i];
11025                 mirror_id_cbdata.is_valid_id = false;
11026
11027                 rc = llapi_layout_comp_iterate(layout, compare_mirror_ids,
11028                                                &mirror_id_cbdata);
11029                 if (rc < 0) {
11030                         rc = -errno;
11031                         fprintf(stderr,
11032                                 "%s: '%s' failed to verify mirror id: %u.\n",
11033                                 progname, fname, mirror_ids[i]);
11034                         goto free_layout;
11035                 }
11036
11037                 if (!mirror_id_cbdata.is_valid_id) {
11038                         rc2 = -EINVAL;
11039                         fprintf(stderr,
11040                                 "%s: '%s' invalid specified mirror id: %u.\n",
11041                                 progname, fname, mirror_ids[i]);
11042                 }
11043         }
11044         rc = rc2;
11045
11046 free_layout:
11047         llapi_layout_free(layout);
11048         llapi_lease_release(fd);
11049 close_fd:
11050         close(fd);
11051 error:
11052         return rc;
11053 }
11054
11055 static inline
11056 int lfs_mirror_resync_file(const char *fname, struct ll_ioc_lease *ioc,
11057                            __u16 *mirror_ids, int ids_nr)
11058 {
11059         struct llapi_resync_comp comp_array[1024] = { { 0 } };
11060         struct llapi_layout *layout;
11061         struct stat stbuf;
11062         uint32_t flr_state;
11063         uint64_t start;
11064         uint64_t end;
11065         int comp_size = 0;
11066         int idx;
11067         int fd;
11068         int rc;
11069         int rc2;
11070
11071         if (stat(fname, &stbuf) < 0) {
11072                 fprintf(stderr, "%s: cannot stat file '%s': %s.\n",
11073                         progname, fname, strerror(errno));
11074                 rc = -errno;
11075                 goto error;
11076         }
11077         if (!S_ISREG(stbuf.st_mode)) {
11078                 fprintf(stderr, "%s: '%s' is not a regular file.\n",
11079                         progname, fname);
11080                 rc = -EINVAL;
11081                 goto error;
11082         }
11083
11084         /* Allow mirror resync even without the key on encrypted files */
11085         fd = open(fname, O_DIRECT | O_RDWR | O_FILE_ENC);
11086         if (fd < 0) {
11087                 fprintf(stderr, "%s: cannot open '%s': %s.\n",
11088                         progname, fname, strerror(errno));
11089                 rc = -errno;
11090                 goto error;
11091         }
11092
11093         layout = llapi_layout_get_by_fd(fd, 0);
11094         if (!layout) {
11095                 fprintf(stderr, "%s: '%s' llapi_layout_get_by_fd failed: %s.\n",
11096                         progname, fname, strerror(errno));
11097                 rc = -errno;
11098                 goto close_fd;
11099         }
11100
11101         rc = llapi_layout_flags_get(layout, &flr_state);
11102         if (rc) {
11103                 fprintf(stderr, "%s: '%s' llapi_layout_flags_get failed: %s.\n",
11104                         progname, fname, strerror(errno));
11105                 rc = -errno;
11106                 goto free_layout;
11107         }
11108
11109         flr_state &= LCM_FL_FLR_MASK;
11110         if (flr_state == LCM_FL_NONE) {
11111                 rc = -EINVAL;
11112                 fprintf(stderr, "%s: '%s' is not a FLR file.\n",
11113                         progname, fname);
11114                 goto free_layout;
11115         }
11116
11117         /* get stale component info */
11118         comp_size = llapi_mirror_find_stale(layout, comp_array,
11119                                             ARRAY_SIZE(comp_array),
11120                                             mirror_ids, ids_nr);
11121         if (comp_size <= 0) {
11122                 rc = comp_size;
11123                 goto free_layout;
11124         }
11125
11126         ioc->lil_mode = LL_LEASE_WRLCK;
11127         ioc->lil_flags = LL_LEASE_RESYNC;
11128         rc = llapi_lease_set(fd, ioc);
11129         if (rc < 0) {
11130                 if (rc == -EALREADY)
11131                         rc = 0;
11132                 else
11133                         fprintf(stderr,
11134                             "%s: '%s' llapi_lease_get_ext resync failed: %s.\n",
11135                                 progname, fname, strerror(-rc));
11136                 goto free_layout;
11137         }
11138
11139         /* get the read range [start, end) */
11140         start = comp_array[0].lrc_start;
11141         end = comp_array[0].lrc_end;
11142         for (idx = 1; idx < comp_size; idx++) {
11143                 if (comp_array[idx].lrc_start < start)
11144                         start = comp_array[idx].lrc_start;
11145                 if (end < comp_array[idx].lrc_end)
11146                         end = comp_array[idx].lrc_end;
11147         }
11148
11149         rc = llapi_lease_check(fd);
11150         if (rc != LL_LEASE_WRLCK) {
11151                 fprintf(stderr, "%s: '%s' lost lease lock.\n",
11152                         progname, fname);
11153                 goto free_layout;
11154         }
11155
11156         rc = llapi_mirror_resync_many(fd, layout, comp_array, comp_size,
11157                                       start, end);
11158         if (rc < 0)
11159                 fprintf(stderr, "%s: '%s' llapi_mirror_resync_many: %s.\n",
11160                         progname, fname, strerror(-rc));
11161
11162         rc = migrate_set_timestamps(fd, &stbuf);
11163         if (rc < 0) {
11164                 fprintf(stderr, "%s: '%s' cannot set timestamps: %s\n",
11165                         progname, fname, strerror(-rc));
11166                 goto free_layout;
11167         }
11168
11169         /* need to do the lease unlock even resync fails */
11170         ioc->lil_mode = LL_LEASE_UNLCK;
11171         ioc->lil_flags = LL_LEASE_RESYNC_DONE;
11172         ioc->lil_count = 0;
11173         for (idx = 0; idx < comp_size; idx++) {
11174                 if (comp_array[idx].lrc_synced) {
11175                         ioc->lil_ids[ioc->lil_count] = comp_array[idx].lrc_id;
11176                         ioc->lil_count++;
11177                 }
11178         }
11179
11180         rc2 = llapi_lease_set(fd, ioc);
11181         /**
11182          * llapi_lease_set returns lease mode when it request to unlock
11183          * the lease lock.
11184          */
11185         if (rc2 <= 0) {
11186                 /* rc2 == 0 means lost lease lock */
11187                 if (rc2 == 0 && rc == 0)
11188                         rc = -EBUSY;
11189                 else
11190                         rc = rc2;
11191                 fprintf(stderr, "%s: resync file '%s' failed: %s.\n",
11192                         progname, fname,
11193                         rc2 == 0 ? "lost lease lock" : strerror(-rc2));
11194
11195                 llapi_lease_release(fd);
11196                 goto free_layout;
11197         }
11198
11199 free_layout:
11200         llapi_layout_free(layout);
11201 close_fd:
11202         close(fd);
11203 error:
11204         return rc;
11205 }
11206
11207 static inline int lfs_mirror_resync(int argc, char **argv)
11208 {
11209         struct option long_opts[] = {
11210         { .val = 'h',   .name = "help",         .has_arg = no_argument },
11211         { .val = 'o',   .name = "only",         .has_arg = required_argument },
11212         { .name = NULL } };
11213         struct ll_ioc_lease *ioc = NULL;
11214         __u16 mirror_ids[128] = { 0 };
11215         int ids_nr = 0;
11216         int c;
11217         int rc = 0;
11218
11219         while ((c = getopt_long(argc, argv, "ho:", long_opts, NULL)) >= 0) {
11220                 switch (c) {
11221                 case 'o':
11222                         rc = parse_mirror_ids(mirror_ids,
11223                                         sizeof(mirror_ids) / sizeof(__u16),
11224                                         optarg);
11225                         if (rc < 0) {
11226                                 fprintf(stderr,
11227                                         "%s: bad mirror ids '%s'.\n",
11228                                         argv[0], optarg);
11229                                 goto error;
11230                         }
11231                         ids_nr = rc;
11232                         break;
11233                 default:
11234                         fprintf(stderr, "%s: unrecognized option '%s'\n",
11235                                 progname, argv[optind - 1]);
11236                         fallthrough;
11237                 case 'h':
11238                         rc = CMD_HELP;
11239                         goto error;
11240                 }
11241         }
11242
11243         if (argc == optind) {
11244                 fprintf(stderr, "%s: no file name given.\n", argv[0]);
11245                 rc = CMD_HELP;
11246                 goto error;
11247         }
11248
11249         if (ids_nr > 0 && argc > optind + 1) {
11250                 fprintf(stderr,
11251                     "%s: option '--only' cannot be used upon multiple files.\n",
11252                         argv[0]);
11253                 rc = CMD_HELP;
11254                 goto error;
11255         }
11256
11257         if (ids_nr > 0) {
11258                 rc = verify_mirror_ids(argv[optind], mirror_ids, ids_nr);
11259                 if (rc < 0)
11260                         goto error;
11261         }
11262
11263         /* set the lease on the file */
11264         ioc = calloc(sizeof(*ioc) + sizeof(__u32) * 4096, 1);
11265         if (!ioc) {
11266                 fprintf(stderr, "%s: cannot alloc id array for ioc: %s.\n",
11267                         argv[0], strerror(errno));
11268                 rc = -errno;
11269                 goto error;
11270         }
11271
11272         for (; optind < argc; optind++) {
11273                 rc = lfs_mirror_resync_file(argv[optind], ioc,
11274                                             mirror_ids, ids_nr);
11275                 /* ignore previous file's error, continue with next file */
11276
11277                 /* reset ioc */
11278                 memset(ioc, 0, sizeof(*ioc) + sizeof(__u32) * 4096);
11279         }
11280
11281         free(ioc);
11282 error:
11283         return rc;
11284 }
11285
11286 static inline int verify_mirror_id_by_fd(int fd, __u16 mirror_id)
11287 {
11288         struct llapi_layout *layout;
11289         int rc;
11290
11291         layout = llapi_layout_get_by_fd(fd, 0);
11292         if (!layout) {
11293                 fprintf(stderr, "could not get layout.\n");
11294                 return  -EINVAL;
11295         }
11296
11297         rc = llapi_layout_comp_iterate(layout, find_mirror_id, &mirror_id);
11298         if (rc < 0) {
11299                 fprintf(stderr, "failed to iterate layout\n");
11300                 llapi_layout_free(layout);
11301
11302                 return rc;
11303         } else if (rc == LLAPI_LAYOUT_ITER_CONT) {
11304                 fprintf(stderr, "does not find mirror with ID %u\n", mirror_id);
11305                 llapi_layout_free(layout);
11306
11307                 return -EINVAL;
11308         }
11309         llapi_layout_free(layout);
11310
11311         return 0;
11312 }
11313
11314 /**
11315  * Check whether two files are the same file
11316  * \retval      0  same file
11317  * \retval      1  not the same file
11318  * \retval      <0 error code
11319  */
11320 static inline int check_same_file(int fd, const char *f2)
11321 {
11322         struct stat stbuf1;
11323         struct stat stbuf2;
11324
11325         if (fstat(fd, &stbuf1) < 0)
11326                 return -errno;
11327
11328         if (stat(f2, &stbuf2) < 0)
11329                 return 1;
11330
11331         if (stbuf1.st_rdev == stbuf2.st_rdev &&
11332             stbuf1.st_ino == stbuf2.st_ino)
11333                 return 0;
11334
11335         return 1;
11336 }
11337
11338 static inline int lfs_mirror_read(int argc, char **argv)
11339 {
11340         int rc = CMD_HELP;
11341         __u16 mirror_id = 0;
11342         const char *outfile = NULL;
11343         char *fname;
11344         int fd = 0;
11345         int outfd;
11346         int c;
11347         void *buf;
11348         const size_t buflen = 4 << 20;
11349         off_t pos;
11350         struct option long_opts[] = {
11351         { .val = 'h',   .name = "help",         .has_arg = no_argument },
11352         { .val = 'N',   .name = "mirror-id",    .has_arg = required_argument },
11353         { .val = 'o',   .name = "outfile",      .has_arg = required_argument },
11354         { .name = NULL } };
11355
11356         while ((c = getopt_long(argc, argv, "hN:o:", long_opts, NULL)) >= 0) {
11357                 char *end;
11358
11359                 switch (c) {
11360                 case 'N': {
11361                         unsigned long int id;
11362
11363                         errno = 0;
11364                         id = strtoul(optarg, &end, 0);
11365                         if (errno != 0 || *end != '\0' || id == 0 ||
11366                             id > UINT16_MAX) {
11367                                 fprintf(stderr,
11368                                         "%s %s: invalid mirror ID '%s'\n",
11369                                         progname, argv[0], optarg);
11370                                 return rc;
11371                         }
11372
11373                         mirror_id = (__u16)id;
11374                         break;
11375                 }
11376                 case 'o':
11377                         outfile = optarg;
11378                         break;
11379                 default:
11380                         fprintf(stderr, "%s: unrecognized option '%s'\n",
11381                                 progname, argv[optind - 1]);
11382                         fallthrough;
11383                 case 'h':
11384                         return CMD_HELP;
11385                 }
11386         }
11387
11388         if (argc == optind) {
11389                 fprintf(stderr, "%s %s: no mirrored file provided\n",
11390                         progname, argv[0]);
11391                 return rc;
11392         } else if (argc > optind + 1) {
11393                 fprintf(stderr, "%s %s: too many files\n", progname, argv[0]);
11394                 return rc;
11395         }
11396
11397         if (mirror_id == 0) {
11398                 fprintf(stderr, "%s %s: no valid mirror ID is provided\n",
11399                         progname, argv[0]);
11400                 return rc;
11401         }
11402
11403         /* open mirror file */
11404         fname = argv[optind];
11405         fd = open(fname, O_DIRECT | O_RDONLY);
11406         if (fd < 0) {
11407                 fprintf(stderr, "%s %s: cannot open '%s': %s\n",
11408                         progname, argv[0], fname, strerror(errno));
11409                 return rc;
11410         }
11411
11412         /* verify mirror id */
11413         rc = verify_mirror_id_by_fd(fd, mirror_id);
11414         if (rc) {
11415                 fprintf(stderr,
11416                         "%s %s: cannot find mirror with ID %u in '%s'\n",
11417                         progname, argv[0], mirror_id, fname);
11418                 goto close_fd;
11419         }
11420
11421         /* open output file - O_EXCL ensures output is not the same as input */
11422         if (outfile) {
11423                 outfd = open(outfile, O_EXCL | O_WRONLY | O_CREAT, 0644);
11424                 if (outfd < 0) {
11425                         fprintf(stderr, "%s %s: cannot create file '%s': %s\n",
11426                                 progname, argv[0], outfile, strerror(errno));
11427                         rc = -errno;
11428                         goto close_fd;
11429                 }
11430         } else {
11431                 outfd = STDOUT_FILENO;
11432         }
11433
11434         /* allocate buffer */
11435         rc = posix_memalign(&buf, sysconf(_SC_PAGESIZE), buflen);
11436         if (rc) {
11437                 fprintf(stderr, "%s %s: posix_memalign returns %d\n",
11438                                 progname, argv[0], rc);
11439                 goto close_outfd;
11440         }
11441
11442         pos = 0;
11443         while (1) {
11444                 ssize_t bytes_read;
11445                 ssize_t written = 0;
11446
11447                 bytes_read = llapi_mirror_read(fd, mirror_id, buf, buflen, pos);
11448                 if (bytes_read < 0) {
11449                         rc = bytes_read;
11450                         fprintf(stderr,
11451                                 "%s %s: fail to read data from mirror %u: %s\n",
11452                                 progname, argv[0], mirror_id, strerror(-rc));
11453                         goto free_buf;
11454                 }
11455
11456                 /* EOF reached */
11457                 if (bytes_read == 0)
11458                         break;
11459
11460                 while (written < bytes_read) {
11461                         ssize_t written2;
11462
11463                         written2 = write(outfd, buf + written,
11464                                          bytes_read - written);
11465                         if (written2 < 0) {
11466                                 fprintf(stderr,
11467                                         "%s %s: fail to write %s: %s\n",
11468                                         progname, argv[0], outfile ? : "STDOUT",
11469                                         strerror(errno));
11470                                 rc = -errno;
11471                                 goto free_buf;
11472                         }
11473                         written += written2;
11474                 }
11475
11476                 if (written != bytes_read) {
11477                         fprintf(stderr,
11478                 "%s %s: written %ld bytes does not match with %ld read.\n",
11479                                 progname, argv[0], written, bytes_read);
11480                         rc = -EIO;
11481                         goto free_buf;
11482                 }
11483
11484                 pos += bytes_read;
11485         }
11486
11487         fsync(outfd);
11488         rc = 0;
11489
11490 free_buf:
11491         free(buf);
11492 close_outfd:
11493         if (outfile)
11494                 close(outfd);
11495 close_fd:
11496         close(fd);
11497
11498         return rc;
11499 }
11500
11501 static inline int lfs_mirror_write(int argc, char **argv)
11502 {
11503         int rc = CMD_HELP;
11504         __u16 mirror_id = 0;
11505         const char *inputfile = NULL;
11506         char *fname;
11507         int fd = 0;
11508         int inputfd;
11509         int c;
11510         void *buf;
11511         const size_t buflen = 4 << 20;
11512         off_t pos;
11513         size_t page_size = sysconf(_SC_PAGESIZE);
11514         struct ll_ioc_lease_id ioc;
11515         struct option long_opts[] = {
11516         { .val = 'h',   .name = "help",         .has_arg = no_argument },
11517         { .val = 'i',   .name = "inputfile",    .has_arg = required_argument },
11518         { .val = 'N',   .name = "mirror-id",    .has_arg = required_argument },
11519         { .name = NULL } };
11520
11521         while ((c = getopt_long(argc, argv, "hi:N:", long_opts, NULL)) >= 0) {
11522                 char *end;
11523
11524                 switch (c) {
11525                 case 'N': {
11526                         unsigned long int id;
11527
11528                         errno = 0;
11529                         id = strtoul(optarg, &end, 0);
11530                         if (errno != 0 || *end != '\0' || id == 0 ||
11531                             id > UINT16_MAX) {
11532                                 fprintf(stderr,
11533                                         "%s %s: invalid mirror ID '%s'\n",
11534                                         progname, argv[0], optarg);
11535                                 return rc;
11536                         }
11537
11538                         mirror_id = (__u16)id;
11539                         break;
11540                 }
11541                 case 'i':
11542                         inputfile = optarg;
11543                         break;
11544                 default:
11545                         fprintf(stderr, "%s: unrecognized option '%s'\n",
11546                                 progname, argv[optind - 1]);
11547                         fallthrough;
11548                 case 'h':
11549                         return CMD_HELP;
11550                 }
11551         }
11552
11553         if (argc == optind) {
11554                 fprintf(stderr, "%s %s: no mirrored file provided\n",
11555                         progname, argv[0]);
11556                 return rc;
11557         } else if (argc > optind + 1) {
11558                 fprintf(stderr, "%s %s: too many files\n", progname, argv[0]);
11559                 return rc;
11560         }
11561
11562         if (mirror_id == 0) {
11563                 fprintf(stderr, "%s %s: no valid mirror ID is provided\n",
11564                         progname, argv[0]);
11565                 return rc;
11566         }
11567
11568         /* open mirror file */
11569         fname = argv[optind];
11570         fd = open(fname, O_DIRECT | O_WRONLY);
11571         if (fd < 0) {
11572                 fprintf(stderr, "%s %s: cannot open '%s': %s\n",
11573                         progname, argv[0], fname, strerror(errno));
11574                 return rc;
11575         }
11576
11577         /* verify mirror id */
11578         rc = verify_mirror_id_by_fd(fd, mirror_id);
11579         if (rc) {
11580                 fprintf(stderr,
11581                         "%s %s: cannot find mirror with ID %u in '%s'\n",
11582                         progname, argv[0], mirror_id, fname);
11583                 goto close_fd;
11584         }
11585
11586         /* open input file */
11587         if (inputfile) {
11588                 rc = check_same_file(fd, inputfile);
11589                 if (rc == 0) {
11590                         fprintf(stderr,
11591                         "%s %s: input file cannot be the mirrored file\n",
11592                                 progname, argv[0]);
11593                         goto close_fd;
11594                 }
11595                 if (rc < 0)
11596                         goto close_fd;
11597
11598                 inputfd = open(inputfile, O_RDONLY, 0644);
11599                 if (inputfd < 0) {
11600                         fprintf(stderr, "%s %s: cannot open file '%s': %s\n",
11601                                 progname, argv[0], inputfile, strerror(errno));
11602                         rc = -errno;
11603                         goto close_fd;
11604                 }
11605         } else {
11606                 inputfd = STDIN_FILENO;
11607         }
11608
11609         /* allocate buffer */
11610         rc = posix_memalign(&buf, page_size, buflen);
11611         if (rc) {
11612                 fprintf(stderr, "%s %s: posix_memalign returns %d\n",
11613                         progname, argv[0], rc);
11614                 goto close_inputfd;
11615         }
11616
11617         /* prepare target mirror components instantiation */
11618         ioc.lil_mode = LL_LEASE_WRLCK;
11619         ioc.lil_flags = LL_LEASE_RESYNC;
11620         ioc.lil_mirror_id = mirror_id;
11621         rc = llapi_lease_set(fd, (struct ll_ioc_lease *)&ioc);
11622         if (rc < 0) {
11623                 fprintf(stderr,
11624                         "%s %s: '%s' llapi_lease_get_ext failed: %s\n",
11625                         progname, argv[0], fname, strerror(errno));
11626                 goto free_buf;
11627         }
11628
11629         pos = 0;
11630         while (1) {
11631                 ssize_t bytes_read;
11632                 ssize_t written;
11633                 size_t to_write;
11634
11635                 rc = llapi_lease_check(fd);
11636                 if (rc != LL_LEASE_WRLCK) {
11637                         fprintf(stderr, "%s %s: '%s' lost lease lock\n",
11638                                 progname, argv[0], fname);
11639                         goto free_buf;
11640                 }
11641
11642                 bytes_read = read(inputfd, buf, buflen);
11643                 if (bytes_read < 0) {
11644                         rc = bytes_read;
11645                         fprintf(stderr,
11646                                 "%s %s: fail to read data from '%s': %s\n",
11647                                 progname, argv[0], inputfile ? : "STDIN",
11648                                 strerror(errno));
11649                         rc = -errno;
11650                         goto free_buf;
11651                 }
11652
11653                 /* EOF reached */
11654                 if (bytes_read == 0)
11655                         break;
11656
11657                 /* round up to page align to make direct IO happy. */
11658                 to_write = (bytes_read + page_size - 1) & ~(page_size - 1);
11659
11660                 written = llapi_mirror_write(fd, mirror_id, buf, to_write,
11661                                              pos);
11662                 if (written < 0) {
11663                         rc = written;
11664                         fprintf(stderr,
11665                               "%s %s: fail to write to mirror %u: %s\n",
11666                                 progname, argv[0], mirror_id,
11667                                 strerror(-rc));
11668                         goto free_buf;
11669                 }
11670
11671                 pos += bytes_read;
11672         }
11673
11674         if (pos & (page_size - 1)) {
11675                 rc = llapi_mirror_truncate(fd, mirror_id, pos);
11676                 if (rc < 0)
11677                         goto free_buf;
11678         }
11679
11680         ioc.lil_mode = LL_LEASE_UNLCK;
11681         ioc.lil_flags = LL_LEASE_RESYNC_DONE;
11682         ioc.lil_count = 0;
11683         rc = llapi_lease_set(fd, (struct ll_ioc_lease *)&ioc);
11684         if (rc <= 0) {
11685                 if (rc == 0)
11686                         rc = -EBUSY;
11687                 fprintf(stderr,
11688                         "%s %s: release lease lock of '%s' failed: %s\n",
11689                         progname, argv[0], fname, strerror(errno));
11690                 goto free_buf;
11691         }
11692
11693         rc = 0;
11694
11695 free_buf:
11696         free(buf);
11697 close_inputfd:
11698         if (inputfile)
11699                 close(inputfd);
11700 close_fd:
11701         close(fd);
11702
11703         return rc;
11704 }
11705
11706 static inline int get_other_mirror_ids(int fd, __u16 *ids, __u16 exclude_id)
11707 {
11708         struct llapi_layout *layout;
11709         struct collect_ids_data cid = { .cid_ids = ids,
11710                                         .cid_count = 0,
11711                                         .cid_exclude = exclude_id, };
11712         int rc;
11713
11714         layout = llapi_layout_get_by_fd(fd, 0);
11715         if (!layout) {
11716                 fprintf(stderr, "could not get layout\n");
11717                 return -EINVAL;
11718         }
11719
11720         rc = llapi_layout_comp_iterate(layout, collect_mirror_id, &cid);
11721         if (rc < 0) {
11722                 fprintf(stderr, "failed to iterate layout\n");
11723                 llapi_layout_free(layout);
11724
11725                 return rc;
11726         }
11727         llapi_layout_free(layout);
11728
11729         return cid.cid_count;
11730 }
11731
11732 #ifndef MIRROR_ID_NEG
11733 #define MIRROR_ID_NEG         0x8000
11734 #endif
11735
11736 static inline int lfs_mirror_copy(int argc, char **argv)
11737 {
11738         int rc = CMD_HELP;
11739         __u16 read_mirror_id = 0;
11740         __u16 ids[128] = { 0 };
11741         int count = 0;
11742         struct llapi_layout *layout = NULL;
11743         struct llapi_resync_comp comp_array[1024] = { { 0 } };
11744         int comp_size = 0;
11745         char *fname;
11746         int fd = 0;
11747         int c;
11748         int i;
11749         ssize_t copied;
11750         struct ll_ioc_lease *ioc = NULL;
11751         struct ll_ioc_lease_id *resync_ioc;
11752         struct option long_opts[] = {
11753         { .val = 'h',   .name = "help",         .has_arg = no_argument },
11754         { .val = 'i',   .name = "read-mirror",  .has_arg = required_argument },
11755         { .val = 'o',   .name = "write-mirror", .has_arg = required_argument },
11756         { .name = NULL } };
11757         char cmd[PATH_MAX];
11758
11759         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
11760         progname = cmd;
11761         while ((c = getopt_long(argc, argv, "hi:o:", long_opts, NULL)) >= 0) {
11762                 char *end;
11763
11764                 switch (c) {
11765                 case 'i': {
11766                         unsigned long int id;
11767
11768                         errno = 0;
11769                         id = strtoul(optarg, &end, 0);
11770                         if (errno != 0 || *end != '\0' || id == 0 ||
11771                             id > UINT16_MAX) {
11772                                 fprintf(stderr,
11773                                         "%s: invalid read mirror ID '%s'\n",
11774                                         progname, optarg);
11775                                 return rc;
11776                         }
11777
11778                         read_mirror_id = (__u16)id;
11779                         break;
11780                 }
11781                 case 'o':
11782                         if (!strcmp(optarg, "-1")) {
11783                                 /* specify all other mirrors */
11784                                 ids[0] = (__u16)-1;
11785                                 count = 1;
11786                         } else {
11787                                 count = parse_mirror_ids((__u16 *)ids,
11788                                                          ARRAY_SIZE(ids),
11789                                                          optarg);
11790                                 if (count < 0)
11791                                         return rc;
11792                         }
11793                         break;
11794                 default:
11795                         fprintf(stderr, "%s: unrecognized option '%s'\n",
11796                                 progname, argv[optind - 1]);
11797                         fallthrough;
11798                 case 'h':
11799                         return CMD_HELP;
11800                 }
11801         }
11802
11803         if (argc == optind) {
11804                 fprintf(stderr, "%s %s: no mirrored file provided\n",
11805                         progname, argv[0]);
11806                 return rc;
11807         } else if (argc > optind + 1) {
11808                 fprintf(stderr, "%s %s: too many files\n", progname, argv[0]);
11809                 return rc;
11810         }
11811
11812         if (read_mirror_id == 0) {
11813                 fprintf(stderr,
11814                         "%s %s: no valid read mirror ID %d is provided\n",
11815                         progname, argv[0], read_mirror_id);
11816                 return rc;
11817         }
11818
11819         if (count == 0) {
11820                 fprintf(stderr,
11821                         "%s %s: no write mirror ID is provided\n",
11822                         progname, argv[0]);
11823                 return rc;
11824         }
11825
11826         for (i = 0; i < count; i++) {
11827                 if (read_mirror_id == ids[i]) {
11828                         fprintf(stderr,
11829                         "%s %s: read and write mirror ID cannot be the same\n",
11830                                 progname, argv[0]);
11831                         return rc;
11832                 }
11833         }
11834
11835         /* open mirror file */
11836         fname = argv[optind];
11837
11838         fd = open(fname, O_DIRECT | O_RDWR);
11839         if (fd < 0) {
11840                 fprintf(stderr, "%s %s: cannot open '%s': %s\n",
11841                         progname, argv[0], fname, strerror(errno));
11842                 return rc;
11843         }
11844
11845         /* write to all other mirrors */
11846         if (ids[0] == (__u16)-1) {
11847                 count = get_other_mirror_ids(fd, ids, read_mirror_id);
11848                 if (count <= 0) {
11849                         rc = count;
11850                         fprintf(stderr,
11851                         "%s %s: failed to get other mirror ids in '%s': %d\n",
11852                                 progname, argv[0], fname, rc);
11853                         goto close_fd;
11854                 }
11855         }
11856
11857         /* verify mirror id */
11858         rc = verify_mirror_id_by_fd(fd, read_mirror_id);
11859         if (rc) {
11860                 fprintf(stderr,
11861                         "%s %s: cannot find mirror with ID %u in '%s'\n",
11862                         progname, argv[0], read_mirror_id, fname);
11863                 goto close_fd;
11864         }
11865
11866         for (i = 0; i < count; i++) {
11867                 rc = verify_mirror_id_by_fd(fd, ids[i]);
11868                 if (rc) {
11869                         fprintf(stderr,
11870                         "%s %s: cannot find mirror with ID %u in '%s'\n",
11871                                 progname, argv[0], ids[i], fname);
11872                         goto close_fd;
11873                 }
11874         }
11875
11876         ioc = calloc(sizeof(*ioc) + sizeof(__u32) * 4096, 1);
11877         if (!ioc) {
11878                 fprintf(stderr,
11879                         "%s %s: cannot alloc comp id array for ioc: %s\n",
11880                         progname, argv[0], strerror(errno));
11881                 rc = -errno;
11882                 goto close_fd;
11883         }
11884
11885         /* get stale component info */
11886         layout = llapi_layout_get_by_fd(fd, 0);
11887         if (!layout) {
11888                 fprintf(stderr, "%s %s: failed to get layout of '%s': %s\n",
11889                         progname, argv[0], fname, strerror(errno));
11890                 rc = -errno;
11891                 goto free_ioc;
11892         }
11893         comp_size = llapi_mirror_find_stale(layout, comp_array,
11894                                             ARRAY_SIZE(comp_array),
11895                                             ids, count);
11896         llapi_layout_free(layout);
11897         if (comp_size < 0) {
11898                 rc = comp_size;
11899                 goto free_ioc;
11900         }
11901
11902         /* prepare target mirror components instantiation */
11903         resync_ioc = (struct ll_ioc_lease_id *)ioc;
11904         resync_ioc->lil_mode = LL_LEASE_WRLCK;
11905         resync_ioc->lil_flags = LL_LEASE_RESYNC;
11906         if (count == 1)
11907                 resync_ioc->lil_mirror_id = ids[0];
11908         else
11909                 resync_ioc->lil_mirror_id = read_mirror_id | MIRROR_ID_NEG;
11910         rc = llapi_lease_set(fd, ioc);
11911         if (rc < 0) {
11912                 fprintf(stderr,
11913                         "%s %s: '%s' llapi_lease_get_ext failed: %s\n",
11914                         progname, argv[0], fname, strerror(errno));
11915                 goto free_ioc;
11916         }
11917
11918         copied = llapi_mirror_copy_many(fd, read_mirror_id, ids, count);
11919         if (copied < 0) {
11920                 rc = copied;
11921                 fprintf(stderr, "%s %s: copy error: %d\n",
11922                         progname, argv[0], rc);
11923                 goto free_ioc;
11924         }
11925
11926         fprintf(stdout, "mirror copied successfully: ");
11927         for (i = 0; i < copied; i++)
11928                 fprintf(stdout, "%d ", ids[i]);
11929         fprintf(stdout, "\n");
11930
11931         ioc->lil_mode = LL_LEASE_UNLCK;
11932         ioc->lil_flags = LL_LEASE_RESYNC_DONE;
11933         ioc->lil_count = 0;
11934         for (i = 0; i < comp_size; i++) {
11935                 int j;
11936
11937                 for (j = 0; j < copied; j++) {
11938                         if (comp_array[i].lrc_mirror_id != ids[j])
11939                                 continue;
11940
11941                         ioc->lil_ids[ioc->lil_count] = comp_array[i].lrc_id;
11942                         ioc->lil_count++;
11943                 }
11944         }
11945         rc = llapi_lease_set(fd, ioc);
11946         if (rc <= 0) {
11947                 if (rc == 0)
11948                         rc = -EBUSY;
11949                 fprintf(stderr,
11950                         "%s %s: release lease lock of '%s' failed: %s\n",
11951                         progname, argv[0], fname, strerror(errno));
11952                 goto free_ioc;
11953         }
11954
11955         rc = 0;
11956
11957 free_ioc:
11958         free(ioc);
11959 close_fd:
11960         close(fd);
11961
11962         return rc;
11963 }
11964
11965 /**
11966  * struct verify_chunk - Mirror chunk to be verified.
11967  * @chunk:        [start, end) of the chunk.
11968  * @mirror_count: Number of mirror ids in @mirror_id array.
11969  * @mirror_id:    Array of valid mirror ids that cover the chunk.
11970  */
11971 struct verify_chunk {
11972         struct lu_extent chunk;
11973         unsigned int mirror_count;
11974         __u16 mirror_id[LUSTRE_MIRROR_COUNT_MAX];
11975 };
11976
11977 /**
11978  * print_chunks() - Print chunk information.
11979  * @fname:       Mirrored file name.
11980  * @chunks:      Array of chunks.
11981  * @chunk_count: Number of chunks in @chunks array.
11982  *
11983  * This function prints [start, end) of each chunk in @chunks
11984  * for mirrored file @fname, and also prints the valid mirror ids
11985  * that cover the chunk.
11986  *
11987  * Return: void.
11988  */
11989 static inline
11990 void print_chunks(const char *fname, struct verify_chunk *chunks,
11991                   int chunk_count)
11992 {
11993         int i;
11994         int j;
11995
11996         fprintf(stdout, "Chunks to be verified in %s:\n", fname);
11997         for (i = 0; i < chunk_count; i++) {
11998                 fprintf(stdout, DEXT, PEXT(&chunks[i].chunk));
11999
12000                 if (chunks[i].mirror_count == 0)
12001                         fprintf(stdout, "\t[");
12002                 else {
12003                         fprintf(stdout, "\t[%u", chunks[i].mirror_id[0]);
12004                         for (j = 1; j < chunks[i].mirror_count; j++)
12005                                 fprintf(stdout, ", %u", chunks[i].mirror_id[j]);
12006                 }
12007                 fprintf(stdout, "]\t%u\n", chunks[i].mirror_count);
12008         }
12009         fprintf(stdout, "\n");
12010 }
12011
12012 /**
12013  * print_checksums() - Print CRC-32 checksum values.
12014  * @chunk: A chunk and its corresponding valid mirror ids.
12015  * @crc:   CRC-32 checksum values on the chunk for each valid mirror.
12016  *
12017  * This function prints CRC-32 checksum values on @chunk for
12018  * each valid mirror that covers it.
12019  *
12020  * Return: void.
12021  */
12022 static inline
12023 void print_checksums(struct verify_chunk *chunk, unsigned long *crc,
12024                      unsigned long long pos, unsigned long long len)
12025 {
12026         int i;
12027
12028         fprintf(stdout,
12029                 "CRC-32 checksum value for chunk "DEXT":\n", pos, pos + len);
12030         for (i = 0; i < chunk->mirror_count; i++)
12031                 fprintf(stdout, "Mirror %u:\t%#lx\n",
12032                         chunk->mirror_id[i], crc[i]);
12033         fprintf(stdout, "\n");
12034 }
12035
12036 /**
12037  * filter_mirror_id() - Filter specified mirror ids.
12038  * @chunks:      Array of chunks.
12039  * @chunk_count: Number of chunks in @chunks array.
12040  * @mirror_ids:  Specified mirror ids to be verified.
12041  * @ids_nr:      Number of specified mirror ids.
12042  *
12043  * This function scans valid mirror ids that cover each chunk in @chunks
12044  * and filters specified mirror ids.
12045  *
12046  * Return: void.
12047  */
12048 static inline
12049 void filter_mirror_id(struct verify_chunk *chunks, int chunk_count,
12050                       __u16 *mirror_ids, int ids_nr)
12051 {
12052         int i;
12053         int j;
12054         int k;
12055         __u16 valid_id[LUSTRE_MIRROR_COUNT_MAX] = { 0 };
12056         unsigned int valid_count = 0;
12057
12058         for (i = 0; i < chunk_count; i++) {
12059                 if (chunks[i].mirror_count == 0)
12060                         continue;
12061
12062                 valid_count = 0;
12063                 for (j = 0; j < ids_nr; j++) {
12064                         for (k = 0; k < chunks[i].mirror_count; k++) {
12065                                 if (chunks[i].mirror_id[k] == mirror_ids[j]) {
12066                                         valid_id[valid_count] = mirror_ids[j];
12067                                         valid_count++;
12068                                         break;
12069                                 }
12070                         }
12071                 }
12072
12073                 memcpy(chunks[i].mirror_id, valid_id,
12074                        sizeof(__u16) * valid_count);
12075                 chunks[i].mirror_count = valid_count;
12076         }
12077 }
12078
12079 /**
12080  * lfs_mirror_prepare_chunk() - Find mirror chunks to be verified.
12081  * @layout:      Mirror component list.
12082  * @chunks:      Array of chunks.
12083  * @chunks_size: Array size of @chunks.
12084  *
12085  * This function scans the components in @layout from offset 0 to LUSTRE_EOF
12086  * to find out chunk segments and store them in @chunks array.
12087  *
12088  * The @mirror_id array in each element of @chunks will store the valid
12089  * mirror ids that cover the chunk. If a mirror component covering the
12090  * chunk has LCME_FL_STALE or LCME_FL_OFFLINE flag, then the mirror id
12091  * will not be stored into the @mirror_id array, and the chunk for that
12092  * mirror will not be verified.
12093  *
12094  * The @mirror_count in each element of @chunks will store the number of
12095  * mirror ids in @mirror_id array. If @mirror_count is 0, it indicates the
12096  * chunk is invalid in all of the mirrors. And if @mirror_count is 1, it
12097  * indicates the chunk is valid in only one mirror. In both cases, the
12098  * chunk will not be verified.
12099  *
12100  * Here is an example:
12101  *
12102  *  0      1M     2M     3M     4M           EOF
12103  *  +------+-------------+--------------------+
12104  *  |      |             |      S             |       mirror1
12105  *  +------+------+------+------+-------------+
12106  *  |             |   S  |   S  |             |       mirror2
12107  *  +-------------+------+------+-------------+
12108  *
12109  * prepared @chunks array will contain 5 elements:
12110  * (([0, 1M), [1, 2], 2),
12111  *  ([1M, 2M), [1, 2], 2),
12112  *  ([2M, 3M), [1], 1),
12113  *  ([3M, 4M], [], 0),
12114  *  ([4M, EOF), [2], 1))
12115  *
12116  * Return: the actual array size of @chunks on success
12117  *         or a negative error code on failure.
12118  */
12119 static inline
12120 int lfs_mirror_prepare_chunk(struct llapi_layout *layout,
12121                              struct verify_chunk *chunks,
12122                              size_t chunks_size)
12123 {
12124         uint64_t start;
12125         uint64_t end;
12126         uint32_t mirror_id;
12127         uint32_t flags;
12128         int idx = 0;
12129         int i = 0;
12130         int rc = 0;
12131
12132         memset(chunks, 0, sizeof(*chunks) * chunks_size);
12133
12134         while (1) {
12135                 rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_FIRST);
12136                 if (rc < 0) {
12137                         fprintf(stderr,
12138                                 "%s: move to the first layout component: %s.\n",
12139                                 progname, strerror(errno));
12140                         goto error;
12141                 }
12142
12143                 i = 0;
12144                 rc = 0;
12145                 chunks[idx].chunk.e_end = LUSTRE_EOF;
12146                 while (rc == 0) {
12147                         rc = llapi_layout_comp_extent_get(layout, &start, &end);
12148                         if (rc < 0) {
12149                                 fprintf(stderr,
12150                                         "%s: llapi_layout_comp_extent_get failed: %s.\n",
12151                                         progname, strerror(errno));
12152                                 goto error;
12153                         }
12154
12155                         if (start > chunks[idx].chunk.e_start ||
12156                             end <= chunks[idx].chunk.e_start)
12157                                 goto next;
12158
12159                         if (end < chunks[idx].chunk.e_end)
12160                                 chunks[idx].chunk.e_end = end;
12161
12162                         rc = llapi_layout_comp_flags_get(layout, &flags);
12163                         if (rc < 0) {
12164                                 fprintf(stderr,
12165                                         "%s: llapi_layout_comp_flags_get failed: %s.\n",
12166                                         progname, strerror(errno));
12167                                 goto error;
12168                         }
12169
12170                         if (flags & LCME_FL_STALE || flags & LCME_FL_OFFLINE)
12171                                 goto next;
12172
12173                         rc = llapi_layout_mirror_id_get(layout, &mirror_id);
12174                         if (rc < 0) {
12175                                 fprintf(stderr,
12176                                         "%s: llapi_layout_mirror_id_get failed: %s.\n",
12177                                         progname, strerror(errno));
12178                                 goto error;
12179                         }
12180
12181                         if (i >= ARRAY_SIZE(chunks[idx].mirror_id)) {
12182                                 fprintf(stderr,
12183                                         "%s: mirror_id array is too small.\n",
12184                                         progname);
12185                                 rc = -EINVAL;
12186                                 goto error;
12187                         }
12188                         chunks[idx].mirror_id[i] = mirror_id;
12189                         i++;
12190
12191 next:
12192                         rc = llapi_layout_comp_use(layout,
12193                                                    LLAPI_LAYOUT_COMP_USE_NEXT);
12194                         if (rc < 0) {
12195                                 fprintf(stderr,
12196                                         "%s: move to the next layout component: %s.\n",
12197                                         progname, strerror(errno));
12198                                 goto error;
12199                         }
12200                 } /* loop through all components */
12201
12202                 chunks[idx].mirror_count = i;
12203
12204                 if (chunks[idx].chunk.e_end == LUSTRE_EOF)
12205                         break;
12206
12207                 idx++;
12208                 if (idx >= chunks_size) {
12209                         fprintf(stderr, "%s: chunks array is too small.\n",
12210                                 progname);
12211                         rc = -EINVAL;
12212                         goto error;
12213                 }
12214
12215                 chunks[idx].chunk.e_start = chunks[idx - 1].chunk.e_end;
12216         }
12217
12218 error:
12219         return rc < 0 ? rc : idx + 1;
12220 }
12221
12222 /**
12223  * lfs_mirror_verify_chunk() - Verify a chunk.
12224  * @fd:        File descriptor of the mirrored file.
12225  * @file_size: Size of the mirrored file.
12226  * @chunk:     A chunk and its corresponding valid mirror ids.
12227  * @verbose:   Verbose mode.
12228  *
12229  * This function verifies a @chunk contains exactly the same data
12230  * ammong the mirrors that cover it.
12231  *
12232  * If @verbose is specified, then the function will print where the
12233  * differences are if the data do not match. Otherwise, it will
12234  * just return an error in that case.
12235  *
12236  * Return: 0 on success or a negative error code on failure.
12237  */
12238 static inline
12239 int lfs_mirror_verify_chunk(int fd, size_t file_size,
12240                             struct verify_chunk *chunk, int verbose)
12241 {
12242         const size_t buflen = 4 * 1024 * 1024; /* 4M */
12243         void *buf;
12244         size_t page_size = sysconf(_SC_PAGESIZE);
12245         ssize_t bytes_read;
12246         ssize_t bytes_done;
12247         size_t count;
12248         off_t pos;
12249         unsigned long crc;
12250         unsigned long crc_array[LUSTRE_MIRROR_COUNT_MAX] = { 0 };
12251         int i;
12252         int rc = 0;
12253
12254         if (file_size == 0)
12255                 return 0;
12256
12257         rc = posix_memalign(&buf, page_size, buflen);
12258         if (rc) /* error code is returned directly */
12259                 return -rc;
12260
12261         if (verbose > 1) {
12262                 fprintf(stdout, "Verifying chunk "DEXT" on mirror:",
12263                         PEXT(&chunk->chunk));
12264                 for (i = 0; i < chunk->mirror_count; i++)
12265                         fprintf(stdout, " %u", chunk->mirror_id[i]);
12266                 fprintf(stdout, "\n");
12267         }
12268
12269         bytes_done = 0;
12270         count = MIN(chunk->chunk.e_end, file_size) - chunk->chunk.e_start;
12271         pos = chunk->chunk.e_start;
12272         while (bytes_done < count) {
12273                 /* compute initial CRC-32 checksum */
12274                 crc = crc32(0L, Z_NULL, 0);
12275                 memset(crc_array, 0, sizeof(crc_array));
12276
12277                 bytes_read = 0;
12278                 for (i = 0; i < chunk->mirror_count; i++) {
12279                         bytes_read = llapi_mirror_read(fd, chunk->mirror_id[i],
12280                                                        buf, buflen, pos);
12281                         if (bytes_read < 0) {
12282                                 rc = bytes_read;
12283                                 fprintf(stderr,
12284                                         "%s: failed to read data from mirror %u: %s.\n",
12285                                         progname, chunk->mirror_id[i],
12286                                         strerror(-rc));
12287                                 goto error;
12288                         }
12289
12290                         /* compute new CRC-32 checksum */
12291                         crc_array[i] = crc32(crc, buf, bytes_read);
12292                 }
12293
12294                 if (verbose)
12295                         print_checksums(chunk, crc_array, pos, buflen);
12296
12297                 /* compare CRC-32 checksum values */
12298                 for (i = 1; i < chunk->mirror_count; i++) {
12299                         if (crc_array[i] != crc_array[0]) {
12300                                 rc = -EINVAL;
12301
12302                                 fprintf(stderr,
12303                                         "%s: chunk "DEXT" has different checksum value on mirror %u and mirror %u.\n",
12304                                         progname, PEXT(&chunk->chunk),
12305                                         chunk->mirror_id[0],
12306                                         chunk->mirror_id[i]);
12307                         }
12308                 }
12309
12310                 pos += bytes_read;
12311                 bytes_done += bytes_read;
12312         }
12313
12314         if (verbose > 1 && rc == 0) {
12315                 fprintf(stdout, "Verifying chunk "DEXT" on mirror:",
12316                         PEXT(&chunk->chunk));
12317                 for (i = 0; i < chunk->mirror_count; i++)
12318                         fprintf(stdout, " %u", chunk->mirror_id[i]);
12319                 fprintf(stdout, " PASS\n\n");
12320         }
12321
12322 error:
12323         free(buf);
12324         return rc;
12325 }
12326
12327 /**
12328  * lfs_mirror_verify_file() - Verify a mirrored file.
12329  * @fname:      Mirrored file name.
12330  * @mirror_ids: Specified mirror ids to be verified.
12331  * @ids_nr:     Number of specified mirror ids.
12332  * @verbose:    Verbose mode.
12333  *
12334  * This function verifies that each SYNC mirror of a mirrored file
12335  * specified by @fname contains exactly the same data.
12336  *
12337  * If @mirror_ids is specified, then the function will verify the
12338  * mirrors specified by @mirror_ids contain exactly the same data.
12339  *
12340  * If @verbose is specified, then the function will print where the
12341  * differences are if the data do not match. Otherwise, it will
12342  * just return an error in that case.
12343  *
12344  * Return: 0 on success or a negative error code on failure.
12345  */
12346 static inline
12347 int lfs_mirror_verify_file(const char *fname, __u16 *mirror_ids, int ids_nr,
12348                            int verbose)
12349 {
12350         struct verify_chunk chunks_array[1024] = { };
12351         struct llapi_layout *layout = NULL;
12352         struct stat stbuf;
12353         uint32_t flr_state;
12354         int fd;
12355         int chunk_count = 0;
12356         int idx = 0;
12357         int rc = 0;
12358         int rc1 = 0;
12359         int rc2 = 0;
12360
12361         if (stat(fname, &stbuf) < 0) {
12362                 fprintf(stderr, "%s: cannot stat file '%s': %s.\n",
12363                         progname, fname, strerror(errno));
12364                 rc = -errno;
12365                 goto error;
12366         }
12367
12368         if (!S_ISREG(stbuf.st_mode)) {
12369                 fprintf(stderr, "%s: '%s' is not a regular file.\n",
12370                         progname, fname);
12371                 rc = -EINVAL;
12372                 goto error;
12373         }
12374
12375         if (stbuf.st_size == 0) {
12376                 if (verbose)
12377                         fprintf(stdout, "%s: '%s' file size is 0.\n",
12378                                 progname, fname);
12379                 rc = 0;
12380                 goto error;
12381         }
12382
12383         /* Allow mirror verify even without the key on encrypted files */
12384         fd = open(fname, O_DIRECT | O_RDONLY | O_FILE_ENC);
12385         if (fd < 0) {
12386                 fprintf(stderr, "%s: cannot open '%s': %s.\n",
12387                         progname, fname, strerror(errno));
12388                 rc = -errno;
12389                 goto error;
12390         }
12391
12392         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
12393         if (rc < 0) {
12394                 fprintf(stderr, "%s: '%s' llapi_lease_acquire failed: %s.\n",
12395                         progname, fname, strerror(errno));
12396                 goto close_fd;
12397         }
12398
12399         layout = llapi_layout_get_by_fd(fd, 0);
12400         if (!layout) {
12401                 fprintf(stderr, "%s: '%s' llapi_layout_get_by_fd failed: %s.\n",
12402                         progname, fname, strerror(errno));
12403                 rc = -errno;
12404                 llapi_lease_release(fd);
12405                 goto close_fd;
12406         }
12407
12408         rc = llapi_layout_flags_get(layout, &flr_state);
12409         if (rc < 0) {
12410                 fprintf(stderr, "%s: '%s' llapi_layout_flags_get failed: %s.\n",
12411                         progname, fname, strerror(errno));
12412                 rc = -errno;
12413                 goto free_layout;
12414         }
12415
12416         flr_state &= LCM_FL_FLR_MASK;
12417         switch (flr_state) {
12418         case LCM_FL_NONE:
12419                 rc = -EINVAL;
12420                 fprintf(stderr, "%s: '%s' file state error: %s.\n",
12421                         progname, fname, llapi_layout_flags_string(flr_state));
12422                 goto free_layout;
12423         default:
12424                 break;
12425         }
12426
12427         /* find out mirror chunks to be verified */
12428         chunk_count = lfs_mirror_prepare_chunk(layout, chunks_array,
12429                                                ARRAY_SIZE(chunks_array));
12430         if (chunk_count < 0) {
12431                 rc = chunk_count;
12432                 goto free_layout;
12433         }
12434
12435         if (ids_nr > 0)
12436                 /* filter specified mirror ids */
12437                 filter_mirror_id(chunks_array, chunk_count, mirror_ids, ids_nr);
12438
12439         if (verbose > 2)
12440                 print_chunks(fname, chunks_array, chunk_count);
12441
12442         for (idx = 0; idx < chunk_count; idx++) {
12443                 if (chunks_array[idx].chunk.e_start >= stbuf.st_size) {
12444                         if (verbose)
12445                                 fprintf(stdout,
12446                                         "%s: '%s' chunk "DEXT" exceeds file size %#llx: skipped\n",
12447                                         progname, fname,
12448                                         PEXT(&chunks_array[idx].chunk),
12449                                         (unsigned long long)stbuf.st_size);
12450                         break;
12451                 }
12452
12453                 if (chunks_array[idx].mirror_count == 0) {
12454                         fprintf(stderr,
12455                                 "%s: '%s' chunk "DEXT" is invalid in all of the mirrors: ",
12456                                 progname, fname,
12457                                 PEXT(&chunks_array[idx].chunk));
12458                         if (verbose) {
12459                                 fprintf(stderr, "skipped\n");
12460                                 continue;
12461                         }
12462                         rc = -EINVAL;
12463                         fprintf(stderr, "failed\n");
12464                         goto free_layout;
12465                 }
12466
12467                 if (chunks_array[idx].mirror_count == 1) {
12468                         if (verbose)
12469                                 fprintf(stdout,
12470                                         "%s: '%s' chunk "DEXT" is only valid in mirror %u: skipped\n",
12471                                         progname, fname,
12472                                         PEXT(&chunks_array[idx].chunk),
12473                                         chunks_array[idx].mirror_id[0]);
12474                         continue;
12475                 }
12476
12477                 rc = llapi_lease_check(fd);
12478                 if (rc != LL_LEASE_RDLCK) {
12479                         fprintf(stderr, "%s: '%s' lost lease lock.\n",
12480                                 progname, fname);
12481                         goto free_layout;
12482                 }
12483
12484                 /* verify one chunk */
12485                 rc1 = lfs_mirror_verify_chunk(fd, stbuf.st_size,
12486                                               &chunks_array[idx], verbose);
12487                 if (rc1 < 0) {
12488                         rc2 = rc1;
12489                         if (!verbose) {
12490                                 rc = rc1;
12491                                 goto free_layout;
12492                         }
12493                 }
12494         }
12495
12496         if (rc2 < 0)
12497                 rc = rc2;
12498
12499 free_layout:
12500         llapi_layout_free(layout);
12501         llapi_lease_release(fd);
12502 close_fd:
12503         close(fd);
12504 error:
12505         return rc;
12506 }
12507
12508 /**
12509  * lfs_mirror_verify() - Parse and execute lfs mirror verify command.
12510  * @argc: The count of lfs mirror verify command line arguments.
12511  * @argv: Array of strings for lfs mirror verify command line arguments.
12512  *
12513  * This function parses lfs mirror verify command and verifies the
12514  * specified mirrored file(s).
12515  *
12516  * Return: 0 on success or a negative error code on failure.
12517  */
12518 static inline int lfs_mirror_verify(int argc, char **argv)
12519 {
12520         __u16 mirror_ids[LUSTRE_MIRROR_COUNT_MAX] = { 0 };
12521         int ids_nr = 0;
12522         int c;
12523         int verbose = 0;
12524         int rc = 0;
12525         int rc1 = 0;
12526         char cmd[PATH_MAX];
12527
12528         struct option long_opts[] = {
12529         { .val = 'h',   .name = "help",         .has_arg = no_argument },
12530         { .val = 'o',   .name = "only",         .has_arg = required_argument },
12531         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
12532         { .name = NULL } };
12533
12534         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
12535         progname = cmd;
12536         while ((c = getopt_long(argc, argv, "ho:v", long_opts, NULL)) >= 0) {
12537                 switch (c) {
12538                 case 'o':
12539                         rc = parse_mirror_ids(mirror_ids,
12540                                               ARRAY_SIZE(mirror_ids),
12541                                               optarg);
12542                         if (rc < 0) {
12543                                 fprintf(stderr,
12544                                         "%s: bad mirror ids '%s'.\n",
12545                                         progname, optarg);
12546                                 goto error;
12547                         }
12548                         ids_nr = rc;
12549                         if (ids_nr < 2) {
12550                                 fprintf(stderr,
12551                                         "%s: at least 2 mirror ids needed with '--only' option.\n",
12552                                         progname);
12553                                 rc = CMD_HELP;
12554                                 goto error;
12555                         }
12556                         break;
12557                 case 'v':
12558                         verbose++;
12559                         break;
12560                 default:
12561                         fprintf(stderr, "%s: unrecognized option '%s'\n",
12562                                 progname, argv[optind - 1]);
12563                         fallthrough;
12564                 case 'h':
12565                         rc = CMD_HELP;
12566                         goto error;
12567                 }
12568         }
12569
12570         if (argc == optind) {
12571                 fprintf(stderr, "%s: no file name given.\n", progname);
12572                 rc = CMD_HELP;
12573                 goto error;
12574         }
12575
12576         if (ids_nr > 0 && argc > optind + 1) {
12577                 fprintf(stderr,
12578                         "%s: '--only' cannot be used upon multiple files.\n",
12579                         progname);
12580                 rc = CMD_HELP;
12581                 goto error;
12582         }
12583
12584         if (ids_nr > 0) {
12585                 rc = verify_mirror_ids(argv[optind], mirror_ids, ids_nr);
12586                 if (rc < 0)
12587                         goto error;
12588         }
12589
12590         rc = 0;
12591         for (; optind < argc; optind++) {
12592                 rc1 = lfs_mirror_verify_file(argv[optind], mirror_ids, ids_nr,
12593                                              verbose);
12594                 if (rc1 < 0)
12595                         rc = rc1;
12596         }
12597 error:
12598         return rc;
12599 }
12600
12601 /**
12602  * lfs_mirror() - Parse and execute lfs mirror commands.
12603  * @argc: The count of lfs mirror command line arguments.
12604  * @argv: Array of strings for lfs mirror command line arguments.
12605  *
12606  * This function parses lfs mirror commands and performs the
12607  * corresponding functions specified in mirror_cmdlist[].
12608  *
12609  * Return: 0 on success or an error code on failure.
12610  */
12611 static int lfs_mirror(int argc, char **argv)
12612 {
12613         char cmd[PATH_MAX];
12614         int rc = 0;
12615
12616         setlinebuf(stdout);
12617
12618         Parser_init("lfs-mirror > ", mirror_cmdlist);
12619
12620         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
12621         progname = cmd;
12622         program_invocation_short_name = cmd;
12623         if (argc > 1)
12624                 rc = Parser_execarg(argc - 1, argv + 1, mirror_cmdlist);
12625         else
12626                 rc = Parser_commands();
12627
12628         return rc < 0 ? -rc : rc;
12629 }
12630
12631 static void lustre_som_swab(struct lustre_som_attrs *attrs)
12632 {
12633 #if __BYTE_ORDER == __BIG_ENDIAN
12634         __swab16s(&attrs->lsa_valid);
12635         __swab64s(&attrs->lsa_size);
12636         __swab64s(&attrs->lsa_blocks);
12637 #endif
12638 }
12639
12640 enum lfs_som_type {
12641         LFS_SOM_SIZE = 0x1,
12642         LFS_SOM_BLOCKS = 0x2,
12643         LFS_SOM_FLAGS = 0x4,
12644         LFS_SOM_ATTR_ALL = LFS_SOM_SIZE | LFS_SOM_BLOCKS |
12645                            LFS_SOM_FLAGS,
12646 };
12647
12648 static int lfs_getsom(int argc, char **argv)
12649 {
12650         const char *path;
12651         struct lustre_som_attrs *attrs;
12652         char buf[sizeof(*attrs) + 64];
12653         enum lfs_som_type type = LFS_SOM_ATTR_ALL;
12654         int rc = 0, c;
12655
12656         while ((c = getopt(argc, argv, "bfhs")) != -1) {
12657                 switch (c) {
12658                 case 'b':
12659                         type = LFS_SOM_BLOCKS;
12660                         break;
12661                 case 'f':
12662                         type = LFS_SOM_FLAGS;
12663                         break;
12664                 case 's':
12665                         type = LFS_SOM_SIZE;
12666                         break;
12667                 default:
12668                         fprintf(stderr, "%s: unrecognized option '%s'\n",
12669                                 progname, argv[optind - 1]);
12670                         fallthrough;
12671                 case 'h':
12672                         return CMD_HELP;
12673                 }
12674         }
12675
12676         argc -= optind;
12677         argv += optind;
12678
12679         if (argc != 1) {
12680                 fprintf(stderr, "%s: %s\n",
12681                         progname, argc == 0 ? "miss file target" :
12682                         "input more than 2 files");
12683                 return CMD_HELP;
12684         }
12685
12686         path = argv[0];
12687         attrs = (void *)buf;
12688         rc = lgetxattr(path, "trusted.som", attrs, sizeof(buf));
12689         if (rc < 0) {
12690                 rc = -errno;
12691                 fprintf(stderr, "%s failed to get som xattr: %s (%d)\n",
12692                         argv[0], strerror(errno), errno);
12693                 return rc;
12694         }
12695
12696         lustre_som_swab(attrs);
12697
12698         switch (type) {
12699         case LFS_SOM_ATTR_ALL:
12700                 printf("file: %s size: %llu blocks: %llu flags: %x\n",
12701                        path, (unsigned long long)attrs->lsa_size,
12702                        (unsigned long long)attrs->lsa_blocks,
12703                        attrs->lsa_valid);
12704                 break;
12705         case LFS_SOM_SIZE:
12706                 printf("%llu\n", (unsigned long long)attrs->lsa_size);
12707                 break;
12708         case LFS_SOM_BLOCKS:
12709                 printf("%llu\n", (unsigned long long)attrs->lsa_blocks);
12710                 break;
12711         case LFS_SOM_FLAGS:
12712                 printf("%x\n", attrs->lsa_valid);
12713                 break;
12714         default:
12715                 fprintf(stderr, "%s: unknown option\n", progname);
12716                 return CMD_HELP;
12717         }
12718
12719         return 0;
12720 }
12721
12722 /**
12723  * lfs_mirror_list_commands() - List lfs mirror commands.
12724  * @argc: The count of command line arguments.
12725  * @argv: Array of strings for command line arguments.
12726  *
12727  * This function lists lfs mirror commands defined in mirror_cmdlist[].
12728  *
12729  * Return: 0 on success.
12730  */
12731 static int lfs_mirror_list_commands(int argc, char **argv)
12732 {
12733         char buffer[81] = "";
12734
12735         Parser_list_commands(mirror_cmdlist, buffer, sizeof(buffer),
12736                              NULL, 0, 4);
12737
12738         return 0;
12739 }
12740
12741 static int lfs_pcc_attach(int argc, char **argv)
12742 {
12743         struct option long_opts[] = {
12744         { .val = 'h',   .name = "help", .has_arg = no_argument },
12745         { .val = 'i',   .name = "id",   .has_arg = required_argument },
12746         { .name = NULL } };
12747         int c;
12748         int rc = 0;
12749         __u32 archive_id = 0;
12750         const char *path;
12751         char *end;
12752         char fullpath[PATH_MAX];
12753         enum lu_pcc_type type = LU_PCC_READWRITE;
12754
12755         optind = 0;
12756         while ((c = getopt_long(argc, argv, "hi:",
12757                                 long_opts, NULL)) != -1) {
12758                 switch (c) {
12759                 case 'i':
12760                         errno = 0;
12761                         archive_id = strtoul(optarg, &end, 0);
12762                         if (errno != 0 || *end != '\0' ||
12763                             archive_id == 0 || archive_id > UINT32_MAX) {
12764                                 fprintf(stderr,
12765                                         "error: %s: bad archive ID '%s'\n",
12766                                         progname, optarg);
12767                                 return CMD_HELP;
12768                         }
12769                         break;
12770                 default:
12771                         fprintf(stderr, "%s: unrecognized option '%s'\n",
12772                                 progname, argv[optind - 1]);
12773                         fallthrough;
12774                 case 'h':
12775                         return CMD_HELP;
12776                 }
12777         }
12778
12779         if (archive_id == 0) {
12780                 fprintf(stderr, "%s: must specify attach ID\n", argv[0]);
12781                 return CMD_HELP;
12782         }
12783
12784         if (argc <= optind) {
12785                 fprintf(stderr, "%s: must specify one or more file names\n",
12786                         argv[0]);
12787                 return CMD_HELP;
12788         }
12789
12790         while (optind < argc) {
12791                 int rc2;
12792
12793                 path = argv[optind++];
12794                 if (!realpath(path, fullpath)) {
12795                         fprintf(stderr, "%s: could not find path '%s': %s\n",
12796                                 argv[0], path, strerror(errno));
12797                         if (rc == 0)
12798                                 rc = -EINVAL;
12799                         continue;
12800                 }
12801
12802                 rc2 = llapi_pcc_attach(fullpath, archive_id, type);
12803                 if (rc2 < 0) {
12804                         fprintf(stderr,
12805                                 "%s: cannot attach '%s' to PCC with archive ID '%u': %s\n",
12806                                 argv[0], path, archive_id, strerror(-rc2));
12807                         if (rc == 0)
12808                                 rc = rc2;
12809                 }
12810         }
12811         return rc;
12812 }
12813
12814 static int lfs_pcc_attach_fid(int argc, char **argv)
12815 {
12816         struct option long_opts[] = {
12817         { .val = 'h',   .name = "help", .has_arg = no_argument },
12818         { .val = 'i',   .name = "id",   .has_arg = required_argument },
12819         { .val = 'm',   .name = "mnt",  .has_arg = required_argument },
12820         { .name = NULL } };
12821         int c;
12822         int rc = 0;
12823         __u32 archive_id = 0;
12824         char *end;
12825         const char *mntpath = NULL;
12826         const char *fidstr;
12827         enum lu_pcc_type type = LU_PCC_READWRITE;
12828
12829         optind = 0;
12830         while ((c = getopt_long(argc, argv, "hi:m:",
12831                                 long_opts, NULL)) != -1) {
12832                 switch (c) {
12833                 case 'i':
12834                         errno = 0;
12835                         archive_id = strtoul(optarg, &end, 0);
12836                         if (errno != 0 || *end != '\0' ||
12837                             archive_id > UINT32_MAX) {
12838                                 fprintf(stderr,
12839                                         "error: %s: bad archive ID '%s'\n",
12840                                         argv[0], optarg);
12841                                 return CMD_HELP;
12842                         }
12843                         break;
12844                 case 'm':
12845                         mntpath = optarg;
12846                         break;
12847                 default:
12848                         fprintf(stderr, "%s: unrecognized option '%s'\n",
12849                                 progname, argv[optind - 1]);
12850                         fallthrough;
12851                 case 'h':
12852                         return CMD_HELP;
12853                 }
12854         }
12855
12856         if (archive_id == 0) {
12857                 fprintf(stderr, "%s: must specify an archive ID\n", argv[0]);
12858                 return CMD_HELP;
12859         }
12860
12861         if (!mntpath) {
12862                 fprintf(stderr, "%s: must specify Lustre mount point\n",
12863                         argv[0]);
12864                 return CMD_HELP;
12865         }
12866
12867         if (argc <= optind) {
12868                 fprintf(stderr, "%s: must specify one or more fids\n", argv[0]);
12869                 return CMD_HELP;
12870         }
12871
12872         while (optind < argc) {
12873                 int rc2;
12874
12875                 fidstr = argv[optind++];
12876
12877                 rc2 = llapi_pcc_attach_fid_str(mntpath, fidstr,
12878                                                archive_id, type);
12879                 if (rc2 < 0) {
12880                         fprintf(stderr,
12881                                 "%s: cannot attach '%s' on '%s' to PCC with archive ID '%u': %s\n",
12882                                 argv[0], fidstr, mntpath, archive_id,
12883                                 strerror(rc2));
12884                 }
12885                 if (rc == 0 && rc2 < 0)
12886                         rc = rc2;
12887         }
12888         return rc;
12889 }
12890
12891 static int lfs_pcc_detach(int argc, char **argv)
12892 {
12893         struct option long_opts[] = {
12894         { .val = 'h',   .name = "help", .has_arg = no_argument },
12895         { .val = 'k',   .name = "keep", .has_arg = no_argument },
12896         { .name = NULL } };
12897         int c;
12898         int rc = 0;
12899         const char *path;
12900         char fullpath[PATH_MAX];
12901         __u32 detach_opt = PCC_DETACH_OPT_UNCACHE;
12902
12903         optind = 0;
12904         while ((c = getopt_long(argc, argv, "hk",
12905                                 long_opts, NULL)) != -1) {
12906                 switch (c) {
12907                 case 'k':
12908                         detach_opt = PCC_DETACH_OPT_NONE;
12909                         break;
12910                 default:
12911                         fprintf(stderr, "%s: unrecognized option '%s'\n",
12912                                 progname, argv[optind - 1]);
12913                         fallthrough;
12914                 case 'h':
12915                         return CMD_HELP;
12916                 }
12917         }
12918
12919         while (optind < argc) {
12920                 int rc2;
12921
12922                 path = argv[optind++];
12923                 if (!realpath(path, fullpath)) {
12924                         fprintf(stderr, "%s: could not find path '%s': %s\n",
12925                                 argv[0], path, strerror(errno));
12926                         if (rc == 0)
12927                                 rc = -EINVAL;
12928                         continue;
12929                 }
12930
12931                 rc2 = llapi_pcc_detach_file(fullpath, detach_opt);
12932                 if (rc2 < 0) {
12933                         rc2 = -errno;
12934                         fprintf(stderr,
12935                                 "%s: cannot detach '%s' from PCC: %s\n",
12936                                 argv[0], path, strerror(errno));
12937                         if (rc == 0)
12938                                 rc = rc2;
12939                 }
12940         }
12941         return rc;
12942 }
12943
12944 static int lfs_pcc_detach_fid(int argc, char **argv)
12945 {
12946         struct option long_opts[] = {
12947         { .val = 'h',   .name = "help", .has_arg = no_argument },
12948         { .val = 'k',   .name = "keep", .has_arg = no_argument },
12949         { .name = NULL } };
12950         int c;
12951         int rc = 0;
12952         const char *fid;
12953         const char *mntpath;
12954         __u32 detach_opt = PCC_DETACH_OPT_UNCACHE;
12955
12956         optind = 0;
12957         while ((c = getopt_long(argc, argv, "hk",
12958                                 long_opts, NULL)) != -1) {
12959                 switch (c) {
12960                 case 'k':
12961                         detach_opt = PCC_DETACH_OPT_NONE;
12962                         break;
12963                 default:
12964                         fprintf(stderr, "%s: unrecognized option '%s'\n",
12965                                 progname, argv[optind - 1]);
12966                         fallthrough;
12967                 case 'h':
12968                         return CMD_HELP;
12969                 }
12970         }
12971
12972         mntpath = argv[optind++];
12973
12974         while (optind < argc) {
12975                 int rc2;
12976
12977                 fid = argv[optind++];
12978
12979                 rc2 = llapi_pcc_detach_fid_str(mntpath, fid, detach_opt);
12980                 if (rc2 < 0) {
12981                         fprintf(stderr,
12982                                 "%s: cannot detach '%s' on '%s' from PCC: %s\n",
12983                                 argv[0], fid, mntpath, strerror(-rc2));
12984                         if (rc == 0)
12985                                 rc = rc2;
12986                 }
12987         }
12988         return rc;
12989 }
12990
12991 static int lfs_pcc_state(int argc, char **argv)
12992 {
12993         int rc = 0;
12994         const char *path;
12995         char fullpath[PATH_MAX];
12996         struct lu_pcc_state state;
12997
12998         optind = 1;
12999
13000         if (argc <= 1) {
13001                 fprintf(stderr, "%s: must specify one or more file names\n",
13002                         progname);
13003                 return CMD_HELP;
13004         }
13005
13006         while (optind < argc) {
13007                 int rc2;
13008
13009                 path = argv[optind++];
13010                 if (!realpath(path, fullpath)) {
13011                         fprintf(stderr, "%s: could not find path '%s': %s\n",
13012                                 argv[0], path, strerror(errno));
13013                         if (rc == 0)
13014                                 rc = -EINVAL;
13015                         continue;
13016                 }
13017
13018                 rc2 = llapi_pcc_state_get(fullpath, &state);
13019                 if (rc2 < 0) {
13020                         if (rc == 0)
13021                                 rc = rc2;
13022                         fprintf(stderr,
13023                                 "%s: cannot get PCC state of '%s': %s\n",
13024                                 argv[0], path, strerror(-rc2));
13025                         continue;
13026                 }
13027
13028                 printf("file: %s", path);
13029                 printf(", type: %s", pcc_type2string(state.pccs_type));
13030                 if (state.pccs_type == LU_PCC_NONE &&
13031                     state.pccs_open_count == 0) {
13032                         printf("\n");
13033                         continue;
13034                 }
13035
13036                 printf(", PCC file: %s", state.pccs_path);
13037                 printf(", user number: %u", state.pccs_open_count);
13038                 printf(", flags: %x", state.pccs_flags);
13039                 printf("\n");
13040         }
13041         return rc;
13042 }
13043
13044 /**
13045  * lfs_pcc_list_commands() - List lfs pcc commands.
13046  * @argc: The count of command line arguments.
13047  * @argv: Array of strings for command line arguments.
13048  *
13049  * This function lists lfs pcc commands defined in pcc_cmdlist[].
13050  *
13051  * Return: 0 on success.
13052  */
13053 static int lfs_pcc_list_commands(int argc, char **argv)
13054 {
13055         char buffer[81] = "";
13056
13057         Parser_list_commands(pcc_cmdlist, buffer, sizeof(buffer),
13058                              NULL, 0, 4);
13059
13060         return 0;
13061 }
13062
13063 /**
13064  * lfs_pcc() - Parse and execute lfs pcc commands.
13065  * @argc: The count of lfs pcc command line arguments.
13066  * @argv: Array of strings for lfs pcc command line arguments.
13067  *
13068  * This function parses lfs pcc commands and performs the
13069  * corresponding functions specified in pcc_cmdlist[].
13070  *
13071  * Return: 0 on success or an error code on failure.
13072  */
13073 static int lfs_pcc(int argc, char **argv)
13074 {
13075         char cmd[PATH_MAX];
13076         int rc = 0;
13077
13078         setlinebuf(stdout);
13079
13080         Parser_init("lfs-pcc > ", pcc_cmdlist);
13081
13082         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
13083         progname = cmd;
13084         program_invocation_short_name = cmd;
13085         if (argc > 1)
13086                 rc = Parser_execarg(argc - 1, argv + 1, pcc_cmdlist);
13087         else
13088                 rc = Parser_commands();
13089
13090         return rc < 0 ? -rc : rc;
13091 }
13092
13093 static int lfs_list_commands(int argc, char **argv)
13094 {
13095         char buffer[81] = ""; /* 80 printable chars + terminating NUL */
13096
13097         Parser_list_commands(cmdlist, buffer, sizeof(buffer), NULL, 0, 4);
13098
13099         return 0;
13100 }
13101
13102 int main(int argc, char **argv)
13103 {
13104         int rc;
13105
13106         /* Ensure that liblustreapi constructor has run */
13107         if (!llapi_liblustreapi_initialized())
13108                 fprintf(stderr, "liblustreapi was not properly initialized\n");
13109
13110         setlinebuf(stdout);
13111         opterr = 0;
13112
13113         Parser_init("lfs > ", cmdlist);
13114
13115         progname = program_invocation_short_name; /* Used in error messages */
13116         if (argc > 1) {
13117                 llapi_set_command_name(argv[1]);
13118                 rc = Parser_execarg(argc - 1, argv + 1, cmdlist);
13119                 llapi_clear_command_name();
13120         } else {
13121                 rc = Parser_commands();
13122         }
13123
13124         return rc < 0 ? -rc : rc;
13125 }
13126
13127 #ifdef _LUSTRE_IDL_H_
13128 /* Everything we need here should be included by lustreapi.h. */
13129 # error "lfs should not depend on lustre_idl.h"
13130 #endif /* _LUSTRE_IDL_H_ */