Whamcloud - gitweb
58890c86b2cc842c4b63d66d518f71829161280b
[fs/lustre-release.git] / lustre / utils / lfs.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2011, 2017, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  *
31  * lustre/utils/lfs.c
32  *
33  * Author: Peter J. Braam <braam@clusterfs.com>
34  * Author: Phil Schwan <phil@clusterfs.com>
35  * Author: Robert Read <rread@clusterfs.com>
36  */
37
38 /* for O_DIRECTORY */
39 #ifndef _GNU_SOURCE
40 #define _GNU_SOURCE
41 #endif
42
43 #include <stdlib.h>
44 #include <stdio.h>
45 #include <inttypes.h>
46 #include <getopt.h>
47 #include <string.h>
48 #include <mntent.h>
49 #include <unistd.h>
50 #include <errno.h>
51 #include <err.h>
52 #include <pwd.h>
53 #include <grp.h>
54 #include <sys/ioctl.h>
55 #include <sys/quota.h>
56 #include <sys/time.h>
57 #include <sys/types.h>
58 #include <sys/stat.h>
59 #include <sys/param.h>
60 #include <sys/xattr.h>
61 #include <fcntl.h>
62 #include <dirent.h>
63 #include <time.h>
64 #include <ctype.h>
65 #include <zlib.h>
66 #include <libgen.h>
67 #include <asm/byteorder.h>
68 #include "lfs_project.h"
69
70 #include <libcfs/util/string.h>
71 #include <libcfs/util/ioctl.h>
72 #include <libcfs/util/parser.h>
73 #include <libcfs/util/string.h>
74 #include <lustre/lustreapi.h>
75 #include <linux/lustre/lustre_ver.h>
76 #include <linux/lustre/lustre_param.h>
77 #include <linux/lnet/nidstr.h>
78 #include <lnetconfig/cyaml.h>
79 #include "lstddef.h"
80
81 /* all functions */
82 static int lfs_find(int argc, char **argv);
83 static int lfs_getstripe(int argc, char **argv);
84 static int lfs_getdirstripe(int argc, char **argv);
85 static int lfs_setdirstripe(int argc, char **argv);
86 static int lfs_rmentry(int argc, char **argv);
87 static int lfs_unlink_foreign(int argc, char **argv);
88 static int lfs_osts(int argc, char **argv);
89 static int lfs_mdts(int argc, char **argv);
90 static int lfs_df(int argc, char **argv);
91 static int lfs_getname(int argc, char **argv);
92 static int lfs_check(int argc, char **argv);
93 #ifdef HAVE_SYS_QUOTA_H
94 static int lfs_setquota(int argc, char **argv);
95 static int lfs_quota(int argc, char **argv);
96 static int lfs_project(int argc, char **argv);
97 #endif
98 static int lfs_flushctx(int argc, char **argv);
99 static int lfs_poollist(int argc, char **argv);
100 static int lfs_changelog(int argc, char **argv);
101 static int lfs_changelog_clear(int argc, char **argv);
102 static int lfs_fid2path(int argc, char **argv);
103 static int lfs_path2fid(int argc, char **argv);
104 static int lfs_rmfid(int argc, char **argv);
105 static int lfs_data_version(int argc, char **argv);
106 static int lfs_hsm_state(int argc, char **argv);
107 static int lfs_hsm_set(int argc, char **argv);
108 static int lfs_hsm_clear(int argc, char **argv);
109 static int lfs_hsm_action(int argc, char **argv);
110 static int lfs_hsm_archive(int argc, char **argv);
111 static int lfs_hsm_restore(int argc, char **argv);
112 static int lfs_hsm_release(int argc, char **argv);
113 static int lfs_hsm_remove(int argc, char **argv);
114 static int lfs_hsm_cancel(int argc, char **argv);
115 static int lfs_swap_layouts(int argc, char **argv);
116 static int lfs_mv(int argc, char **argv);
117 static int lfs_ladvise(int argc, char **argv);
118 static int lfs_getsom(int argc, char **argv);
119 static int lfs_heat_get(int argc, char **argv);
120 static int lfs_heat_set(int argc, char **argv);
121 static int lfs_mirror(int argc, char **argv);
122 static int lfs_mirror_list_commands(int argc, char **argv);
123 static int lfs_list_commands(int argc, char **argv);
124 static inline int lfs_mirror_resync(int argc, char **argv);
125 static inline int lfs_mirror_verify(int argc, char **argv);
126 static inline int lfs_mirror_read(int argc, char **argv);
127 static inline int lfs_mirror_write(int argc, char **argv);
128 static inline int lfs_mirror_copy(int argc, char **argv);
129 static int lfs_pcc_attach(int argc, char **argv);
130 static int lfs_pcc_attach_fid(int argc, char **argv);
131 static int lfs_pcc_detach(int argc, char **argv);
132 static int lfs_pcc_detach_fid(int argc, char **argv);
133 static int lfs_pcc_state(int argc, char **argv);
134 static int lfs_pcc(int argc, char **argv);
135 static int lfs_pcc_list_commands(int argc, char **argv);
136 static int lfs_migrate_to_dom(int fd, int fdv, char *name,
137                               __u64 migration_flags);
138
139 struct pool_to_id_cbdata {
140         const char *pool;
141         __u32 id;
142 };
143 static int find_comp_id_by_pool(struct llapi_layout *layout, void *cbdata);
144 static int find_mirror_id_by_pool(struct llapi_layout *layout, void *cbdata);
145
146 enum setstripe_origin {
147         SO_SETSTRIPE,
148         SO_MIGRATE,
149         SO_MIGRATE_MDT,
150         SO_MIRROR_CREATE,
151         SO_MIRROR_EXTEND,
152         SO_MIRROR_SPLIT,
153         SO_MIRROR_DELETE,
154 };
155
156 static int lfs_setstripe_internal(int argc, char **argv,
157                                   enum setstripe_origin opc);
158
159 static inline int lfs_setstripe(int argc, char **argv)
160 {
161         return lfs_setstripe_internal(argc, argv, SO_SETSTRIPE);
162 }
163
164 static inline int lfs_setstripe_migrate(int argc, char **argv)
165 {
166         return lfs_setstripe_internal(argc, argv, SO_MIGRATE);
167 }
168
169 static inline int lfs_mirror_create(int argc, char **argv)
170 {
171         return lfs_setstripe_internal(argc, argv, SO_MIRROR_CREATE);
172 }
173
174 static inline int lfs_mirror_extend(int argc, char **argv)
175 {
176         return lfs_setstripe_internal(argc, argv, SO_MIRROR_EXTEND);
177 }
178
179 static inline int lfs_mirror_split(int argc, char **argv)
180 {
181         return lfs_setstripe_internal(argc, argv, SO_MIRROR_SPLIT);
182 }
183
184 static inline int lfs_mirror_delete(int argc, char **argv)
185 {
186         return lfs_setstripe_internal(argc, argv, SO_MIRROR_DELETE);
187 }
188
189 /* Setstripe and migrate share mostly the same parameters */
190 #define SSM_CMD_COMMON(cmd) \
191         "usage: "cmd" [--component-end|-E COMP_END]\n"                  \
192         "                 [--copy=LUSTRE_SRC]\n"                        \
193         "                 [--extension-size|--ext-size|-z SIZE]\n"      \
194         "                 [--help|-h] [--layout|-L PATTERN]\n"          \
195         "                 [--layout|-L PATTERN]\n"                      \
196         "                 [--mirror-count|-N[MIRROR_COUNT]]\n"          \
197         "                 [--ost|-o OST_INDICES]\n"                     \
198         "                 [--overstripe-count|-C STRIPE_COUNT]\n"       \
199         "                 [--pool|-p POOL_NAME]\n"                      \
200         "                 [--stripe-count|-c STRIPE_COUNT]\n"           \
201         "                 [--stripe-index|-i START_OST_IDX]\n"          \
202         "                 [--stripe-size|-S STRIPE_SIZE]\n"             \
203         "                 [--yaml|-y YAML_TEMPLATE_FILE]\n"
204
205 #define MIRROR_EXTEND_USAGE                                             \
206         "                 {--mirror-count|-N[MIRROR_COUNT]}\n"          \
207         "                 [SETSTRIPE_OPTIONS|-f|--file VICTIM_FILE]\n"  \
208         "                 [--no-verify]\n"
209
210 #define SETSTRIPE_USAGE                                                 \
211         SSM_CMD_COMMON("setstripe")                                     \
212         MIRROR_EXTEND_USAGE                                             \
213         "                 DIRECTORY|FILENAME\n"
214
215 #define MIGRATE_USAGE                                                   \
216         SSM_CMD_COMMON("migrate  ")                                     \
217         "                 [--block|-b] [--non-block|-n]\n"              \
218         "                 [--non-direct|-D] [--verbose|-v]\n"           \
219         "                 FILENAME\n"
220
221 #define SETDIRSTRIPE_USAGE                                              \
222         "               [--mdt-count|-c stripe_count>\n"                \
223         "               [--help|-h] [--mdt-hash|-H mdt_hash]\n"         \
224         "               [--mdt-index|-i mdt_index[,mdt_index,...]\n"    \
225         "               [--default|-D] [--mode|-o mode]\n"              \
226         "               [--max-inherit|-X max_inherit]\n"               \
227         "               [--max-inherit-rr max_inherit_rr] <dir>\n"      \
228         "To create dir with a foreign (free format) layout :\n"         \
229         "setdirstripe|mkdir --foreign[=FOREIGN_TYPE] -x|-xattr STRING " \
230         "               [--mode|-o MODE] [--flags HEX] DIRECTORY\n"
231
232 /**
233  * command_t mirror_cmdlist - lfs mirror commands.
234  */
235 command_t mirror_cmdlist[] = {
236         { .pc_name = "create", .pc_func = lfs_mirror_create,
237           .pc_help = "Create a mirrored file.\n"
238                 "usage: lfs mirror create --mirror-count|-N[MIRROR_COUNT]\n"
239                 "           [SETSTRIPE_OPTIONS] ... FILENAME|DIRECTORY ...\n" },
240         { .pc_name = "delete", .pc_func = lfs_mirror_delete,
241           .pc_help = "Delete a mirror from a file.\n"
242         "usage: lfs mirror delete {--mirror-id <mirror_id> |\n"
243         "\t               --component-id|--comp-id|-I COMP_ID |\n"
244         "\t               -p <pool>} MIRRORED_FILE ...\n"
245         },
246         { .pc_name = "extend", .pc_func = lfs_mirror_extend,
247           .pc_help = "Extend a mirrored file.\n"
248                 "usage: lfs mirror extend "
249                 "{--mirror-count|-N[MIRROR_COUNT]} [--no-verify] "
250                 "[SETSTRIPE_OPTIONS|-f VICTIM_FILE] ... FILENAME ...\n" },
251         { .pc_name = "split", .pc_func = lfs_mirror_split,
252           .pc_help = "Split a mirrored file.\n"
253         "usage: lfs mirror split {--mirror-id MIRROR_ID |\n"
254         "\t             --component-id|-I COMP_ID|-p POOL} [--destroy|-d]\n"
255         "\t             [-f NEW_FILE] MIRRORED_FILE ...\n" },
256         { .pc_name = "read", .pc_func = lfs_mirror_read,
257           .pc_help = "Read the content of a specified mirror of a file.\n"
258                 "usage: lfs mirror read {--mirror-id|-N MIRROR_ID}\n"
259                 "\t\t[--outfile|-o <output_file>] <mirrored_file>\n" },
260         { .pc_name = "write", .pc_func = lfs_mirror_write,
261           .pc_help = "Write to a specified mirror of a file.\n"
262                 "usage: lfs mirror write {--mirror-id|-N MIRROR_ID}\n"
263                 "\t\t[--inputfile|-i <input_file>] <mirrored_file>\n" },
264         { .pc_name = "copy", .pc_func = lfs_mirror_copy,
265           .pc_help = "Copy a specified mirror to other mirror(s) of a file.\n"
266                 "usage: lfs mirror copy {--read-mirror|-i MIRROR_ID0}\n"
267                 "\t\t{--write-mirror|-o MIRROR_ID1[,...]} <mirrored_file>\n" },
268         { .pc_name = "resync", .pc_func = lfs_mirror_resync,
269           .pc_help = "Resynchronizes out-of-sync mirrored file(s).\n"
270                 "usage: lfs mirror resync [--only MIRROR_ID[,...]>]\n"
271                 "\t\t<mirrored_file> [<mirrored_file2>...]\n" },
272         { .pc_name = "verify", .pc_func = lfs_mirror_verify,
273           .pc_help = "Verify mirrored file(s).\n"
274                 "usage: lfs mirror verify [--only MIRROR_ID[,...]]\n"
275                 "\t\t[--verbose|-v] <mirrored_file> [<mirrored_file2> ...]\n" },
276         { .pc_name = "list-commands", .pc_func = lfs_mirror_list_commands,
277           .pc_help = "list commands supported by lfs mirror"},
278         { .pc_name = "help", .pc_func = Parser_help, .pc_help = "help" },
279         { .pc_name = "exit", .pc_func = Parser_quit, .pc_help = "quit" },
280         { .pc_name = "quit", .pc_func = Parser_quit, .pc_help = "quit" },
281         { .pc_help = NULL }
282 };
283
284 /**
285  * command_t pcc_cmdlist - lfs pcc commands.
286  */
287 command_t pcc_cmdlist[] = {
288         { .pc_name = "attach", .pc_func = lfs_pcc_attach,
289           .pc_help = "Attach given files to the Persistent Client Cache.\n"
290                 "usage: lfs pcc attach <--id|-i NUM> <file> ...\n"
291                 "\t-i: archive id for RW-PCC\n" },
292         { .pc_name = "attach_fid", .pc_func = lfs_pcc_attach_fid,
293           .pc_help = "Attach given files into PCC by FID(s).\n"
294                 "usage: lfs pcc attach_id {--id|-i NUM} {--mnt|-m MOUNTPOINT} FID ...\n"
295                 "\t-i: archive id for RW-PCC\n"
296                 "\t-m: Lustre mount point\n" },
297         { .pc_name = "state", .pc_func = lfs_pcc_state,
298           .pc_help = "Display the PCC state for given files.\n"
299                 "usage: lfs pcc state <file> ...\n" },
300         { .pc_name = "detach", .pc_func = lfs_pcc_detach,
301           .pc_help = "Detach given files from the Persistent Client Cache.\n"
302                 "usage: lfs pcc detach <file> ...\n" },
303         { .pc_name = "detach_fid", .pc_func = lfs_pcc_detach_fid,
304           .pc_help = "Detach given files from PCC by FID(s).\n"
305                 "usage: lfs pcc detach_fid <mntpath> <fid>...\n" },
306         { .pc_name = "list-commands", .pc_func = lfs_pcc_list_commands,
307           .pc_help = "list commands supported by lfs pcc"},
308         { .pc_name = "help", .pc_func = Parser_help, .pc_help = "help" },
309         { .pc_name = "exit", .pc_func = Parser_quit, .pc_help = "quit" },
310         { .pc_name = "quit", .pc_func = Parser_quit, .pc_help = "quit" },
311         { .pc_help = NULL }
312 };
313
314 /* all available commands */
315 command_t cmdlist[] = {
316         {"setstripe", lfs_setstripe, 0,
317          "To create a file with specified striping/composite layout, or\n"
318          "create/replace the default layout on an existing directory:\n"
319          SSM_CMD_COMMON("setstripe")
320          "                 [--mode MODE]\n"
321          "                 <directory|filename>\n"
322          " or\n"
323          "To add component(s) to an existing composite file:\n"
324          SSM_CMD_COMMON("setstripe --component-add")
325          "To totally delete the default striping from an existing directory:\n"
326          "usage: setstripe [--delete|-d] <directory>\n"
327          " or\n"
328          "To create a mirrored file or set s default mirror layout on a directory:\n"
329          "usage: setstripe {--mirror-count|-N}[MIRROR_COUNT] [SETSTRIPE_OPTIONS] <directory|filename>\n"
330          " or\n"
331          "To delete the last component(s) from an existing composite file\n"
332          "(note that this will also delete any data in those components):\n"
333          "usage: setstripe --component-del [--component-id|-I COMP_ID]\n"
334          "                               [--component-flags|-F COMP_FLAGS]\n"
335          "                               <filename>\n"
336          "\tCOMP_ID:     Unique component ID to delete\n"
337          "\tCOMP_FLAGS:  'init' indicating all instantiated components\n"
338          "\t             '^init' indicating all uninstantiated components\n"
339          "\t-I and -F cannot be specified at the same time\n"
340          " or\n"
341          "To set or clear flags on a specific component\n"
342          "(note that this command can only be applied to mirrored files:\n"
343          "usage: setstripe --comp-set {-I COMP_ID|--comp-flags=COMP_FLAGS}\n"
344          "                            <filename>\n"
345          " or\n"
346          "To create a file with a foreign (free format) layout:\n"
347          "usage: setstripe --foreign[=FOREIGN_TYPE]\n"
348          "                 --xattr|-x LAYOUT_STRING [--flags HEX]\n"
349          "                 [--mode MODE] <filename>\n"},
350         {"getstripe", lfs_getstripe, 0,
351          "To list the layout pattern for a given file or files in a\n"
352          "directory or recursively for all files in a directory tree.\n"
353          "usage: getstripe [--ost|-O UUID] [--quiet|-q] [--verbose|-v]\n"
354          "                 [--stripe-count|-c] [--stripe-index|-i] [--fid|-F]\n"
355          "                 [--pool|-p] [--stripe-size|-S] [--directory|-d]\n"
356          "                 [--mdt-index|-m] [--recursive|-r] [--raw|-R]\n"
357          "                 [--layout|-L] [--generation|-g] [--yaml|-y]\n"
358          "                 [--help|-h] [--component-id|-I[=COMP_ID]]\n"
359          "                 [--component-flags[=COMP_FLAGS]]\n"
360          "                 [--component-count]\n"
361          "                 [--extension-size|--ext-size|-z]\n"
362          "                 [--component-start[=[+-]COMP_START]]\n"
363          "                 [--component-end[=[+-]COMP_END]|-E[[+-]comp_end]]\n"
364          "                 [[!] --mirror-index=[+-]INDEX |\n"
365          "                 [!] --mirror-id=[+-]MIRROR_ID] [--mirror-count|-N]\n"
366          "                 <directory|filename> ..."},
367         {"setdirstripe", lfs_setdirstripe, 0,
368          "Create striped directory on specified MDT, same as mkdir.\n"
369          "May be restricted to root or group users, depending on settings.\n"
370          "usage: setdirstripe [OPTION] <directory>\n"
371          SETDIRSTRIPE_USAGE},
372         {"getdirstripe", lfs_getdirstripe, 0,
373          "To list the layout pattern info for a given directory\n"
374          "or recursively for all directories in a directory tree.\n"
375          "usage: getdirstripe [--mdt-count|-c] [--mdt-index|-m|-i]\n"
376          "                    [--help|-h] [--mdt-hash|-H] [--obd|-O UUID]\n"
377          "                    [--recursive|-r] [--yaml|-y]\n"
378          "                    [--verbose|-v] [--default|-D]\n"
379          "                    [--max-inherit|-X]\n"
380          "                    [--max-inherit-rr] <dir> ..."},
381         {"mkdir", lfs_setdirstripe, 0,
382          "Create striped directory on specified MDT, same as setdirstripe.\n"
383          "usage: mkdir [OPTION] <directory>\n"
384          SETDIRSTRIPE_USAGE},
385         {"rm_entry", lfs_rmentry, 0,
386          "To remove the name entry of the remote directory. Note: This\n"
387          "command will only delete the name entry, i.e. the remote directory\n"
388          "will become inaccessable after this command. This can only be done\n"
389          "by the administrator\n"
390          "usage: rm_entry <dir>\n"},
391         {"rmentry", lfs_rmentry, 0, "remove a dir entry, same as 'rm_entry'\n"},
392         {"unlink_foreign", lfs_unlink_foreign, 0,
393          "To remove the foreign file/dir.\n"
394          "Note: This is for files/dirs prevented to be removed using\n"
395          "unlink/rmdir, but works also for regular ones\n"
396          "usage: unlink_foreign <foreign_dir/file> [<foreign_dir/file> ...]\n"},
397         {"pool_list", lfs_poollist, 0,
398          "List pools or pool OSTs\n"
399          "usage: pool_list <fsname>[.<pool>] | <pathname>\n"},
400         {"find", lfs_find, 0,
401          "find files matching given attributes recursively in directory tree.\n"
402          "usage: find <directory|filename> ...\n"
403          "     [[!] --atime|-A [+-]N[smhdwy]] [[!] --btime|-B [+-]N[smhdwy]]\n"
404          "     [[!] --ctime|-C [+-]N[smhdwy]] [[!] --mtime|-M [+-]N[smhdwy]]\n"
405          "     [[!] --blocks|-b N] [[!] --component-count [+-]<comp_cnt>]\n"
406          "     [[!] --component-start [+-]N[kMGTPE]]\n"
407          "     [[!] --component-end|-E [+-]N[kMGTPE]]\n"
408          "     [[!] --component-flags {init,stale,prefer,offline,nosync,extension}]\n"
409          "     [[!] --extension-size|--ext-size|-z [+-]N[kMGT]]\n"
410          "     [[!] --foreign[=<foreign_type>]]\n"
411          "     [[!] --gid|-g|--group|-G <gid>|<gname>] [--help|-h]\n"
412          "     [[!] --layout|-L released,raid0,mdt] [--lazy]\n"
413          "     [--maxdepth|-D N] [[!] --mdt-count|-T [+-]<stripes>]\n"
414          "     [[!] --mdt-hash|-H <[^][blm],[^]fnv_1a_64,all_char,crush,...>\n"
415          "     [[!] --mdt-index|--mdt|-m <uuid|index,...>]\n"
416          "     [[!] --mirror-count|-N [+-]<n>]\n"
417          "     [[!] --mirror-state <[^]state>]\n"
418          "     [[!] --name|-n <pattern>] [[!] --newer[XY] <reference>]\n"
419          "     [[!] --ost|-O <uuid|index,...>] [[!] --perm [/-]mode]\n"
420          "     [[!] --pool <pool>] [--print|-P] [--print0|-0] [--printf <format>]\n"
421          "     [[!] --projid <projid>] [[!] --size|-s [+-]N[bkMGTPE]]\n"
422          "     [[!] --stripe-count|-c [+-]<stripes>]\n"
423          "     [[!] --stripe-index|-i <index,...>]\n"
424          "     [[!] --stripe-size|-S [+-]N[kMGT]] [[!] --type|-t <filetype>]\n"
425          "     [[!] --uid|-u|--user|-U <uid>|<uname>]\n"
426          "\t !: used before an option indicates 'NOT' requested attribute\n"
427          "\t -: used before a value indicates less than requested value\n"
428          "\t +: used before a value indicates more than requested value\n"
429          "\t ^: used before a flag indicates to exclude it\n"},
430         {"check", lfs_check, 0,
431          "Display the status of MGTs, MDTs or OSTs (as specified in the command)\n"
432          "or all the servers (MGTs, MDTs and OSTs) [for specified path only].\n"
433          "usage: check {mgts|osts|mdts|all} [path]"},
434         {"osts", lfs_osts, 0, "list OSTs connected to client "
435          "[for specified path only]\n" "usage: osts [path]"},
436         {"mdts", lfs_mdts, 0, "list MDTs connected to client "
437          "[for specified path only]\n" "usage: mdts [path]"},
438         {"df", lfs_df, 0,
439          "report filesystem disk space usage or inodes usage "
440          "of each MDS and all OSDs or a batch belonging to a specific pool.\n"
441          "Usage: df [--inodes|-i] [--human-readable|-h] [--lazy|-l]\n"
442          "          [--pool|-p <fsname>[.<pool>]] [path]"},
443         {"getname", lfs_getname, 0,
444          "list instances and specified mount points [for specified path only]\n"
445          "Usage: getname [--help|-h] [--instance|-i] [--fsname|-n] [path ...]"},
446 #ifdef HAVE_SYS_QUOTA_H
447         {"setquota", lfs_setquota, 0, "Set filesystem quotas.\n"
448          "usage: setquota [-t][-D] {-u|-U|-g|-G|-p|-P} {-b|-B|-i|-I LIMIT} [--pool POOL] FILESYSTEM\n"
449          "       setquota {-u|-g|-p} --delete FILESYSTEM\n"},
450         {"quota", lfs_quota, 0, "Display disk usage and limits.\n"
451          "usage: quota [-q] [-v] [-h] [-o OBD_UUID|-i MDT_IDX|-I OST_IDX]\n"
452          "             [{-u|-g|-p} UNAME|UID|GNAME|GID|PROJID]\n"
453          "             [--pool <OST pool name>] <filesystem>\n"
454          "       quota -t <-u|-g|-p> [--pool <OST pool name>] <filesystem>\n"
455          "       quota [-q] [-v] [h] {-U|-G|-P} [--pool <OST pool name>] <filesystem>"},
456         {"project", lfs_project, 0,
457          "Change or list project attribute for specified file or directory.\n"
458          "usage: project [-d|-r] <file|directory...>\n"
459          "         list project ID and flags on file(s) or directories\n"
460          "       project [-p id] [-s] [-r] <file|directory...>\n"
461          "         set project ID and/or inherit flag for specified file(s) or directories\n"
462          "       project -c [-d|-r [-p id] [-0]] <file|directory...>\n"
463          "         check project ID and flags on file(s) or directories, print outliers\n"
464          "       project -C [-d|-r] [-k] <file|directory...>\n"
465          "         clear the project inherit flag and ID on the file or directory\n"
466         },
467 #endif
468         {"flushctx", lfs_flushctx, 0,
469          "Flush security context for current user.\n"
470          "usage: flushctx [-k] [-r] [mountpoint...]"},
471         {"changelog", lfs_changelog, 0,
472          "Show the metadata changes on an MDT."
473          "\nusage: changelog <mdtname> [startrec [endrec]]"},
474         {"changelog_clear", lfs_changelog_clear, 0,
475          "Indicate that old changelog records up to <endrec> are no longer of "
476          "interest to consumer <id>, allowing the system to free up space.\n"
477          "An <endrec> of 0 means all records.\n"
478          "usage: changelog_clear <mdtname> <id> <endrec>"},
479         {"fid2path", lfs_fid2path, 0,
480          "Resolve the full path(s) for given FID(s). For a specific hardlink "
481          "specify link number <linkno>.\n"
482          "usage: fid2path [--print-fid|-f] [--print-link|-c] [--link|-l <linkno>] "
483          "<fsname|root> <fid>..."},
484         {"path2fid", lfs_path2fid, 0, "Display the fid(s) for a given path(s).\n"
485          "usage: path2fid [--parents] <path> ..."},
486         {"rmfid", lfs_rmfid, 0, "Remove file(s) by FID(s)\n"
487          "usage: rmfid <fsname|rootpath> <fid> ..."},
488         {"data_version", lfs_data_version, 0, "Display file data version for "
489          "a given path.\n" "usage: data_version [-n|-r|-w] <path>"},
490         {"hsm_state", lfs_hsm_state, 0, "Display the HSM information (states, "
491          "undergoing actions) for given files.\n usage: hsm_state <file> ..."},
492         {"hsm_set", lfs_hsm_set, 0, "Set HSM user flag on specified files.\n"
493          "usage: hsm_set [--norelease] [--noarchive] [--dirty] [--exists] "
494          "[--archived] [--lost] [--archive-id NUM] <file> ..."},
495         {"hsm_clear", lfs_hsm_clear, 0, "Clear HSM user flag on specified "
496          "files.\n"
497          "usage: hsm_clear [--norelease] [--noarchive] [--dirty] [--exists] "
498          "[--archived] [--lost] <file> ..."},
499         {"hsm_action", lfs_hsm_action, 0, "Display current HSM request for "
500          "given files.\n" "usage: hsm_action <file> ..."},
501         {"hsm_archive", lfs_hsm_archive, 0,
502          "Archive file to external storage.\n"
503          "usage: hsm_archive [--filelist FILELIST] [--data DATA] [--archive NUM] "
504          "<file> ..."},
505         {"hsm_restore", lfs_hsm_restore, 0,
506          "Restore file from external storage.\n"
507          "usage: hsm_restore [--filelist FILELIST] [--data DATA] <file> ..."},
508         {"hsm_release", lfs_hsm_release, 0,
509          "Release files from Lustre.\n"
510          "usage: hsm_release [--filelist FILELIST] [--data DATA] <file> ..."},
511         {"hsm_remove", lfs_hsm_remove, 0,
512          "Remove file copy from external storage.\n"
513          "usage: hsm_remove [--filelist FILELIST] [--data DATA] "
514          "[--archive NUM]\n"
515          "                  (FILE [FILE ...] | "
516          "--mntpath MOUNTPATH FID [FID ...])\n"
517          "\n"
518          "Note: To remove an archived copy of a file already deleted from a "
519          "Lustre FS, the\n"
520          "--mntpath option and a list of FIDs must be specified"
521         },
522         {"hsm_cancel", lfs_hsm_cancel, 0,
523          "Cancel requests related to specified files.\n"
524          "usage: hsm_cancel [--filelist FILELIST] [--data DATA] <file> ..."},
525         {"swap_layouts", lfs_swap_layouts, 0, "Swap layouts between 2 files.\n"
526          "usage: swap_layouts <path1> <path2>"},
527         {"migrate", lfs_setstripe_migrate, 0,
528          "migrate directories and their inodes between MDTs.\n"
529          "usage: migrate [--mdt-count|-c STRIPE_COUNT] [--directory|-d]\n"
530          "               [--mdt-hash|-H HASH_TYPE]\n"
531          "               [--mdt-index|-m START_MDT_INDEX] [--verbose|-v]\n"
532          "               DIRECTORY\n"
533          "\n"
534          "migrate file objects from one OST layout to another\n"
535          "(may be not safe with concurent writes).\n"
536          MIGRATE_USAGE },
537         {"mv", lfs_mv, 0,
538          "To move directories between MDTs. This command is deprecated, "
539          "use \"migrate\" instead.\n"
540          "usage: mv <directory|filename> [--mdt-index|-m MDT_INDEX] "
541          "[--verbose|-v]\n"},
542         {"ladvise", lfs_ladvise, 0,
543          "Provide servers with advice about access patterns for a file.\n"
544          "usage: ladvise [--advice|-a ADVICE] [--start|-s START[kMGT]]\n"
545          "               [--background|-b] [--unset|-u]\n\n"
546          "               {--end|-e END[kMGT]|--length|-l LENGTH[kMGT]}\n"
547          "               {[--mode|-m [READ,WRITE]}\n"
548          "               <file> ...\n"},
549         {"mirror", lfs_mirror, mirror_cmdlist,
550          "lfs commands used to manage files with mirrored components:\n"
551          "lfs mirror create - create a mirrored file or directory\n"
552          "lfs mirror extend - add mirror(s) to an existing file\n"
553          "lfs mirror split  - split a mirror from an existing mirrored file\n"
554          "lfs mirror resync - resynchronize out-of-sync mirrored file(s)\n"
555          "lfs mirror read   - read a mirror content of a mirrored file\n"
556          "lfs mirror write  - write to a mirror of a mirrored file\n"
557          "lfs mirror copy   - copy a mirror to other mirror(s) of a file\n"
558          "lfs mirror verify - verify mirrored file(s)\n"},
559         {"getsom", lfs_getsom, 0, "To list the SOM info for a given file.\n"
560          "usage: getsom [-s] [-b] [-f] <path>\n"
561          "\t-s: Only show the size value of the SOM data for a given file\n"
562          "\t-b: Only show the blocks value of the SOM data for a given file\n"
563          "\t-f: Only show the flags value of the SOM data for a given file\n"},
564         {"heat_get", lfs_heat_get, 0,
565          "To get heat of files.\n"
566          "usage: heat_get <file> ...\n"},
567         {"heat_set", lfs_heat_set, 0,
568          "To set heat flags of files.\n"
569          "usage: heat_set [--clear|-c] [--off|-o] [--on|-O] <file> ...\n"
570          "\t--clear|-c: Clear file heat for given files\n"
571          "\t--off|-o:   Turn off file heat for given files\n"
572          "\t--on|-O:    Turn on file heat for given files\n"},
573         {"pcc", lfs_pcc, pcc_cmdlist,
574          "lfs commands used to interact with PCC features:\n"
575          "lfs pcc attach - attach given files to Persistent Client Cache\n"
576          "lfs pcc attach_fid - attach given files into PCC by FID(s)\n"
577          "lfs pcc state  - display the PCC state for given files\n"
578          "lfs pcc detach - detach given files from Persistent Client Cache\n"
579          "lfs pcc detach_fid - detach given files from PCC by FID(s)\n"},
580         {"help", Parser_help, 0, "help"},
581         {"exit", Parser_quit, 0, "quit"},
582         {"quit", Parser_quit, 0, "quit"},
583         {"--version", Parser_version, 0,
584          "output build version of the utility and exit"},
585         {"--list-commands", lfs_list_commands, 0,
586          "list commands supported by the utility and exit"},
587         { 0, 0, 0, NULL }
588 };
589
590 static int check_hashtype(const char *hashtype)
591 {
592         int type_num = atoi(hashtype);
593         int i;
594
595         /* numeric hash type */
596         if (hashtype && lmv_is_known_hash_type(type_num))
597                 return type_num;
598         /* string hash type */
599         for (i = LMV_HASH_TYPE_ALL_CHARS; i < ARRAY_SIZE(mdt_hash_name); i++)
600                 if (strcmp(hashtype, mdt_hash_name[i]) == 0)
601                         return i;
602
603         return 0;
604 }
605
606 static uint32_t check_foreign_type_name(const char *foreign_type_name)
607 {
608         uint32_t i;
609
610         for (i = 0; i < LU_FOREIGN_TYPE_UNKNOWN; i++) {
611                 if (!lu_foreign_types[i].lft_name)
612                         break;
613                 if (strcmp(foreign_type_name,
614                            lu_foreign_types[i].lft_name) == 0)
615                         return lu_foreign_types[i].lft_type;
616         }
617
618         return LU_FOREIGN_TYPE_UNKNOWN;
619 }
620
621 static const char *error_loc = "syserror";
622
623 static int
624 migrate_open_files(const char *name, __u64 migration_flags,
625                    const struct llapi_stripe_param *param,
626                    struct llapi_layout *layout, int *fd_src, int *fd_tgt)
627 {
628         int                      fd = -1;
629         int                      fdv = -1;
630         int                      rflags;
631         int                      mdt_index;
632         int                      random_value;
633         char                     parent[PATH_MAX];
634         char                     volatile_file[PATH_MAX];
635         char                    *ptr;
636         int                      rc;
637         struct stat              st;
638         struct stat              stv;
639
640         if (!param && !layout) {
641                 error_loc = "layout information";
642                 return -EINVAL;
643         }
644
645         /* search for file directory pathname */
646         if (strlen(name) > sizeof(parent) - 1) {
647                 error_loc = "source file name";
648                 return -ERANGE;
649         }
650
651         strncpy(parent, name, sizeof(parent));
652         ptr = strrchr(parent, '/');
653         if (!ptr) {
654                 if (!getcwd(parent, sizeof(parent))) {
655                         error_loc = "getcwd";
656                         return -errno;
657                 }
658         } else {
659                 if (ptr == parent) /* leading '/' */
660                         ptr = parent + 1;
661                 *ptr = '\0';
662         }
663
664         /* even if the file is only read, WR mode is nedeed to allow
665          * layout swap on fd
666          */
667         /* Allow migrating even without the key on encrypted files */
668         rflags = O_RDWR | O_NOATIME | O_FILE_ENC;
669         if (!(migration_flags & LLAPI_MIGRATION_NONDIRECT))
670                 rflags |= O_DIRECT;
671 source_open:
672         fd = open(name, rflags);
673         if (fd < 0) {
674                 /* If encrypted file without the key,
675                  * retry mirror extend in O_DIRECT.
676                  */
677                 if (errno == ENOKEY && !(rflags & O_DIRECT) &&
678                     migration_flags & LLAPI_MIGRATION_MIRROR) {
679                         rflags |= O_DIRECT;
680                         goto source_open;
681                 }
682                 rc = -errno;
683                 error_loc = "cannot open source file";
684                 return rc;
685         }
686
687         rc = llapi_file_fget_mdtidx(fd, &mdt_index);
688         if (rc < 0) {
689                 error_loc = "cannot get MDT index";
690                 goto out;
691         }
692
693         do {
694                 int open_flags = O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW |
695                         /* Allow migrating without the key on encrypted files */
696                         O_FILE_ENC;
697                 mode_t open_mode = S_IRUSR | S_IWUSR;
698
699                 if (rflags & O_DIRECT)
700                         open_flags |= O_DIRECT;
701                 random_value = random();
702                 rc = snprintf(volatile_file, sizeof(volatile_file),
703                               "%s/%s:%.4X:%.4X:fd=%.2d", parent,
704                               LUSTRE_VOLATILE_HDR, mdt_index,
705                               random_value, fd);
706                 if (rc >= sizeof(volatile_file)) {
707                         rc = -ENAMETOOLONG;
708                         break;
709                 }
710
711                 /* create, open a volatile file, use caching (ie no directio) */
712                 if (layout) {
713                         /* Returns -1 and sets errno on error: */
714                         fdv = llapi_layout_file_open(volatile_file, open_flags,
715                                                      open_mode, layout);
716                         if (fdv < 0)
717                                 fdv = -errno;
718                 } else {
719                         /* Does the right thing on error: */
720                         fdv = llapi_file_open_param(volatile_file, open_flags,
721                                                     open_mode, param);
722                 }
723         } while (fdv < 0 && (rc = fdv) == -EEXIST);
724
725         if (rc < 0) {
726                 error_loc = "cannot create volatile file";
727                 goto out;
728         }
729
730         /*
731          * In case the MDT does not support creation of volatile files
732          * we should try to unlink it.
733          */
734         (void)unlink(volatile_file);
735
736         /*
737          * Not-owner (root?) special case.
738          * Need to set owner/group of volatile file like original.
739          * This will allow to pass related check during layout_swap.
740          */
741         rc = fstat(fd, &st);
742         if (rc != 0) {
743                 rc = -errno;
744                 error_loc = "cannot stat source file";
745                 goto out;
746         }
747
748         rc = fstat(fdv, &stv);
749         if (rc != 0) {
750                 rc = -errno;
751                 error_loc = "cannot stat volatile";
752                 goto out;
753         }
754
755         if (st.st_uid != stv.st_uid || st.st_gid != stv.st_gid) {
756                 rc = fchown(fdv, st.st_uid, st.st_gid);
757                 if (rc != 0) {
758                         rc = -errno;
759                         error_loc = "cannot change ownwership of volatile";
760                         goto out;
761                 }
762         }
763
764 out:
765         if (rc < 0) {
766                 if (fd > 0)
767                         close(fd);
768                 if (fdv > 0)
769                         close(fdv);
770         } else {
771                 *fd_src = fd;
772                 *fd_tgt = fdv;
773                 error_loc = NULL;
774         }
775         return rc;
776 }
777
778 static int migrate_copy_data(int fd_src, int fd_dst, int (*check_file)(int))
779 {
780         struct llapi_layout *layout;
781         size_t buf_size = 4 * 1024 * 1024;
782         void *buf = NULL;
783         off_t pos = 0;
784         off_t data_end = 0;
785         size_t page_size = sysconf(_SC_PAGESIZE);
786         bool sparse;
787         int rc;
788
789         layout = llapi_layout_get_by_fd(fd_src, 0);
790         if (layout) {
791                 uint64_t stripe_size;
792
793                 rc = llapi_layout_stripe_size_get(layout, &stripe_size);
794                 if (rc == 0)
795                         buf_size = stripe_size;
796
797                 llapi_layout_free(layout);
798         }
799
800         /* Use a page-aligned buffer for direct I/O */
801         rc = posix_memalign(&buf, page_size, buf_size);
802         if (rc != 0)
803                 return -rc;
804
805         sparse = llapi_file_is_sparse(fd_src);
806         if (sparse) {
807                 rc = ftruncate(fd_dst, pos);
808                 if (rc < 0) {
809                         rc = -errno;
810                         return rc;
811                 }
812         }
813
814         while (1) {
815                 off_t data_off;
816                 size_t to_read, to_write;
817                 ssize_t rsize;
818
819                 if (sparse && pos >= data_end) {
820                         size_t data_size;
821
822                         data_off = llapi_data_seek(fd_src, pos, &data_size);
823                         if (data_off < 0) {
824                                 /* Non-fatal, switch to full copy */
825                                 sparse = false;
826                                 continue;
827                         }
828                         /* hole at the end of file, truncate up to it */
829                         if (!data_size) {
830                                 rc = ftruncate(fd_dst, data_off);
831                                 if (rc < 0)
832                                         goto out;
833                         }
834                         pos = data_off & ~(page_size - 1);
835                         data_end = data_off + data_size;
836                         to_read = ((data_end - pos - 1) | (page_size - 1)) + 1;
837                         to_read = MIN(to_read, buf_size);
838                 } else {
839                         to_read = buf_size;
840                 }
841
842                 if (check_file) {
843                         rc = check_file(fd_src);
844                         if (rc < 0)
845                                 goto out;
846                 }
847
848                 rsize = pread(fd_src, buf, to_read, pos);
849                 if (rsize < 0) {
850                         rc = -errno;
851                         goto out;
852                 }
853                 /* EOF */
854                 if (rsize == 0)
855                         break;
856
857                 to_write = rsize;
858                 while (to_write > 0) {
859                         ssize_t written;
860
861                         written = pwrite(fd_dst, buf, to_write, pos);
862                         if (written < 0) {
863                                 rc = -errno;
864                                 goto out;
865                         }
866                         pos += written;
867                         to_write -= written;
868                 }
869                 if (rc || rsize < to_read)
870                         break;
871         }
872
873         rc = fsync(fd_dst);
874         if (rc < 0)
875                 rc = -errno;
876 out:
877         /* Try to avoid page cache pollution after migration. */
878         (void)posix_fadvise(fd_src, 0, 0, POSIX_FADV_DONTNEED);
879         (void)posix_fadvise(fd_dst, 0, 0, POSIX_FADV_DONTNEED);
880
881         free(buf);
882         return rc;
883 }
884
885 static int migrate_set_timestamps(int fd, const struct stat *st)
886 {
887         struct timeval tv[2] = {
888                 {.tv_sec = st->st_atime},
889                 {.tv_sec = st->st_mtime}
890         };
891
892         return futimes(fd, tv);
893 }
894
895 static int migrate_block(int fd, int fdv)
896 {
897         struct stat st;
898         __u64   dv1;
899         int     gid;
900         int     rc;
901         int     rc2;
902
903         rc = fstat(fd, &st);
904         if (rc < 0) {
905                 error_loc = "cannot stat source file";
906                 return -errno;
907         }
908
909         rc = llapi_get_data_version(fd, &dv1, LL_DV_RD_FLUSH);
910         if (rc < 0) {
911                 error_loc = "cannot get dataversion";
912                 return rc;
913         }
914
915         do
916                 gid = random();
917         while (gid == 0);
918
919         /*
920          * The grouplock blocks all concurrent accesses to the file.
921          * It has to be taken after llapi_get_data_version as it would
922          * block it too.
923          */
924         rc = llapi_group_lock(fd, gid);
925         if (rc < 0) {
926                 error_loc = "cannot get group lock";
927                 return rc;
928         }
929
930         rc = migrate_copy_data(fd, fdv, NULL);
931         if (rc < 0) {
932                 error_loc = "data copy failed";
933                 goto out_unlock;
934         }
935
936         /* Make sure we keep original atime/mtime values */
937         rc = migrate_set_timestamps(fdv, &st);
938         if (rc < 0) {
939                 error_loc = "set target file timestamp failed";
940                 goto out_unlock;
941         }
942
943         /*
944          * swap layouts
945          * for a migration we need to check data version on file did
946          * not change.
947          *
948          * Pass in gid=0 since we already own grouplock.
949          */
950         rc = llapi_fswap_layouts_grouplock(fd, fdv, dv1, 0, 0,
951                                            SWAP_LAYOUTS_CHECK_DV1);
952         if (rc == -EAGAIN) {
953                 error_loc = "file changed";
954                 goto out_unlock;
955         } else if (rc < 0) {
956                 error_loc = "cannot swap layout";
957                 goto out_unlock;
958         }
959
960 out_unlock:
961         rc2 = llapi_group_unlock(fd, gid);
962         if (rc2 < 0 && rc == 0) {
963                 error_loc = "unlock group lock";
964                 rc = rc2;
965         }
966
967         return rc;
968 }
969
970 /**
971  * Internal helper for migrate_copy_data(). Check lease and report error if
972  * need be.
973  *
974  * \param[in]  fd           File descriptor on which to check the lease.
975  *
976  * \retval 0       Migration can keep on going.
977  * \retval -errno  Error occurred, abort migration.
978  */
979 static int check_lease(int fd)
980 {
981         int rc;
982
983         rc = llapi_lease_check(fd);
984         if (rc > 0)
985                 return 0; /* llapi_check_lease returns > 0 on success. */
986
987         return -EBUSY;
988 }
989
990 static int migrate_nonblock(int fd, int fdv)
991 {
992         struct stat st;
993         __u64   dv1;
994         __u64   dv2;
995         int     rc;
996
997         rc = fstat(fd, &st);
998         if (rc < 0) {
999                 error_loc = "cannot stat source file";
1000                 return -errno;
1001         }
1002
1003         rc = llapi_get_data_version(fd, &dv1, LL_DV_RD_FLUSH);
1004         if (rc < 0) {
1005                 error_loc = "cannot get data version";
1006                 return rc;
1007         }
1008
1009         rc = migrate_copy_data(fd, fdv, check_lease);
1010         if (rc < 0) {
1011                 error_loc = "data copy failed";
1012                 return rc;
1013         }
1014
1015         rc = llapi_get_data_version(fd, &dv2, LL_DV_RD_FLUSH);
1016         if (rc != 0) {
1017                 error_loc = "cannot get data version";
1018                 return rc;
1019         }
1020
1021         if (dv1 != dv2) {
1022                 rc = -EAGAIN;
1023                 error_loc = "source file changed";
1024                 return rc;
1025         }
1026
1027         /* Make sure we keep original atime/mtime values */
1028         rc = migrate_set_timestamps(fdv, &st);
1029         if (rc < 0) {
1030                 error_loc = "set target file timestamp failed";
1031                 return -errno;
1032         }
1033         return 0;
1034 }
1035
1036 static
1037 int lfs_layout_compid_by_pool(char *fname, const char *pool, int *comp_id)
1038 {
1039         struct pool_to_id_cbdata data = { .pool = pool };
1040         struct llapi_layout *layout = NULL;
1041         int rc;
1042
1043         layout = llapi_layout_get_by_path(fname, 0);
1044         if (!layout) {
1045                 fprintf(stderr,
1046                         "error %s: file '%s' couldn't get layout: rc=%d\n",
1047                         progname, fname, errno);
1048                 rc = -errno;
1049                 goto free_layout;
1050         }
1051         rc = llapi_layout_sanity(layout, false, true);
1052         if (rc < 0) {
1053                 llapi_layout_sanity_perror(errno);
1054                 goto free_layout;
1055         }
1056         rc = llapi_layout_comp_iterate(layout, find_comp_id_by_pool, &data);
1057         if (rc < 0)
1058                 goto free_layout;
1059
1060         *comp_id = data.id;
1061         rc = 0;
1062
1063 free_layout:
1064         if (layout)
1065                 llapi_layout_free(layout);
1066         return rc;
1067 }
1068
1069 static int lfs_component_set(char *fname, int comp_id, const char *pool,
1070                              __u32 flags, __u32 neg_flags)
1071 {
1072         __u32 ids[2];
1073         __u32 flags_array[2];
1074         size_t count = 0;
1075         int rc;
1076
1077         if (!comp_id) {
1078                 if (pool == NULL) {
1079                         fprintf(stderr,
1080                                 "error %s: neither component id nor pool is specified\n",
1081                                 progname);
1082                         return -EINVAL;
1083                 }
1084                 rc = lfs_layout_compid_by_pool(fname, pool, &comp_id);
1085                 if (rc)
1086                         return rc;
1087         }
1088
1089         if (flags) {
1090                 ids[count] = comp_id;
1091                 flags_array[count] = flags;
1092                 ++count;
1093         }
1094
1095         if (neg_flags) {
1096                 if (neg_flags & LCME_FL_STALE) {
1097                         fprintf(stderr,
1098                                 "%s: cannot clear 'stale' flags from component. Please use lfs-mirror-resync(1) instead\n",
1099                                 progname);
1100                         return -EINVAL;
1101                 }
1102
1103                 ids[count] = comp_id;
1104                 flags_array[count] = neg_flags | LCME_FL_NEG;
1105                 ++count;
1106         }
1107
1108         rc = llapi_layout_file_comp_set(fname, ids, flags_array, count);
1109         if (rc) {
1110                 if (errno == EUCLEAN) {
1111                         rc = -errno;
1112                         fprintf(stderr,
1113                                 "%s: cannot set 'stale' flag on component '%#x' of the last non-stale mirror of '%s'\n",
1114                                 progname, comp_id, fname);
1115                 } else {
1116                         fprintf(stderr,
1117                                 "%s: cannot change the flags of component '%#x' of file '%s': %x / ^(%x)\n",
1118                                 progname, comp_id, fname, flags, neg_flags);
1119                 }
1120         }
1121
1122         return rc;
1123 }
1124
1125 static int lfs_component_del(char *fname, __u32 comp_id,
1126                              __u32 flags, __u32 neg_flags)
1127 {
1128         int     rc = 0;
1129
1130         if (flags && neg_flags) {
1131                 fprintf(stderr,
1132                         "%s: cannot specify both positive and negative flags\n",
1133                         progname);
1134                 return -EINVAL;
1135         }
1136
1137         if (!flags && neg_flags)
1138                 flags = neg_flags | LCME_FL_NEG;
1139
1140         if (flags && comp_id) {
1141                 fprintf(stderr,
1142                         "%s: cannot specify component ID and flags at the same time\n",
1143                         progname);
1144                 return -EINVAL;
1145         }
1146
1147         if (!flags && !comp_id) {
1148                 fprintf(stderr,
1149                         "%s: neither flags nor component ID is specified\n",
1150                         progname);
1151                 return -EINVAL;
1152         }
1153
1154         if (flags) {
1155                 if (flags & ~LCME_KNOWN_FLAGS) {
1156                         fprintf(stderr,
1157                                 "%s setstripe: unknown flags %#x\n",
1158                                 progname, flags);
1159                         return -EINVAL;
1160                 }
1161         } else if (comp_id > LCME_ID_MAX) {
1162                 fprintf(stderr, "%s setstripe: invalid component id %u\n",
1163                         progname, comp_id);
1164                 return -EINVAL;
1165         }
1166
1167         rc = llapi_layout_file_comp_del(fname, comp_id, flags);
1168         if (rc)
1169                 fprintf(stderr,
1170                         "%s setstripe: cannot delete component %#x from '%s': %s\n",
1171                         progname, comp_id, fname, strerror(errno));
1172         return rc;
1173 }
1174
1175 static int lfs_component_add(char *fname, struct llapi_layout *layout)
1176 {
1177         int     rc;
1178
1179         if (!layout)
1180                 return -EINVAL;
1181
1182         rc = llapi_layout_file_comp_add(fname, layout);
1183         if (rc)
1184                 fprintf(stderr, "Add layout component(s) to %s failed. %s\n",
1185                         fname, strerror(errno));
1186         return rc;
1187 }
1188
1189 static int lfs_component_create(char *fname, int open_flags, mode_t open_mode,
1190                                 struct llapi_layout *layout)
1191 {
1192         struct stat     st;
1193         int     fd;
1194
1195         if (!layout)
1196                 return -EINVAL;
1197
1198         fd = lstat(fname, &st);
1199         if (fd == 0 && S_ISDIR(st.st_mode))
1200                 open_flags = O_DIRECTORY | O_RDONLY;
1201
1202         fd = llapi_layout_file_open(fname, open_flags, open_mode, layout);
1203         if (fd < 0)
1204                 fprintf(stderr, "%s: cannot %s '%s': %s\n", progname,
1205                         S_ISDIR(st.st_mode) ?
1206                                 "set default composite layout for" :
1207                                 "create composite file",
1208                         fname, strerror(errno));
1209         return fd;
1210 }
1211
1212 static int lfs_migrate(char *name, __u64 migration_flags,
1213                        struct llapi_stripe_param *param,
1214                        struct llapi_layout *layout)
1215 {
1216         struct llapi_layout *existing;
1217         uint64_t dom_new, dom_cur;
1218         int fd = -1;
1219         int fdv = -1;
1220         int rc;
1221
1222         rc = migrate_open_files(name, migration_flags, param, layout,
1223                                 &fd, &fdv);
1224         if (rc < 0)
1225                 goto out;
1226
1227         rc = llapi_layout_dom_size(layout, &dom_new);
1228         if (rc) {
1229                 error_loc = "cannot get new layout DoM size";
1230                 goto out;
1231         }
1232         /* special case for migration to DOM layout*/
1233         existing = llapi_layout_get_by_fd(fd, 0);
1234         if (!existing) {
1235                 error_loc = "cannot get existing layout";
1236                 goto out;
1237         }
1238
1239         rc = llapi_layout_dom_size(existing, &dom_cur);
1240         if (rc) {
1241                 error_loc = "cannot get current layout DoM size";
1242                 goto out;
1243         }
1244
1245         /*
1246          * if file has DoM layout already then migration is possible to
1247          * the new layout with the same DoM component via swap layout,
1248          * if new layout used bigger DOM size, then mirroring is used
1249          */
1250         if (dom_new > dom_cur) {
1251                 rc = lfs_migrate_to_dom(fd, fdv, name, migration_flags);
1252                 if (rc)
1253                         error_loc = "cannot migrate to DOM layout";
1254                 goto out_closed;
1255         }
1256
1257         if (!(migration_flags & LLAPI_MIGRATION_NONBLOCK)) {
1258                 /*
1259                  * Blocking mode (forced if servers do not support file lease).
1260                  * It is also the default mode, since we cannot distinguish
1261                  * between a broken lease and a server that does not support
1262                  * atomic swap/close (LU-6785)
1263                  */
1264                 rc = migrate_block(fd, fdv);
1265                 goto out;
1266         }
1267
1268         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
1269         if (rc < 0) {
1270                 error_loc = "cannot get lease";
1271                 goto out;
1272         }
1273
1274         rc = migrate_nonblock(fd, fdv);
1275         if (rc < 0) {
1276                 llapi_lease_release(fd);
1277                 goto out;
1278         }
1279
1280         /*
1281          * Atomically put lease, swap layouts and close.
1282          * for a migration we need to check data version on file did
1283          * not change.
1284          */
1285         rc = llapi_fswap_layouts(fd, fdv, 0, 0, SWAP_LAYOUTS_CLOSE);
1286         if (rc < 0) {
1287                 error_loc = "cannot swap layout";
1288                 goto out;
1289         }
1290
1291 out:
1292         if (fd >= 0)
1293                 close(fd);
1294
1295         if (fdv >= 0)
1296                 close(fdv);
1297 out_closed:
1298         if (rc < 0)
1299                 fprintf(stderr, "error: %s: %s: %s: %s\n",
1300                         progname, name, error_loc, strerror(-rc));
1301         else if (migration_flags & LLAPI_MIGRATION_VERBOSE)
1302                 printf("%s\n", name);
1303
1304         return rc;
1305 }
1306
1307 static int comp_str2flags(char *string, __u32 *flags, __u32 *neg_flags)
1308 {
1309         char *name;
1310         char *dup_string = NULL;
1311         int rc = 0;
1312
1313         *flags = 0;
1314         *neg_flags = 0;
1315
1316         if (!string || !string[0])
1317                 return -EINVAL;
1318
1319         dup_string = strdup(string);
1320         if (!dup_string) {
1321                 llapi_printf(LLAPI_MSG_ERROR,
1322                              "%s: insufficient memory\n",
1323                              progname);
1324                 return -ENOMEM;
1325         }
1326
1327         for (name = strtok(dup_string, ","); name; name = strtok(NULL, ",")) {
1328                 bool found = false;
1329                 int i;
1330
1331                 for (i = 0; i < ARRAY_SIZE(comp_flags_table); i++) {
1332                         __u32 comp_flag = comp_flags_table[i].cfn_flag;
1333                         const char *comp_name = comp_flags_table[i].cfn_name;
1334
1335                         if (strcmp(name, comp_name) == 0) {
1336                                 *flags |= comp_flag;
1337                                 found = true;
1338                         } else if (strncmp(name, "^", 1) == 0 &&
1339                                    strcmp(name + 1, comp_name) == 0) {
1340                                 *neg_flags |= comp_flag;
1341                                 found = true;
1342                         }
1343                 }
1344                 if (!found) {
1345                         llapi_printf(LLAPI_MSG_ERROR,
1346                                      "%s: component flag '%s' not supported\n",
1347                                      progname, name);
1348                         rc = -EINVAL;
1349                         goto out_free;
1350                 }
1351         }
1352
1353         if (!*flags && !*neg_flags)
1354                 rc = -EINVAL;
1355
1356         /* don't allow to set and exclude the same flag */
1357         if (*flags & *neg_flags)
1358                 rc = -EINVAL;
1359
1360 out_free:
1361         free(dup_string);
1362         return rc;
1363 }
1364
1365 static int mdthash_input(char *string, __u32 *inflags,
1366                          __u32 *exflags, __u32 *type)
1367 {
1368         char *name;
1369         struct mhf_list {
1370                 char *name;
1371                 __u32 flag;
1372         } mhflist[] = {
1373                 {"migrating", LMV_HASH_FLAG_MIGRATION},
1374                 {"bad_type", LMV_HASH_FLAG_BAD_TYPE},
1375                 {"badtype", LMV_HASH_FLAG_BAD_TYPE},
1376                 {"lost_lmv", LMV_HASH_FLAG_LOST_LMV},
1377                 {"lostlmv", LMV_HASH_FLAG_LOST_LMV},
1378         };
1379
1380         if (string == NULL)
1381                 return -EINVAL;
1382
1383         *inflags = 0;
1384         *exflags = 0;
1385         *type = 0;
1386         for (name = strtok(string, ","); name; name = strtok(NULL, ",")) {
1387                 bool found = false;
1388                 int i;
1389
1390                 for (i = 0; i < ARRAY_SIZE(mhflist); i++) {
1391                         if (strcmp(name, mhflist[i].name) == 0 ||
1392                             name[0] == mhflist[i].name[0]) {
1393                                 *inflags |= mhflist[i].flag;
1394                                 found = true;
1395                         } else if (name[0] == '^' &&
1396                                    (strcmp(name + 1, mhflist[i].name) == 0 ||
1397                                     name[1] == mhflist[i].name[0])) {
1398                                 *exflags |= mhflist[i].flag;
1399                                 found = true;
1400                         }
1401                 }
1402                 if (!found) {
1403                         i = check_hashtype(name);
1404                         if (i > 0) {
1405                                 *type |= 1 << i;
1406                                 continue;
1407                         }
1408                         llapi_printf(LLAPI_MSG_ERROR,
1409                                      "%s: invalid mdt_hash value '%s'\n",
1410                                      progname, name);
1411                         return -EINVAL;
1412                 }
1413         }
1414
1415         /* don't allow to include and exclude the same flag */
1416         if (*inflags & *exflags) {
1417                 llapi_printf(LLAPI_MSG_ERROR,
1418                              "%s: include and exclude same flag '%s'\n",
1419                              progname, string);
1420                 return -EINVAL;
1421         }
1422
1423         return 0;
1424 }
1425
1426 static int mirror_str2state(char *string, __u16 *state, __u16 *neg_state)
1427 {
1428         if (!string)
1429                 return -EINVAL;
1430
1431         *state = 0;
1432         *neg_state = 0;
1433
1434         if (strncmp(string, "^", 1) == 0) {
1435                 *neg_state = llapi_layout_string_flags(string + 1);
1436                 if (*neg_state != 0)
1437                         return 0;
1438         } else {
1439                 *state = llapi_layout_string_flags(string);
1440                 if (*state != 0)
1441                         return 0;
1442         }
1443
1444         llapi_printf(LLAPI_MSG_ERROR,
1445                      "%s: mirrored file state '%s' not supported\n",
1446                      progname, string);
1447         return -EINVAL;
1448 }
1449
1450 /**
1451  * struct mirror_args - Command-line arguments for mirror(s).
1452  * @m_count:  Number of mirrors to be created with this layout.
1453  * @m_flags:  Mirror level flags, only 'prefer' is supported.
1454  * @m_layout: Mirror layout.
1455  * @m_file:   A victim file. Its layout will be split and used as a mirror.
1456  * @m_next:   Point to the next node of the list.
1457  *
1458  * Command-line arguments for mirror(s) will be parsed and stored in
1459  * a linked list that consists of this structure.
1460  */
1461 struct mirror_args {
1462         __u32                   m_count;
1463         __u32                   m_flags;
1464         struct llapi_layout     *m_layout;
1465         const char              *m_file;
1466         struct mirror_args      *m_next;
1467         bool                    m_inherit;
1468 };
1469
1470 /**
1471  * enum mirror_flags - Flags for extending a mirrored file.
1472  * @MF_NO_VERIFY: Indicates not to verify the mirror(s) from victim file(s)
1473  *             in case the victim file(s) contains the same data as the
1474  *             original mirrored file.
1475  * @MF_DESTROY: Indicates to delete the mirror from the mirrored file.
1476  * @MF_COMP_ID: specified component id instead of mirror id
1477  *
1478  * Flags for extending a mirrored file.
1479  */
1480 enum mirror_flags {
1481         MF_NO_VERIFY    = 0x1,
1482         MF_DESTROY      = 0x2,
1483         MF_COMP_ID      = 0x4,
1484         MF_COMP_POOL    = 0x8,
1485 };
1486
1487 /**
1488  * mirror_create_sanity_check() - Check mirror list.
1489  * @list:  A linked list that stores the mirror arguments.
1490  *
1491  * This function does a sanity check on @list for creating
1492  * a mirrored file.
1493  *
1494  * Return: 0 on success or a negative error code on failure.
1495  */
1496 static int mirror_create_sanity_check(const char *fname,
1497                                       struct mirror_args *list,
1498                                       bool check_fname)
1499 {
1500         int rc = 0;
1501         bool has_m_file = false;
1502         bool has_m_layout = false;
1503
1504         if (!list)
1505                 return -EINVAL;
1506
1507         if (fname && check_fname) {
1508                 struct llapi_layout *layout;
1509
1510                 layout = llapi_layout_get_by_path(fname, 0);
1511                 if (!layout) {
1512                         fprintf(stderr,
1513                                 "error: %s: file '%s' couldn't get layout\n",
1514                                 progname, fname);
1515                         return -ENODATA;
1516                 }
1517
1518                 rc = llapi_layout_sanity(layout, false, true);
1519
1520                 llapi_layout_free(layout);
1521
1522                 if (rc) {
1523                         llapi_layout_sanity_perror(rc);
1524                         return rc;
1525                 }
1526         }
1527
1528         while (list) {
1529                 if (list->m_file) {
1530                         has_m_file = true;
1531                         llapi_layout_free(list->m_layout);
1532
1533                         list->m_layout =
1534                                 llapi_layout_get_by_path(list->m_file, 0);
1535                         if (!list->m_layout) {
1536                                 fprintf(stderr,
1537                                         "error: %s: file '%s' has no layout\n",
1538                                         progname, list->m_file);
1539                                 return -ENODATA;
1540                         }
1541                 } else {
1542                         has_m_layout = true;
1543                         if (!list->m_layout) {
1544                                 fprintf(stderr, "error: %s: no mirror layout\n",
1545                                         progname);
1546                                 return -EINVAL;
1547                         }
1548                 }
1549
1550                 rc = llapi_layout_sanity(list->m_layout, false, true);
1551                 if (rc) {
1552                         llapi_layout_sanity_perror(rc);
1553                         return rc;
1554                 }
1555
1556                 list = list->m_next;
1557         }
1558
1559         if (has_m_file && has_m_layout) {
1560                 fprintf(stderr,
1561                         "error: %s: -f <victim_file> option should not be specified with setstripe options\n",
1562                         progname);
1563                 return -EINVAL;
1564         }
1565
1566         return 0;
1567 }
1568
1569 static int mirror_set_flags(struct llapi_layout *layout, void *cbdata)
1570 {
1571         __u32 mirror_flags = *(__u32 *)cbdata;
1572         uint32_t flags;
1573         int rc;
1574
1575         rc = llapi_layout_comp_flags_get(layout, &flags);
1576         if (rc < 0)
1577                 return rc;
1578
1579         if (!flags) {
1580                 rc = llapi_layout_comp_flags_set(layout, mirror_flags);
1581                 if (rc)
1582                         return rc;
1583         }
1584
1585         return LLAPI_LAYOUT_ITER_CONT;
1586 }
1587
1588 /**
1589  * mirror_create() - Create a mirrored file.
1590  * @fname:        The file to be created.
1591  * @mirror_list:  A linked list that stores the mirror arguments.
1592  *
1593  * This function creates a mirrored file @fname with the mirror(s)
1594  * from @mirror_list.
1595  *
1596  * Return: 0 on success or a negative error code on failure.
1597  */
1598 static int mirror_create(char *fname, struct mirror_args *mirror_list)
1599 {
1600         struct llapi_layout *layout = NULL;
1601         struct mirror_args *cur_mirror = NULL;
1602         uint16_t mirror_count = 0;
1603         int i = 0;
1604         int rc = 0;
1605
1606         rc = mirror_create_sanity_check(fname, mirror_list, false);
1607         if (rc)
1608                 return rc;
1609
1610         cur_mirror = mirror_list;
1611         while (cur_mirror) {
1612                 rc = llapi_layout_comp_iterate(cur_mirror->m_layout,
1613                                                mirror_set_flags,
1614                                                &cur_mirror->m_flags);
1615                 if (rc) {
1616                         rc = -errno;
1617                         fprintf(stderr, "%s: failed to set mirror flags\n",
1618                                 progname);
1619                         goto error;
1620                 }
1621
1622                 for (i = 0; i < cur_mirror->m_count; i++) {
1623                         rc = llapi_layout_merge(&layout, cur_mirror->m_layout);
1624                         if (rc) {
1625                                 rc = -errno;
1626                                 fprintf(stderr,
1627                                         "error: %s: merge layout failed: %s\n",
1628                                         progname, strerror(errno));
1629                                 goto error;
1630                         }
1631                 }
1632                 mirror_count += cur_mirror->m_count;
1633                 cur_mirror = cur_mirror->m_next;
1634         }
1635
1636         if (!layout) {
1637                 fprintf(stderr, "error: %s: layout is NULL\n", progname);
1638                 return -EINVAL;
1639         }
1640
1641         rc = llapi_layout_mirror_count_set(layout, mirror_count);
1642         if (rc) {
1643                 rc = -errno;
1644                 fprintf(stderr, "error: %s: set mirror count failed: %s\n",
1645                         progname, strerror(errno));
1646                 goto error;
1647         }
1648
1649         rc = lfs_component_create(fname, O_CREAT | O_WRONLY, 0666,
1650                                   layout);
1651         if (rc >= 0) {
1652                 close(rc);
1653                 rc = 0;
1654         }
1655
1656 error:
1657         llapi_layout_free(layout);
1658         return rc;
1659 }
1660
1661 /**
1662  * Compare files and check lease on @fd.
1663  *
1664  * \retval bytes number of bytes are the same
1665  */
1666 static ssize_t mirror_file_compare(int fd, int fdv)
1667 {
1668         const size_t buflen = 4 * 1024 * 1024; /* 4M */
1669         void *buf;
1670         ssize_t bytes_done = 0;
1671         ssize_t bytes_read = 0;
1672
1673         buf = malloc(buflen * 2);
1674         if (!buf)
1675                 return -ENOMEM;
1676
1677         while (1) {
1678                 if (!llapi_lease_check(fd)) {
1679                         bytes_done = -EBUSY;
1680                         break;
1681                 }
1682
1683                 bytes_read = read(fd, buf, buflen);
1684                 if (bytes_read <= 0)
1685                         break;
1686
1687                 if (bytes_read != read(fdv, buf + buflen, buflen))
1688                         break;
1689
1690                 /*
1691                  * XXX: should compute the checksum on each buffer and then
1692                  * compare checksum to avoid cache collision
1693                  */
1694                 if (memcmp(buf, buf + buflen, bytes_read))
1695                         break;
1696
1697                 bytes_done += bytes_read;
1698         }
1699
1700         free(buf);
1701
1702         return bytes_done;
1703 }
1704
1705 static int mirror_extend_file(const char *fname, const char *victim_file,
1706                               enum mirror_flags mirror_flags)
1707 {
1708         int fd = -1;
1709         int fdv = -1;
1710         struct stat stbuf;
1711         struct stat stbuf_v;
1712         struct ll_ioc_lease *data = NULL;
1713         int rc;
1714
1715         fd = open(fname, O_RDWR);
1716         if (fd < 0) {
1717                 error_loc = "open source file";
1718                 rc = -errno;
1719                 goto out;
1720         }
1721
1722         fdv = open(victim_file, O_RDWR);
1723         if (fdv < 0) {
1724                 error_loc = "open target file";
1725                 rc = -errno;
1726                 goto out;
1727         }
1728
1729         if (fstat(fd, &stbuf) || fstat(fdv, &stbuf_v)) {
1730                 error_loc = "stat source or target file";
1731                 rc = -errno;
1732                 goto out;
1733         }
1734
1735         if (stbuf.st_dev != stbuf_v.st_dev) {
1736                 error_loc = "stat source and target file";
1737                 rc = -EXDEV;
1738                 goto out;
1739         }
1740
1741         /* mirrors should be of the same size */
1742         if (stbuf.st_size != stbuf_v.st_size) {
1743                 error_loc = "file sizes don't match";
1744                 rc = -EINVAL;
1745                 goto out;
1746         }
1747
1748         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
1749         if (rc < 0) {
1750                 error_loc = "cannot get lease";
1751                 goto out;
1752         }
1753
1754         if (!(mirror_flags & MF_NO_VERIFY)) {
1755                 ssize_t ret;
1756                 /* mirrors should have the same contents */
1757                 ret = mirror_file_compare(fd, fdv);
1758                 if (ret != stbuf.st_size) {
1759                         error_loc = "file busy or contents don't match";
1760                         rc = ret < 0 ? ret : -EINVAL;
1761                         goto out;
1762                 }
1763         }
1764
1765         /* Get rid of caching pages from clients */
1766         rc = llapi_file_flush(fd);
1767         if (rc < 0) {
1768                 error_loc = "cannot get data version";
1769                 goto out;
1770         }
1771
1772         rc = llapi_file_flush(fdv);
1773         if (rc < 0) {
1774                 error_loc = "cannot get data version";
1775                 goto out;
1776         }
1777
1778         rc = migrate_set_timestamps(fd, &stbuf);
1779         if (rc < 0) {
1780                 error_loc = "cannot set source file timestamp";
1781                 goto out;
1782         }
1783
1784         /* Atomically put lease, merge layouts and close. */
1785         data = calloc(1, offsetof(typeof(*data), lil_ids[1]));
1786         if (!data) {
1787                 error_loc = "memory allocation";
1788                 goto out;
1789         }
1790         data->lil_mode = LL_LEASE_UNLCK;
1791         data->lil_flags = LL_LEASE_LAYOUT_MERGE;
1792         data->lil_count = 1;
1793         data->lil_ids[0] = fdv;
1794         rc = llapi_lease_set(fd, data);
1795         if (rc < 0) {
1796                 error_loc = "cannot merge layout";
1797                 goto out;
1798         } else if (rc == 0) {
1799                 rc = -EBUSY;
1800                 error_loc = "lost lease lock";
1801                 goto out;
1802         }
1803         rc = 0;
1804
1805 out:
1806         if (data)
1807                 free(data);
1808         if (fd >= 0)
1809                 close(fd);
1810         if (fdv >= 0)
1811                 close(fdv);
1812         if (!rc)
1813                 (void) unlink(victim_file);
1814         if (rc < 0)
1815                 fprintf(stderr, "error: %s: %s: %s: %s\n",
1816                         progname, fname, error_loc, strerror(-rc));
1817         return rc;
1818 }
1819
1820 static int mirror_extend_layout(char *name, struct llapi_layout *m_layout,
1821                                 bool inherit, uint32_t flags)
1822 {
1823         struct llapi_layout *f_layout = NULL;
1824         struct ll_ioc_lease *data = NULL;
1825         struct stat st;
1826         int fd = -1;
1827         int fdv = -1;
1828         int rc = 0;
1829
1830         if (inherit) {
1831                 f_layout = llapi_layout_get_by_path(name, 0);
1832                 if (!f_layout) {
1833                         rc = -EINVAL;
1834                         fprintf(stderr, "%s: cannot get layout\n", progname);
1835                         goto out;
1836                 }
1837                 rc = llapi_layout_get_last_init_comp(f_layout);
1838                 if (rc) {
1839                         fprintf(stderr, "%s: cannot get the last init comp\n",
1840                                 progname);
1841                         goto out;
1842                 }
1843                 rc = llapi_layout_mirror_inherit(f_layout, m_layout);
1844                 if (rc) {
1845                         fprintf(stderr,
1846                                 "%s: cannot inherit from the last init comp\n",
1847                                 progname);
1848                         goto out;
1849                 }
1850         }
1851
1852         llapi_layout_comp_flags_set(m_layout, flags);
1853         rc = migrate_open_files(name,
1854                              LLAPI_MIGRATION_NONDIRECT | LLAPI_MIGRATION_MIRROR,
1855                              NULL, m_layout, &fd, &fdv);
1856         if (rc < 0)
1857                 goto out;
1858
1859         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
1860         if (rc < 0) {
1861                 error_loc = "cannot get lease";
1862                 goto out;
1863         }
1864
1865         rc = fstat(fd, &st);
1866         if (rc < 0) {
1867                 error_loc = "cannot stat source file";
1868                 goto out;
1869         }
1870
1871         rc = migrate_nonblock(fd, fdv);
1872         if (rc < 0) {
1873                 llapi_lease_release(fd);
1874                 goto out;
1875         }
1876
1877         rc = migrate_set_timestamps(fd, &st);
1878         if (rc < 0) {
1879                 error_loc = "cannot set source file timestamp";
1880                 goto out;
1881         }
1882
1883         /* Atomically put lease, merge layouts and close. */
1884         data = calloc(1, offsetof(typeof(*data), lil_ids[1]));
1885         if (!data) {
1886                 error_loc = "memory allocation";
1887                 goto out;
1888         }
1889         data->lil_mode = LL_LEASE_UNLCK;
1890         data->lil_flags = LL_LEASE_LAYOUT_MERGE;
1891         data->lil_count = 1;
1892         data->lil_ids[0] = fdv;
1893         rc = llapi_lease_set(fd, data);
1894         if (rc < 0) {
1895                 error_loc = "cannot merge layout";
1896                 goto out;
1897         } else if (rc == 0) {
1898                 rc = -EBUSY;
1899                 error_loc = "lost lease lock";
1900                 goto out;
1901         }
1902         rc = 0;
1903
1904 out:
1905         if (data)
1906                 free(data);
1907         if (fd >= 0)
1908                 close(fd);
1909         if (fdv >= 0)
1910                 close(fdv);
1911         if (rc < 0)
1912                 fprintf(stderr, "error: %s: %s: %s: %s\n",
1913                         progname, name, error_loc, strerror(-rc));
1914         return rc;
1915 }
1916
1917 static int mirror_extend(char *fname, struct mirror_args *mirror_list,
1918                          enum mirror_flags mirror_flags)
1919 {
1920         int rc = 0;
1921
1922         while (mirror_list) {
1923                 if (mirror_list->m_file) {
1924                         rc = mirror_extend_file(fname, mirror_list->m_file,
1925                                                 mirror_flags);
1926                 } else {
1927                         __u32 mirror_count = mirror_list->m_count;
1928
1929                         while (mirror_count > 0) {
1930                                 rc = mirror_extend_layout(fname,
1931                                                         mirror_list->m_layout,
1932                                                         mirror_list->m_inherit,
1933                                                         mirror_list->m_flags);
1934                                 if (rc)
1935                                         break;
1936
1937                                 --mirror_count;
1938                         }
1939                 }
1940                 if (rc)
1941                         break;
1942
1943                 mirror_list = mirror_list->m_next;
1944         }
1945
1946         return rc;
1947 }
1948
1949 static int find_mirror_id(struct llapi_layout *layout, void *cbdata)
1950 {
1951         uint32_t id;
1952         int rc;
1953
1954         rc = llapi_layout_mirror_id_get(layout, &id);
1955         if (rc < 0)
1956                 return rc;
1957
1958         if ((__u16)id == *(__u16 *)cbdata)
1959                 return LLAPI_LAYOUT_ITER_STOP;
1960
1961         return LLAPI_LAYOUT_ITER_CONT;
1962 }
1963
1964 static int find_comp_id(struct llapi_layout *layout, void *cbdata)
1965 {
1966         uint32_t id;
1967         int rc;
1968
1969         rc = llapi_layout_comp_id_get(layout, &id);
1970         if (rc < 0)
1971                 return rc;
1972
1973         if (id == *(__u32 *)cbdata)
1974                 return LLAPI_LAYOUT_ITER_STOP;
1975
1976         return LLAPI_LAYOUT_ITER_CONT;
1977 }
1978
1979 static int find_mirror_id_by_pool(struct llapi_layout *layout, void *cbdata)
1980 {
1981         char buf[LOV_MAXPOOLNAME + 1];
1982         struct pool_to_id_cbdata *d = (void *)cbdata;
1983         uint32_t id;
1984         int rc;
1985
1986         rc = llapi_layout_pool_name_get(layout, buf, sizeof(buf));
1987         if (rc < 0)
1988                 return rc;
1989         if (strcmp(d->pool, buf))
1990                 return LLAPI_LAYOUT_ITER_CONT;
1991
1992         rc = llapi_layout_mirror_id_get(layout, &id);
1993         if (rc < 0)
1994                 return rc;
1995         d->id = id;
1996
1997         return LLAPI_LAYOUT_ITER_STOP;
1998 }
1999
2000 static int find_comp_id_by_pool(struct llapi_layout *layout, void *cbdata)
2001 {
2002         char buf[LOV_MAXPOOLNAME + 1];
2003         struct pool_to_id_cbdata *d = (void *)cbdata;
2004         uint32_t id;
2005         int rc;
2006
2007         rc = llapi_layout_pool_name_get(layout, buf, sizeof(buf));
2008         if (rc < 0)
2009                 return rc;
2010         if (strcmp(d->pool, buf))
2011                 return LLAPI_LAYOUT_ITER_CONT;
2012
2013         rc = llapi_layout_comp_id_get(layout, &id);
2014         if (rc < 0)
2015                 return rc;
2016         d->id = id;
2017
2018         return LLAPI_LAYOUT_ITER_STOP;
2019 }
2020
2021 struct collect_ids_data {
2022         __u16   *cid_ids;
2023         int     cid_count;
2024         __u16   cid_exclude;
2025 };
2026
2027 static int collect_mirror_id(struct llapi_layout *layout, void *cbdata)
2028 {
2029         struct collect_ids_data *cid = cbdata;
2030         uint32_t id;
2031         int rc;
2032
2033         rc = llapi_layout_mirror_id_get(layout, &id);
2034         if (rc < 0)
2035                 return rc;
2036
2037         if ((__u16)id != cid->cid_exclude) {
2038                 int i;
2039
2040                 for (i = 0; i < cid->cid_count; i++) {
2041                         /* already collected the mirror id */
2042                         if (id == cid->cid_ids[i])
2043                                 return LLAPI_LAYOUT_ITER_CONT;
2044                 }
2045                 cid->cid_ids[cid->cid_count] = id;
2046                 cid->cid_count++;
2047         }
2048
2049         return LLAPI_LAYOUT_ITER_CONT;
2050 }
2051
2052 /**
2053  * last_non_stale_mirror() - Check if a mirror is the last non-stale mirror.
2054  * @mirror_id: Mirror id to be checked.
2055  * @layout:    Mirror component list.
2056  *
2057  * This function checks if a mirror with specified @mirror_id is the last
2058  * non-stale mirror of a layout @layout.
2059  *
2060  * Return: true or false.
2061  */
2062 static inline
2063 bool last_non_stale_mirror(__u16 mirror_id, struct llapi_layout *layout)
2064 {
2065         __u16 mirror_ids[128] = { 0 };
2066         struct collect_ids_data cid = { .cid_ids = mirror_ids,
2067                                         .cid_count = 0,
2068                                         .cid_exclude = mirror_id, };
2069         int i;
2070
2071         llapi_layout_comp_iterate(layout, collect_mirror_id, &cid);
2072
2073         for (i = 0; i < cid.cid_count; i++) {
2074                 struct llapi_resync_comp comp_array[1024] = { { 0 } };
2075                 int comp_size = 0;
2076
2077                 comp_size = llapi_mirror_find_stale(layout, comp_array,
2078                                                     ARRAY_SIZE(comp_array),
2079                                                     &mirror_ids[i], 1);
2080                 if (comp_size == 0)
2081                         return false;
2082         }
2083
2084         return true;
2085 }
2086
2087 static int mirror_split(const char *fname, __u32 id, const char *pool,
2088                         enum mirror_flags mflags, const char *victim_file)
2089 {
2090         struct llapi_layout *layout;
2091         char parent[PATH_MAX];
2092         char victim[PATH_MAX];
2093         int flags = O_CREAT | O_EXCL | O_LOV_DELAY_CREATE | O_NOFOLLOW;
2094         char *ptr;
2095         struct ll_ioc_lease *data;
2096         uint16_t mirror_count;
2097         __u32 mirror_id;
2098         int mdt_index;
2099         int fd, fdv;
2100         bool purge = true; /* delete mirror by setting fdv=fd */
2101         bool is_encrypted;
2102         int rc;
2103
2104         if (victim_file && (strcmp(fname, victim_file) == 0)) {
2105                 fprintf(stderr,
2106                         "error %s: the source file '%s' and -f file are the same\n",
2107                         progname, fname);
2108                 return -EINVAL;
2109         }
2110
2111         /* check fname contains mirror with mirror_id/comp_id */
2112         layout = llapi_layout_get_by_path(fname, 0);
2113         if (!layout) {
2114                 fprintf(stderr,
2115                         "error %s: file '%s' couldn't get layout\n",
2116                         progname, fname);
2117                 return -EINVAL;
2118         }
2119
2120         rc = llapi_layout_sanity(layout, false, true);
2121         if (rc) {
2122                 llapi_layout_sanity_perror(rc);
2123                 goto free_layout;
2124         }
2125
2126         rc = llapi_layout_mirror_count_get(layout, &mirror_count);
2127         if (rc) {
2128                 fprintf(stderr,
2129                         "error %s: file '%s' couldn't get mirror count\n",
2130                         progname, fname);
2131                 goto free_layout;
2132         }
2133         if (mirror_count < 2) {
2134                 fprintf(stderr,
2135                         "error %s: file '%s' has %d component, cannot split\n",
2136                         progname, fname, mirror_count);
2137                 goto free_layout;
2138         }
2139
2140         if (mflags & MF_COMP_POOL) {
2141                 struct pool_to_id_cbdata data = { .pool = pool };
2142
2143                 rc = llapi_layout_comp_iterate(layout, find_mirror_id_by_pool,
2144                                                &data);
2145                 mirror_id = data.id;
2146         } else if (mflags & MF_COMP_ID) {
2147                 rc = llapi_layout_comp_iterate(layout, find_comp_id, &id);
2148                 mirror_id = mirror_id_of(id);
2149         } else {
2150                 rc = llapi_layout_comp_iterate(layout, find_mirror_id, &id);
2151                 mirror_id = id;
2152         }
2153         if (rc < 0) {
2154                 fprintf(stderr, "error %s: failed to iterate layout of '%s'\n",
2155                         progname, fname);
2156                 goto free_layout;
2157         } else if (rc == LLAPI_LAYOUT_ITER_CONT) {
2158                 if (mflags & MF_COMP_POOL) {
2159                         fprintf(stderr,
2160                                 "error %s: file '%s' does not contain mirror with pool '%s'\n",
2161                                 progname, fname, pool);
2162                         goto free_layout;
2163                 } else if (mflags & MF_COMP_ID) {
2164                         fprintf(stderr,
2165                                 "error %s: file '%s' does not contain mirror with comp-id %u\n",
2166                                 progname, fname, id);
2167                         goto free_layout;
2168                 } else {
2169                         fprintf(stderr,
2170                                 "error %s: file '%s' does not contain mirror with id %u\n",
2171                                 progname, fname, id);
2172                         goto free_layout;
2173                 }
2174         }
2175
2176         if (!victim_file && mflags & MF_DESTROY)
2177                 /* Allow mirror split even without the key on encrypted files,
2178                  * and in this case of a 'split -d', open file with O_DIRECT
2179                  * (no IOs will be done).
2180                  */
2181                 fd = open(fname, O_RDWR | O_DIRECT | O_FILE_ENC);
2182         else
2183                 fd = open(fname, O_RDWR);
2184
2185         if (fd < 0) {
2186                 fprintf(stderr,
2187                         "error %s: open file '%s' failed: %s\n",
2188                         progname, fname, strerror(errno));
2189                 goto free_layout;
2190         }
2191
2192         /* get victim file directory pathname */
2193         if (strlen(fname) > sizeof(parent) - 1) {
2194                 fprintf(stderr, "error %s: file name of '%s' too long\n",
2195                         progname, fname);
2196                 rc = -ERANGE;
2197                 goto close_fd;
2198         }
2199         strncpy(parent, fname, sizeof(parent));
2200         ptr = strrchr(parent, '/');
2201         if (!ptr) {
2202                 if (!getcwd(parent, sizeof(parent))) {
2203                         fprintf(stderr, "error %s: getcwd failed: %s\n",
2204                                 progname, strerror(errno));
2205                         rc = -errno;
2206                         goto close_fd;
2207                 }
2208         } else {
2209                 if (ptr == parent)
2210                         ptr = parent + 1;
2211                 *ptr = '\0';
2212         }
2213
2214         rc = llapi_file_fget_mdtidx(fd, &mdt_index);
2215         if (rc < 0) {
2216                 fprintf(stderr, "%s: cannot get MDT index of '%s'\n",
2217                         progname, fname);
2218                 goto close_fd;
2219         }
2220
2221         rc = llapi_file_is_encrypted(fd);
2222         if (rc < 0) {
2223                 fprintf(stderr, "%s: cannot get flags of '%s': %d\n",
2224                         progname, fname, rc);
2225                 goto close_fd;
2226         }
2227         is_encrypted = rc;
2228
2229 again:
2230         if (!victim_file) {
2231                 /* use a temp file to store the splitted layout */
2232                 if (mflags & MF_DESTROY) {
2233                         char file_path[PATH_MAX];
2234                         unsigned int rnumber;
2235                         int open_flags;
2236
2237                         if (last_non_stale_mirror(mirror_id, layout)) {
2238                                 rc = -EUCLEAN;
2239                                 fprintf(stderr,
2240                                         "%s: cannot destroy the last non-stale mirror of file '%s'\n",
2241                                         progname, fname);
2242                                 goto close_fd;
2243                         }
2244
2245                         if (purge) {
2246                                 /* don't use volatile file for mirror destroy */
2247                                 fdv = fd;
2248                         } else {
2249                                 /**
2250                                  * try the old way to delete mirror using
2251                                  * volatile file.
2252                                  */
2253                                 do {
2254                                         rnumber = random();
2255                                         rc = snprintf(file_path,
2256                                                       sizeof(file_path),
2257                                                       "%s/" LUSTRE_VOLATILE_HDR ":%.4X:%.4X:fd=%.2d",
2258                                                       parent, mdt_index,
2259                                                       rnumber, fd);
2260                                         if (rc < 0 ||
2261                                             rc >= sizeof(file_path)) {
2262                                                 fdv = -ENAMETOOLONG;
2263                                                 break;
2264                                         }
2265
2266                                         open_flags = O_RDWR |
2267                                              (O_LOV_DELAY_CREATE & ~O_ACCMODE) |
2268                                              O_CREAT | O_EXCL | O_NOFOLLOW |
2269                                              /* O_DIRECT for mirror split -d */
2270                                              O_DIRECT |
2271                                              /* Allow split without the key */
2272                                              O_FILE_ENC;
2273                                         fdv = open(file_path, open_flags,
2274                                                    S_IRUSR | S_IWUSR);
2275                                         if (fdv < 0)
2276                                                 rc = -errno;
2277                                 } while (fdv < 0 && rc == -EEXIST);
2278                         }
2279                 } else {
2280                         if (is_encrypted) {
2281                                 rc = -1;
2282                                 fprintf(stderr,
2283                                         "error %s: not permitted on encrypted file '%s': %d\n",
2284                                         progname, fname, rc);
2285                                 goto close_fd;
2286                         }
2287
2288                         snprintf(victim, sizeof(victim), "%s.mirror~%u",
2289                                  fname, mirror_id);
2290                         fdv = open(victim, flags, S_IRUSR | S_IWUSR);
2291                 }
2292         } else {
2293                 /* user specified victim file */
2294                 if (is_encrypted) {
2295                         rc = -1;
2296                         fprintf(stderr,
2297                                 "error %s: not permitted on encrypted file '%s': %d\n",
2298                                 progname, fname, rc);
2299                         goto close_fd;
2300                 }
2301                 fdv = open(victim_file, flags, S_IRUSR | S_IWUSR);
2302         }
2303
2304         if (fdv < 0) {
2305                 fprintf(stderr,
2306                         "error %s: create victim file failed: %s\n",
2307                         progname, strerror(errno));
2308                 goto close_fd;
2309         }
2310
2311         /* get lease lock of fname */
2312         rc = llapi_lease_acquire(fd, LL_LEASE_WRLCK);
2313         if (rc < 0) {
2314                 fprintf(stderr,
2315                         "error %s: cannot get lease of file '%s': %d\n",
2316                         progname, fname, rc);
2317                 goto close_victim;
2318         }
2319
2320         /* Atomatically put lease, split layouts and close. */
2321         data = malloc(offsetof(typeof(*data), lil_ids[2]));
2322         if (!data) {
2323                 rc = -ENOMEM;
2324                 goto close_victim;
2325         }
2326
2327         data->lil_mode = LL_LEASE_UNLCK;
2328         data->lil_flags = LL_LEASE_LAYOUT_SPLIT;
2329         data->lil_count = 2;
2330         data->lil_ids[0] = fdv;
2331         data->lil_ids[1] = mirror_id;
2332         rc = llapi_lease_set(fd, data);
2333         if (rc <= 0) {
2334                 if ((rc == -EINVAL || rc == -EBUSY) && purge) {
2335                         /* could be old MDS which prohibit fd==fdv */
2336                         purge = false;
2337                         goto again;
2338
2339                 }
2340                 if (rc == 0) /* lost lease lock */
2341                         rc = -EBUSY;
2342                 fprintf(stderr,
2343                         "error %s: cannot split '%s': %s\n",
2344                         progname, fname, strerror(-rc));
2345         } else {
2346                 rc = 0;
2347         }
2348         free(data);
2349
2350 close_victim:
2351         if (!purge)
2352                 close(fdv);
2353 close_fd:
2354         close(fd);
2355 free_layout:
2356         llapi_layout_free(layout);
2357         return rc;
2358 }
2359
2360 static inline
2361 int lfs_mirror_resync_file(const char *fname, struct ll_ioc_lease *ioc,
2362                            __u16 *mirror_ids, int ids_nr);
2363
2364 static int lfs_migrate_to_dom(int fd, int fdv, char *name,
2365                               __u64 migration_flags)
2366 {
2367         struct ll_ioc_lease *data = NULL;
2368         int rc;
2369
2370         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
2371         if (rc < 0) {
2372                 error_loc = "cannot get lease";
2373                 goto out_close;
2374         }
2375
2376         rc = migrate_nonblock(fd, fdv);
2377         if (rc < 0)
2378                 goto out_release;
2379
2380         /* Atomically put lease, merge layouts, resync and close. */
2381         data = calloc(1, offsetof(typeof(*data), lil_ids[1]));
2382         if (!data) {
2383                 error_loc = "memory allocation";
2384                 goto out_release;
2385         }
2386         data->lil_mode = LL_LEASE_UNLCK;
2387         data->lil_flags = LL_LEASE_LAYOUT_MERGE;
2388         data->lil_count = 1;
2389         data->lil_ids[0] = fdv;
2390         rc = llapi_lease_set(fd, data);
2391         if (rc < 0) {
2392                 error_loc = "cannot merge layout";
2393                 goto out_close;
2394         } else if (rc == 0) {
2395                 rc = -EBUSY;
2396                 error_loc = "lost lease lock";
2397                 goto out_close;
2398         }
2399         close(fd);
2400         close(fdv);
2401
2402         rc = lfs_mirror_resync_file(name, data, NULL, 0);
2403         if (rc) {
2404                 error_loc = "cannot resync file";
2405                 goto out;
2406         }
2407
2408         /* delete first mirror now */
2409         rc = mirror_split(name, 1, NULL, MF_DESTROY, NULL);
2410         if (rc < 0)
2411                 error_loc = "cannot delete old layout";
2412         goto out;
2413
2414 out_release:
2415         llapi_lease_release(fd);
2416 out_close:
2417         close(fd);
2418         close(fdv);
2419 out:
2420         if (rc < 0)
2421                 fprintf(stderr, "error: %s: %s: %s: %s\n",
2422                         progname, name, error_loc, strerror(-rc));
2423         else if (migration_flags & LLAPI_MIGRATION_VERBOSE)
2424                 printf("%s\n", name);
2425         if (data)
2426                 free(data);
2427         return rc;
2428 }
2429
2430 /**
2431  * Parse a string containing an target index list into an array of integers.
2432  *
2433  * The input string contains a comma delimited list of individual
2434  * indices and ranges, for example "1,2-4,7". Add the indices into the
2435  * \a tgts array and remove duplicates.
2436  *
2437  * \param[out] tgts             array to store indices in
2438  * \param[in] size              size of \a tgts array
2439  * \param[in] offset            starting index in \a tgts
2440  * \param[in] arg               string containing OST index list
2441  * \param[in/out] overstriping  index list may contain duplicates
2442  *
2443  * \retval positive    number of indices in \a tgts
2444  * \retval -EINVAL     unable to parse \a arg
2445  */
2446 static int parse_targets(__u32 *tgts, int size, int offset, char *arg,
2447                          unsigned long long *pattern)
2448 {
2449         int rc;
2450         int nr = offset;
2451         int slots = size - offset;
2452         char *ptr = NULL;
2453         bool overstriped = false;
2454         bool end_of_loop;
2455
2456         if (!arg)
2457                 return -EINVAL;
2458
2459         end_of_loop = false;
2460         while (!end_of_loop) {
2461                 int start_index = 0;
2462                 int end_index = 0;
2463                 int i;
2464                 char *endptr = NULL;
2465
2466                 rc = -EINVAL;
2467
2468                 ptr = strchrnul(arg, ',');
2469
2470                 end_of_loop = *ptr == '\0';
2471                 *ptr = '\0';
2472
2473                 errno = 0;
2474                 start_index = strtol(arg, &endptr, 0);
2475                 if (endptr == arg) /* no data at all */
2476                         break;
2477                 if (errno != 0 || start_index < -1 ||
2478                     (*endptr != '-' && *endptr != '\0'))
2479                         break;
2480
2481                 end_index = start_index;
2482                 if (*endptr == '-') {
2483                         errno = 0;
2484                         end_index = strtol(endptr + 1, &endptr, 0);
2485                         if (errno != 0 || *endptr != '\0' || end_index < -1)
2486                                 break;
2487                         if (end_index < start_index)
2488                                 break;
2489                 }
2490
2491                 for (i = start_index; i <= end_index && slots > 0; i++) {
2492                         int j;
2493
2494                         /* remove duplicate */
2495                         for (j = 0; j < offset; j++) {
2496                                 if (tgts[j] == i && pattern &&
2497                                     *pattern == LLAPI_LAYOUT_OVERSTRIPING)
2498                                         overstriped = true;
2499                                 else if (tgts[j] == i)
2500                                         return -EINVAL;
2501                         }
2502
2503                         j = offset;
2504
2505                         if (j == offset) { /* check complete */
2506                                 tgts[nr++] = i;
2507                                 --slots;
2508                         }
2509                 }
2510
2511                 if (slots == 0 && i < end_index)
2512                         break;
2513
2514                 *ptr = ',';
2515                 arg = ++ptr;
2516                 offset = nr;
2517                 rc = 0;
2518         }
2519         if (!end_of_loop && ptr)
2520                 *ptr = ',';
2521
2522         if (!overstriped && pattern)
2523                 *pattern = LLAPI_LAYOUT_DEFAULT;
2524
2525         return rc < 0 ? rc : nr;
2526 }
2527
2528 struct lfs_setstripe_args {
2529         unsigned long long       lsa_comp_end;
2530         unsigned long long       lsa_stripe_size;
2531         unsigned long long       lsa_extension_size;
2532         long long                lsa_stripe_count;
2533         long long                lsa_stripe_off;
2534         __u32                    lsa_comp_flags;
2535         __u32                    lsa_comp_neg_flags;
2536         unsigned long long       lsa_pattern;
2537         unsigned int             lsa_mirror_count;
2538         int                      lsa_nr_tgts;
2539         bool                     lsa_first_comp;
2540         bool                     lsa_extension_comp;
2541         __u32                   *lsa_tgts;
2542         char                    *lsa_pool_name;
2543 };
2544
2545 static inline void setstripe_args_init(struct lfs_setstripe_args *lsa)
2546 {
2547         unsigned int mirror_count = lsa->lsa_mirror_count;
2548         bool first_comp = lsa->lsa_first_comp;
2549
2550         memset(lsa, 0, sizeof(*lsa));
2551
2552         lsa->lsa_stripe_size = LLAPI_LAYOUT_DEFAULT;
2553         lsa->lsa_stripe_count = LLAPI_LAYOUT_DEFAULT;
2554         lsa->lsa_stripe_off = LLAPI_LAYOUT_DEFAULT;
2555         lsa->lsa_pattern = LLAPI_LAYOUT_RAID0;
2556         lsa->lsa_pool_name = NULL;
2557
2558         lsa->lsa_mirror_count = mirror_count;
2559         lsa->lsa_first_comp = first_comp;
2560 }
2561
2562 /**
2563  * setstripe_args_init_inherit() - Initialize and inherit stripe options.
2564  * @lsa: Stripe options to be initialized and inherited.
2565  *
2566  * This function initializes stripe options in @lsa and inherit
2567  * stripe_size, stripe_count and OST pool_name options.
2568  *
2569  * Return: void.
2570  */
2571 static inline void setstripe_args_init_inherit(struct lfs_setstripe_args *lsa)
2572 {
2573         unsigned long long stripe_size;
2574         long long stripe_count;
2575         char *pool_name = NULL;
2576
2577         stripe_size = lsa->lsa_stripe_size;
2578         stripe_count = lsa->lsa_stripe_count;
2579         pool_name = lsa->lsa_pool_name;
2580
2581         setstripe_args_init(lsa);
2582
2583         lsa->lsa_stripe_size = stripe_size;
2584         lsa->lsa_stripe_count = stripe_count;
2585         lsa->lsa_pool_name = pool_name;
2586 }
2587
2588 static inline bool setstripe_args_specified(struct lfs_setstripe_args *lsa)
2589 {
2590         return (lsa->lsa_stripe_size != LLAPI_LAYOUT_DEFAULT ||
2591                 lsa->lsa_stripe_count != LLAPI_LAYOUT_DEFAULT ||
2592                 lsa->lsa_stripe_off != LLAPI_LAYOUT_DEFAULT ||
2593                 lsa->lsa_pattern != LLAPI_LAYOUT_RAID0 ||
2594                 lsa->lsa_comp_end != 0);
2595 }
2596
2597 static int lsa_args_stripe_count_check(struct lfs_setstripe_args *lsa)
2598 {
2599         if (lsa->lsa_nr_tgts) {
2600                 if (lsa->lsa_nr_tgts < 0 ||
2601                     lsa->lsa_nr_tgts >= LOV_MAX_STRIPE_COUNT) {
2602                         fprintf(stderr, "Invalid nr_tgts(%d)\n",
2603                                 lsa->lsa_nr_tgts);
2604                         errno = EINVAL;
2605                         return -1;
2606                 }
2607
2608                 if (lsa->lsa_stripe_count > 0 &&
2609                     lsa->lsa_stripe_count != LLAPI_LAYOUT_DEFAULT &&
2610                     lsa->lsa_stripe_count != LLAPI_LAYOUT_WIDE &&
2611                     lsa->lsa_nr_tgts != lsa->lsa_stripe_count) {
2612                         fprintf(stderr, "stripe_count(%lld) != nr_tgts(%d)\n",
2613                                 lsa->lsa_stripe_count,
2614                                 lsa->lsa_nr_tgts);
2615                         errno = EINVAL;
2616                         return -1;
2617                 }
2618         }
2619
2620         return 0;
2621
2622 }
2623
2624 /**
2625  * comp_args_to_layout() - Create or extend a composite layout.
2626  * @composite:       Pointer to the composite layout.
2627  * @lsa:             Stripe options for the new component.
2628  *
2629  * This function creates or extends a composite layout by adding a new
2630  * component with stripe options from @lsa.
2631  *
2632  * When modified, adjust llapi_stripe_param_verify() if needed as well.
2633  *
2634  * Return: 0 on success or an error code on failure.
2635  */
2636 static int comp_args_to_layout(struct llapi_layout **composite,
2637                                struct lfs_setstripe_args *lsa,
2638                                bool set_extent)
2639 {
2640         struct llapi_layout *layout = *composite;
2641         uint64_t prev_end = 0;
2642         uint64_t size;
2643         int i = 0, rc;
2644
2645 new_comp:
2646         if (!layout) {
2647                 layout = llapi_layout_alloc();
2648                 if (!layout) {
2649                         fprintf(stderr, "Alloc llapi_layout failed. %s\n",
2650                                 strerror(errno));
2651                         errno = ENOMEM;
2652                         return -1;
2653                 }
2654                 *composite = layout;
2655                 lsa->lsa_first_comp = true;
2656         } else {
2657                 uint64_t start;
2658
2659                 /*
2660                  * Get current component extent, current component
2661                  * must be the tail component.
2662                  */
2663                 rc = llapi_layout_comp_extent_get(layout, &start, &prev_end);
2664                 if (rc) {
2665                         fprintf(stderr, "Get comp extent failed. %s\n",
2666                                 strerror(errno));
2667                         return rc;
2668                 }
2669
2670                 if (lsa->lsa_first_comp) {
2671                         prev_end = 0;
2672                         rc = llapi_layout_add_first_comp(layout);
2673                 } else {
2674                         rc = llapi_layout_comp_add(layout);
2675                 }
2676                 if (rc) {
2677                         fprintf(stderr, "Add component failed. %s\n",
2678                                 strerror(errno));
2679                         return rc;
2680                 }
2681         }
2682
2683         rc = llapi_layout_comp_flags_set(layout, lsa->lsa_comp_flags);
2684         if (rc) {
2685                 fprintf(stderr, "Set flags 0x%x failed: %s\n",
2686                         lsa->lsa_comp_flags, strerror(errno));
2687                 return rc;
2688         }
2689
2690         if (set_extent) {
2691                 uint64_t comp_end = lsa->lsa_comp_end;
2692
2693                 /*
2694                  * The extendable component is 0-length, so it can be removed
2695                  * if there is insufficient space to extend it.
2696                  */
2697                 if (lsa->lsa_extension_comp)
2698                         comp_end = prev_end;
2699
2700                 rc = llapi_layout_comp_extent_set(layout, prev_end,
2701                                                   comp_end);
2702                 if (rc) {
2703                         fprintf(stderr, "Set extent [%lu, %lu) failed. %s\n",
2704                                 prev_end, comp_end, strerror(errno));
2705                         return rc;
2706                 }
2707         }
2708         /* reset lsa_first_comp */
2709         lsa->lsa_first_comp = false;
2710
2711         /* Data-on-MDT component setting */
2712         if (lsa->lsa_pattern == LLAPI_LAYOUT_MDT) {
2713                 /* Yaml support */
2714                 if (lsa->lsa_stripe_count == 0)
2715                         lsa->lsa_stripe_count = LLAPI_LAYOUT_DEFAULT;
2716                 if (lsa->lsa_stripe_size == lsa->lsa_comp_end)
2717                         lsa->lsa_stripe_size = LLAPI_LAYOUT_DEFAULT;
2718                 if (lsa->lsa_stripe_off == -1 ||
2719                     lsa->lsa_stripe_off == 0)
2720                         lsa->lsa_stripe_off = LLAPI_LAYOUT_DEFAULT;
2721                 /*
2722                  * In case of Data-on-MDT patterns the only extra option
2723                  * applicable is stripe size option.
2724                  */
2725                 if (lsa->lsa_stripe_count != LLAPI_LAYOUT_DEFAULT) {
2726                         fprintf(stderr,
2727                                 "Option 'stripe-count' can't be specified with Data-on-MDT component: %lld\n",
2728                                 lsa->lsa_stripe_count);
2729                         errno = EINVAL;
2730                         return -1;
2731                 }
2732                 if (lsa->lsa_stripe_size != LLAPI_LAYOUT_DEFAULT &&
2733                     lsa->lsa_stripe_size != lsa->lsa_comp_end - prev_end) {
2734                         fprintf(stderr,
2735                                 "Option 'stripe-size' can't be specified with Data-on-MDT component: %llu\n",
2736                                 lsa->lsa_stripe_size);
2737                         errno = EINVAL;
2738                         return -1;
2739                 }
2740                 if (lsa->lsa_nr_tgts != 0) {
2741                         fprintf(stderr,
2742                                 "Option 'ost-list' can't be specified with Data-on-MDT component: '%i'\n",
2743                                 lsa->lsa_nr_tgts);
2744                         errno = EINVAL;
2745                         return -1;
2746                 }
2747                 if (lsa->lsa_stripe_off != LLAPI_LAYOUT_DEFAULT) {
2748                         fprintf(stderr,
2749                                 "Option 'stripe-offset' can't be specified with Data-on-MDT component: %lld\n",
2750                                 lsa->lsa_stripe_off);
2751                         errno = EINVAL;
2752                         return -1;
2753                 }
2754                 if (lsa->lsa_pool_name != 0) {
2755                         fprintf(stderr,
2756                                 "Option 'pool' can't be specified with Data-on-MDT component: '%s'\n",
2757                                 lsa->lsa_pool_name);
2758                         errno = EINVAL;
2759                         return -1;
2760                 }
2761
2762                 rc = llapi_layout_pattern_set(layout, lsa->lsa_pattern);
2763                 if (rc) {
2764                         fprintf(stderr, "Set stripe pattern %#llx failed. %s\n",
2765                                 lsa->lsa_pattern,
2766                                 strerror(errno));
2767                         return rc;
2768                 }
2769                 /* Data-on-MDT component has always single stripe up to end */
2770                 lsa->lsa_stripe_size = lsa->lsa_comp_end;
2771         } else if (lsa->lsa_pattern == LLAPI_LAYOUT_OVERSTRIPING) {
2772                 rc = llapi_layout_pattern_set(layout, lsa->lsa_pattern);
2773                 if (rc) {
2774                         fprintf(stderr, "Set stripe pattern %#llx failed. %s\n",
2775                                 lsa->lsa_pattern,
2776                                 strerror(errno));
2777                         return rc;
2778                 }
2779         }
2780
2781         size = lsa->lsa_comp_flags & LCME_FL_EXTENSION ?
2782                 lsa->lsa_extension_size : lsa->lsa_stripe_size;
2783
2784         if (lsa->lsa_comp_flags & LCME_FL_EXTENSION)
2785                 rc = llapi_layout_extension_size_set(layout, size);
2786         else
2787                 rc = llapi_layout_stripe_size_set(layout, size);
2788
2789         if (rc) {
2790                 fprintf(stderr, "Set stripe size %lu failed: %s\n",
2791                         size, strerror(errno));
2792                 return rc;
2793         }
2794
2795         rc = llapi_layout_stripe_count_set(layout, lsa->lsa_stripe_count);
2796         if (rc) {
2797                 fprintf(stderr, "Set stripe count %lld failed: %s\n",
2798                         lsa->lsa_stripe_count, strerror(errno));
2799                 return rc;
2800         }
2801
2802         if (lsa->lsa_pool_name) {
2803                 rc = llapi_layout_pool_name_set(layout, lsa->lsa_pool_name);
2804                 if (rc) {
2805                         fprintf(stderr, "Set pool name: %s failed. %s\n",
2806                                 lsa->lsa_pool_name, strerror(errno));
2807                         return rc;
2808                 }
2809         } else {
2810                 rc = llapi_layout_pool_name_set(layout, "");
2811                 if (rc) {
2812                         fprintf(stderr, "Clear pool name failed: %s\n",
2813                                 strerror(errno));
2814                         return rc;
2815                 }
2816         }
2817
2818         rc = lsa_args_stripe_count_check(lsa);
2819         if (rc)
2820                 return rc;
2821
2822         if (lsa->lsa_nr_tgts > 0) {
2823                 bool found = false;
2824
2825                 for (i = 0; i < lsa->lsa_nr_tgts; i++) {
2826                         rc = llapi_layout_ost_index_set(layout, i,
2827                                                         lsa->lsa_tgts[i]);
2828                         if (rc)
2829                                 break;
2830
2831                         /* Make sure stripe offset is in OST list. */
2832                         if (lsa->lsa_tgts[i] == lsa->lsa_stripe_off)
2833                                 found = true;
2834                 }
2835                 if (!found) {
2836                         fprintf(stderr, "Invalid stripe offset '%lld', not in the target list",
2837                                 lsa->lsa_stripe_off);
2838                         errno = EINVAL;
2839                         return -1;
2840                 }
2841         } else if (lsa->lsa_stripe_off != LLAPI_LAYOUT_DEFAULT &&
2842                    lsa->lsa_stripe_off != -1) {
2843                 rc = llapi_layout_ost_index_set(layout, 0, lsa->lsa_stripe_off);
2844         }
2845         if (rc) {
2846                 fprintf(stderr, "Set ost index %d failed. %s\n",
2847                         i, strerror(errno));
2848                 return rc;
2849         }
2850
2851         /* Create the second, virtual component of extension space */
2852         if (lsa->lsa_extension_comp) {
2853                 lsa->lsa_comp_flags |= LCME_FL_EXTENSION;
2854                 lsa->lsa_extension_comp = false;
2855                 goto new_comp;
2856         }
2857
2858         return rc;
2859 }
2860
2861 static int build_component(struct llapi_layout **layout,
2862                            struct lfs_setstripe_args *lsa, bool set_extent)
2863 {
2864         int rc;
2865
2866         rc = comp_args_to_layout(layout, lsa, set_extent);
2867         if (rc)
2868                 return rc;
2869
2870         if (lsa->lsa_mirror_count > 0) {
2871                 rc = llapi_layout_mirror_count_set(*layout,
2872                                                    lsa->lsa_mirror_count);
2873                 if (rc)
2874                         return rc;
2875
2876                 rc = llapi_layout_flags_set(*layout, LCM_FL_RDONLY);
2877                 if (rc)
2878                         return rc;
2879                 lsa->lsa_mirror_count = 0;
2880         }
2881
2882         return rc;
2883 }
2884
2885 static int build_prev_component(struct llapi_layout **layout,
2886                                 struct lfs_setstripe_args *prev,
2887                                 struct lfs_setstripe_args *lsa,
2888                                 bool set_extent)
2889 {
2890         int extension = lsa->lsa_comp_flags & LCME_FL_EXTENSION;
2891         int rc;
2892
2893         if (prev->lsa_stripe_size) {
2894                 if (extension) {
2895                         prev->lsa_comp_end = lsa->lsa_comp_end;
2896                         prev->lsa_extension_size = lsa->lsa_extension_size;
2897                         prev->lsa_extension_comp = true;
2898                 }
2899
2900                 rc = build_component(layout, prev, true);
2901                 if (rc)
2902                         return rc;
2903         }
2904
2905         /*
2906          * Copy lsa to previous lsa;
2907          * if this is an extension component, make the previous invalid;
2908          */
2909         if (extension)
2910                 prev->lsa_stripe_size = 0;
2911         else
2912                 *prev = *lsa;
2913
2914         return 0;
2915 }
2916
2917 #ifndef LCME_TEMPLATE_FLAGS
2918 #define LCME_TEMPLATE_FLAGS     (LCME_FL_PREF_RW | LCME_FL_NOSYNC | \
2919                                  LCME_FL_EXTENSION)
2920 #endif
2921
2922 static int build_layout_from_yaml_node(struct cYAML *node,
2923                                        struct llapi_layout **layout,
2924                                        struct lfs_setstripe_args *lsa,
2925                                        struct lfs_setstripe_args *prevp)
2926 {
2927         struct lfs_setstripe_args prev = { 0 };
2928         __u32 *osts = lsa->lsa_tgts;
2929         char *string;
2930         int rc = 0;
2931
2932         if (!prevp)
2933                 prevp = &prev;
2934
2935         while (node) {
2936                 string = node->cy_string;
2937
2938                 if (node->cy_type == CYAML_TYPE_OBJECT) {
2939                         /* go deep to sub blocks */
2940                         if (string && !strncmp(string, "component", 9) &&
2941                             strncmp(string, "component0", 10) &&
2942                             strncmp(string, "components", 10)) {
2943                                 rc = build_prev_component(layout, prevp, lsa,
2944                                                           true);
2945                                 if (rc)
2946                                         return rc;
2947
2948                                 /* initialize lsa. */
2949                                 setstripe_args_init(lsa);
2950                                 lsa->lsa_first_comp = false;
2951                                 lsa->lsa_tgts = osts;
2952                         }
2953
2954                         rc = build_layout_from_yaml_node(node->cy_child, layout,
2955                                                          lsa, prevp);
2956                         if (rc)
2957                                 return rc;
2958                 } else {
2959                         if (!node->cy_string)
2960                                 return -EINVAL;
2961
2962                         /* skip leading lmm_ if present, to simplify parsing */
2963                         if (strncmp(string, "lmm_", 4) == 0)
2964                                 string += 4;
2965
2966                         if (node->cy_type == CYAML_TYPE_STRING) {
2967                                 if (!strcmp(string, "lcme_extent.e_end")) {
2968                                         if (!strcmp(node->cy_valuestring, "EOF") ||
2969                                             !strcmp(node->cy_valuestring, "eof"))
2970                                                 lsa->lsa_comp_end = LUSTRE_EOF;
2971                                 } else if (!strcmp(string, "pool")) {
2972                                         lsa->lsa_pool_name = node->cy_valuestring;
2973                                 } else if (!strcmp(string, "pattern")) {
2974                                         if (!strcmp(node->cy_valuestring, "mdt"))
2975                                                 lsa->lsa_pattern = LLAPI_LAYOUT_MDT;
2976                                         if (!strcmp(node->cy_valuestring,
2977                                                     "raid0,overstriped"))
2978                                                 lsa->lsa_pattern =
2979                                                         LLAPI_LAYOUT_OVERSTRIPING;
2980                                 } else if (!strcmp(string, "lcme_flags")) {
2981                                         rc = comp_str2flags(node->cy_valuestring,
2982                                                             &lsa->lsa_comp_flags,
2983                                                             &lsa->lsa_comp_neg_flags);
2984                                         if (rc)
2985                                                 return rc;
2986                                         /*
2987                                          * Only template flags have meaning in
2988                                          * the layout for a new file
2989                                          */
2990                                         lsa->lsa_comp_flags &= LCME_TEMPLATE_FLAGS;
2991                                 }
2992                         } else if (node->cy_type == CYAML_TYPE_NUMBER) {
2993                                 if (!strcmp(string, "lcm_mirror_count")) {
2994                                         lsa->lsa_mirror_count = node->cy_valueint;
2995                                 } else if (!strcmp(string, "lcme_extent.e_start")) {
2996                                         if (node->cy_valueint == 0)
2997                                                 lsa->lsa_first_comp = true;
2998                                 } else if (!strcmp(string, "lcme_extent.e_end")) {
2999                                         if (node->cy_valueint == -1)
3000                                                 lsa->lsa_comp_end = LUSTRE_EOF;
3001                                         else
3002                                                 lsa->lsa_comp_end = node->cy_valueint;
3003                                 } else if (!strcmp(string, "stripe_count")) {
3004                                         lsa->lsa_stripe_count = node->cy_valueint;
3005                                 } else if (!strcmp(string, "stripe_size")) {
3006                                         lsa->lsa_stripe_size = node->cy_valueint;
3007                                 } else if (!strcmp(string, "extension_size")) {
3008                                         lsa->lsa_extension_size = node->cy_valueint;
3009                                         lsa->lsa_extension_comp = true;
3010                                 } else if (!strcmp(string, "stripe_offset")) {
3011                                         lsa->lsa_stripe_off = node->cy_valueint;
3012                                 } else if (!strcmp(string, "l_ost_idx")) {
3013                                         osts[lsa->lsa_nr_tgts] = node->cy_valueint;
3014                                         lsa->lsa_nr_tgts++;
3015                                 }
3016                         }
3017                 }
3018                 node = node->cy_next;
3019         }
3020
3021         if (prevp == &prev) {
3022                 rc = build_prev_component(layout, prevp, lsa, true);
3023                 if (rc)
3024                         return rc;
3025
3026                 if (!(lsa->lsa_comp_flags & LCME_FL_EXTENSION))
3027                         rc = build_component(layout, lsa, *layout != NULL);
3028         }
3029
3030         return rc;
3031 }
3032
3033 static int lfs_comp_create_from_yaml(char *template,
3034                                      struct llapi_layout **layout,
3035                                      struct lfs_setstripe_args *lsa,
3036                                      __u32 *osts)
3037 {
3038         struct cYAML *tree = NULL, *err_rc = NULL;
3039         int rc = 0;
3040
3041         tree = cYAML_build_tree(template, NULL, 0, &err_rc, false);
3042         if (!tree) {
3043                 fprintf(stderr, "%s: cannot parse YAML file %s\n",
3044                         progname, template);
3045                 cYAML_build_error(-EINVAL, -1, "yaml", "from comp yaml",
3046                                   "can't parse", &err_rc);
3047                 cYAML_print_tree2file(stderr, err_rc);
3048                 cYAML_free_tree(err_rc);
3049                 rc = -EINVAL;
3050                 goto err;
3051         }
3052
3053         /* initialize lsa for plain file */
3054         setstripe_args_init(lsa);
3055         lsa->lsa_tgts = osts;
3056
3057         rc = build_layout_from_yaml_node(tree, layout, lsa, NULL);
3058         if (rc) {
3059                 fprintf(stderr, "%s: cannot build layout from YAML file %s.\n",
3060                         progname, template);
3061                 goto err;
3062         }
3063         /* clean clean lsa */
3064         setstripe_args_init(lsa);
3065
3066 err:
3067         if (tree)
3068                 cYAML_free_tree(tree);
3069         return rc;
3070 }
3071
3072 /**
3073  * Get the extension size from the next (SEL) component and extend the
3074  * current component on it. The start of the next component is to be
3075  * adjusted as well.
3076  *
3077  * \param[in] layout    the current layout
3078  * \param[in] start     the start of the current component
3079  * \param[in,out] end   the end of the current component
3080  * \param[in] offset    the offset to adjust the end position to instead of
3081  *                      extension size
3082  *
3083  * \retval 0            - extended successfully
3084  * \retval < 0          - error
3085  */
3086 static int layout_extend_comp(struct llapi_layout *layout,
3087                               uint64_t start, uint64_t *end,
3088                               uint64_t offset)
3089 {
3090         uint64_t size, next_start, next_end;
3091         int rc;
3092
3093         rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_NEXT);
3094         if (rc < 0) {
3095                 fprintf(stderr,
3096                         "%s setstripe: cannot move component cursor: %s\n",
3097                         progname, strerror(errno));
3098                 return rc;
3099         }
3100
3101         /*
3102          * Even if the @size will not be used below, this will fail if
3103          * this is not a SEL component - a good confirmation we are
3104          * working on right components.
3105          */
3106         rc = llapi_layout_extension_size_get(layout, &size);
3107         if (rc < 0) {
3108                 fprintf(stderr,
3109                         "%s setstripe: cannot get component ext size: %s\n",
3110                         progname, strerror(errno));
3111                 return rc;
3112         }
3113
3114         rc = llapi_layout_comp_extent_get(layout, &next_start, &next_end);
3115         if (rc) {
3116                 fprintf(stderr, "%s setstripe: cannot get extent: %s\n",
3117                         progname, strerror(errno));
3118                 return rc;
3119         }
3120
3121         next_start += offset ?: size;
3122         rc = llapi_layout_comp_extent_set(layout, next_start, next_end);
3123         if (rc) {
3124                 fprintf(stderr, "%s setstripe: cannot set extent: %s\n",
3125                         progname, strerror(errno));
3126                 return rc;
3127         }
3128
3129         rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_PREV);
3130         if (rc < 0) {
3131                 fprintf(stderr,
3132                         "%s setstripe: cannot move component cursor: %s\n",
3133                         progname, strerror(errno));
3134                 return rc;
3135         }
3136
3137         *end += offset ?: size;
3138         rc = llapi_layout_comp_extent_set(layout, start, *end);
3139         if (rc) {
3140                 fprintf(stderr, "%s setstripe: cannot set extent: %s\n",
3141                         progname, strerror(errno));
3142                 return rc;
3143         }
3144
3145         return 0;
3146 }
3147
3148 /**
3149  * In 'lfs setstripe --component-add' mode, we need to fetch the extent
3150  * end of the last component in the existing file, and adjust the
3151  * first extent start of the components to be added accordingly.
3152  *
3153  * In the create mode, we need to check if the first component is an extendable
3154  * SEL component and extend its length to the extension size (first component
3155  * of the PFL file is initialised at the create time, cannot be 0-lenght.
3156  */
3157 static int layout_adjust_first_extent(char *fname, struct llapi_layout *layout,
3158                                       bool comp_add)
3159 {
3160         struct llapi_layout *head;
3161         uint64_t start = 0, prev_end = 0;
3162         uint64_t end;
3163         int rc, ret = 0;
3164
3165         if (!layout || !(comp_add || llapi_layout_is_composite(layout)))
3166                 return 0;
3167
3168         errno = 0;
3169         while (comp_add) {
3170                 head = llapi_layout_get_by_path(fname, 0);
3171                 if (!head) {
3172                         fprintf(stderr,
3173                                 "%s setstripe: cannot read layout from '%s': %s\n",
3174                                 progname, fname, strerror(errno));
3175                         return -EINVAL;
3176                 } else if (errno == ENODATA) {
3177                         /*
3178                          * file without LOVEA, this component-add will be turned
3179                          * into a component-create.
3180                          */
3181                         llapi_layout_free(head);
3182                         ret = -ENODATA;
3183
3184                         /*
3185                          * the new layout will be added to an empty one, it
3186                          * still needs to be adjusted below
3187                          */
3188                         comp_add = 0;
3189                         break;
3190                 } else if (!llapi_layout_is_composite(head)) {
3191                         fprintf(stderr,
3192                                 "%s setstripe: '%s' not a composite file\n",
3193                                 progname, fname);
3194                         llapi_layout_free(head);
3195                         return -EINVAL;
3196                 }
3197
3198                 rc = llapi_layout_comp_extent_get(head, &start, &prev_end);
3199                 if (rc) {
3200                         fprintf(stderr,
3201                                 "%s setstripe: cannot get prev extent: %s\n",
3202                                 progname, strerror(errno));
3203                         llapi_layout_free(head);
3204                         return rc;
3205                 }
3206
3207                 llapi_layout_free(head);
3208                 break;
3209         }
3210
3211         /* Make sure we use the first component of the layout to be added. */
3212         rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_FIRST);
3213         if (rc < 0) {
3214                 fprintf(stderr,
3215                         "%s setstripe: cannot move component cursor: %s\n",
3216                         progname, strerror(errno));
3217                 return rc;
3218         }
3219
3220         rc = llapi_layout_comp_extent_get(layout, &start, &end);
3221         if (rc) {
3222                 fprintf(stderr, "%s setstripe: cannot get extent: %s\n",
3223                         progname, strerror(errno));
3224                 return rc;
3225         }
3226
3227         if (start == 0 && end == 0) {
3228                 rc = layout_extend_comp(layout, start, &end,
3229                                         comp_add ? prev_end : 0);
3230                 if (rc)
3231                         return rc;
3232         }
3233
3234         if (start > prev_end || end < prev_end) {
3235                 fprintf(stderr,
3236                         "%s setstripe: first extent [%lu, %lu) not adjacent with extent end %lu\n",
3237                         progname, start, end, prev_end);
3238                 return -EINVAL;
3239         }
3240
3241         rc = llapi_layout_comp_extent_set(layout, prev_end, end);
3242         if (rc) {
3243                 fprintf(stderr,
3244                         "%s setstripe: cannot set component extent [%lu, %lu): %s\n",
3245                         progname, prev_end, end, strerror(errno));
3246                 return rc;
3247         }
3248
3249         return ret;
3250 }
3251
3252 static int mirror_adjust_first_extents(struct mirror_args *list)
3253 {
3254         int rc = 0;
3255
3256         if (!list)
3257                 return 0;
3258
3259         while (list) {
3260                 rc = layout_adjust_first_extent(NULL, list->m_layout, false);
3261                 if (rc)
3262                         break;
3263                 list = list->m_next;
3264         }
3265
3266         return rc;
3267 }
3268
3269 static inline bool arg_is_eof(char *arg)
3270 {
3271         return !strncmp(arg, "-1", strlen("-1")) ||
3272                !strncmp(arg, "EOF", strlen("EOF")) ||
3273                !strncmp(arg, "eof", strlen("eof"));
3274 }
3275
3276 /**
3277  * lfs_mirror_alloc() - Allocate a mirror argument structure.
3278  *
3279  * Return: Valid mirror_args pointer on success and
3280  *         NULL if memory allocation fails.
3281  */
3282 static struct mirror_args *lfs_mirror_alloc(void)
3283 {
3284         struct mirror_args *mirror = NULL;
3285
3286         while (1) {
3287                 mirror = calloc(1, sizeof(*mirror));
3288                 if (mirror) {
3289                         mirror->m_inherit = false;
3290                         break;
3291                 }
3292
3293                 sleep(1);
3294         }
3295
3296         return mirror;
3297 }
3298
3299 /**
3300  * lfs_mirror_free() - Free memory allocated for a mirror argument
3301  *                     structure.
3302  * @mirror: Previously allocated mirror argument structure by
3303  *          lfs_mirror_alloc().
3304  *
3305  * Free memory allocated for @mirror.
3306  *
3307  * Return: void.
3308  */
3309 static void lfs_mirror_free(struct mirror_args *mirror)
3310 {
3311         if (mirror->m_layout)
3312                 llapi_layout_free(mirror->m_layout);
3313         free(mirror);
3314 }
3315
3316 /**
3317  * lfs_mirror_list_free() - Free memory allocated for a mirror list.
3318  * @mirror_list: Previously allocated mirror list.
3319  *
3320  * Free memory allocated for @mirror_list.
3321  *
3322  * Return: void.
3323  */
3324 static void lfs_mirror_list_free(struct mirror_args *mirror_list)
3325 {
3326         struct mirror_args *next_mirror = NULL;
3327
3328         while (mirror_list) {
3329                 next_mirror = mirror_list->m_next;
3330                 lfs_mirror_free(mirror_list);
3331                 mirror_list = next_mirror;
3332         }
3333 }
3334
3335 enum {
3336         LFS_SETQUOTA_DELETE = 1,
3337         LFS_POOL_OPT = 3,
3338         LFS_COMP_COUNT_OPT,
3339         LFS_COMP_START_OPT,
3340         LFS_COMP_FLAGS_OPT,
3341         LFS_COMP_DEL_OPT,
3342         LFS_COMP_SET_OPT,
3343         LFS_COMP_ADD_OPT,
3344         LFS_COMP_NO_VERIFY_OPT,
3345         LFS_PROJID_OPT,
3346         LFS_LAYOUT_FLAGS_OPT, /* used for mirror and foreign flags */
3347         LFS_MIRROR_ID_OPT,
3348         LFS_MIRROR_STATE_OPT,
3349         LFS_LAYOUT_COPY,
3350         LFS_MIRROR_INDEX_OPT,
3351         LFS_LAYOUT_FOREIGN_OPT,
3352         LFS_MODE_OPT,
3353         LFS_NEWERXY_OPT,
3354         LFS_INHERIT_RR_OPT,
3355         LFS_FIND_PERM,
3356         LFS_PRINTF_OPT,
3357 };
3358
3359 #ifndef LCME_USER_MIRROR_FLAGS
3360 /* The mirror flags can be set by users at creation time. */
3361 #define LCME_USER_MIRROR_FLAGS  (LCME_FL_PREF_RW)
3362 #endif
3363
3364 /* functions */
3365 static int lfs_setstripe_internal(int argc, char **argv,
3366                                   enum setstripe_origin opc)
3367 {
3368         struct lfs_setstripe_args        lsa = { 0 };
3369         struct llapi_stripe_param       *param = NULL;
3370         struct find_param                migrate_mdt_param = {
3371                 .fp_max_depth = -1,
3372                 .fp_mdt_index = -1,
3373         };
3374         char                            *fname;
3375         int                              result = 0;
3376         int                              result2 = 0;
3377         char                            *end;
3378         int                              c;
3379         int                              delete = 0;
3380         unsigned long long               size_units = 1;
3381         bool                             migrate_mode = false;
3382         bool                             migrate_mdt_mode = false;
3383         bool                             setstripe_mode = false;
3384         bool                             migration_block = false;
3385         __u64                            migration_flags = 0;
3386         __u32                            tgts[LOV_MAX_STRIPE_COUNT] = { 0 };
3387         int                              comp_del = 0, comp_set = 0;
3388         int                              comp_add = 0;
3389         __u32                            comp_id = 0;
3390         struct llapi_layout             *layout = NULL;
3391         struct llapi_layout             **lpp = &layout;
3392         bool                             mirror_mode = false;
3393         bool                             has_m_file = false;
3394         __u32                            mirror_count = 0;
3395         enum mirror_flags                mirror_flags = 0;
3396         struct mirror_args              *mirror_list = NULL;
3397         struct mirror_args              *new_mirror = NULL;
3398         struct mirror_args              *last_mirror = NULL;
3399         __u16                            mirror_id = 0;
3400         char                             cmd[PATH_MAX];
3401         bool from_yaml = false;
3402         bool from_copy = false;
3403         char *template = NULL;
3404         bool foreign_mode = false;
3405         char *xattr = NULL;
3406         uint32_t type = LU_FOREIGN_TYPE_NONE, flags = 0;
3407         char *mode_opt = NULL;
3408         mode_t previous_umask = 0;
3409         mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
3410
3411         struct option long_opts[] = {
3412 /* find { .val = '0',   .name = "null",         .has_arg = no_argument }, */
3413 /* find { .val = 'A',   .name = "atime",        .has_arg = required_argument }*/
3414         /* --block is only valid in migrate mode */
3415         { .val = 'b',   .name = "block",        .has_arg = no_argument },
3416 /* find { .val = 'B',   .name = "btime",        .has_arg = required_argument }*/
3417         { .val = LFS_COMP_ADD_OPT,
3418                         .name = "comp-add",     .has_arg = no_argument },
3419         { .val = LFS_COMP_ADD_OPT,
3420                         .name = "component-add", .has_arg = no_argument },
3421         { .val = LFS_COMP_DEL_OPT,
3422                         .name = "comp-del",     .has_arg = no_argument },
3423         { .val = LFS_COMP_DEL_OPT,
3424                         .name = "component-del", .has_arg = no_argument },
3425         { .val = LFS_COMP_FLAGS_OPT,
3426                         .name = "comp-flags",   .has_arg = required_argument },
3427         { .val = LFS_COMP_FLAGS_OPT,
3428                         .name = "component-flags",
3429                                                 .has_arg = required_argument },
3430         { .val = LFS_COMP_SET_OPT,
3431                         .name = "comp-set",     .has_arg = no_argument },
3432         { .val = LFS_COMP_SET_OPT,
3433                         .name = "component-set",
3434                                                 .has_arg = no_argument},
3435         { .val = LFS_COMP_NO_VERIFY_OPT,
3436                         .name = "no-verify",    .has_arg = no_argument},
3437         { .val = LFS_LAYOUT_FLAGS_OPT,
3438                         .name = "flags",        .has_arg = required_argument},
3439         { .val = LFS_LAYOUT_FOREIGN_OPT,
3440                         .name = "foreign",      .has_arg = optional_argument},
3441         { .val = LFS_MIRROR_ID_OPT,
3442                         .name = "mirror-id",    .has_arg = required_argument},
3443         { .val = LFS_MODE_OPT,
3444                         .name = "mode",         .has_arg = required_argument},
3445         { .val = LFS_LAYOUT_COPY,
3446                         .name = "copy",         .has_arg = required_argument},
3447         { .val = 'c',   .name = "stripe-count", .has_arg = required_argument},
3448         { .val = 'c',   .name = "stripe_count", .has_arg = required_argument},
3449         { .val = 'c',   .name = "mdt-count",    .has_arg = required_argument},
3450         { .val = 'C',   .name = "overstripe-count",
3451                                                 .has_arg = required_argument},
3452         { .val = 'd',   .name = "delete",       .has_arg = no_argument},
3453         { .val = 'd',   .name = "destroy",      .has_arg = no_argument},
3454         /* used with "lfs migrate -m" */
3455         { .val = 'd',   .name = "directory",    .has_arg = no_argument},
3456         /* --non-direct is only valid in migrate mode */
3457         { .val = 'D',   .name = "non-direct",   .has_arg = no_argument },
3458         { .val = 'E',   .name = "comp-end",     .has_arg = required_argument},
3459         { .val = 'E',   .name = "component-end",
3460                                                 .has_arg = required_argument},
3461         { .val = 'f',   .name = "file",         .has_arg = required_argument },
3462 /* find { .val = 'F',   .name = "fid",          .has_arg = no_argument }, */
3463 /* find { .val = 'g',   .name = "gid",          .has_arg = no_argument }, */
3464 /* find { .val = 'G',   .name = "group",        .has_arg = required_argument }*/
3465         { .val = 'h',   .name = "help",         .has_arg = no_argument },
3466         { .val = 'H',   .name = "mdt-hash",     .has_arg = required_argument},
3467         { .val = 'i',   .name = "stripe-index", .has_arg = required_argument},
3468         { .val = 'i',   .name = "stripe_index", .has_arg = required_argument},
3469         { .val = 'I',   .name = "comp-id",      .has_arg = required_argument},
3470         { .val = 'I',   .name = "component-id", .has_arg = required_argument},
3471 /* find { .val = 'l',   .name = "lazy",         .has_arg = no_argument }, */
3472         { .val = 'L',   .name = "layout",       .has_arg = required_argument },
3473         { .val = 'm',   .name = "mdt",          .has_arg = required_argument},
3474         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument},
3475         { .val = 'm',   .name = "mdt_index",    .has_arg = required_argument},
3476         /* --non-block is only valid in migrate mode */
3477         { .val = 'n',   .name = "non-block",    .has_arg = no_argument },
3478         { .val = 'N',   .name = "mirror-count", .has_arg = optional_argument},
3479         { .val = 'o',   .name = "ost",          .has_arg = required_argument },
3480 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
3481         { .val = 'o',   .name = "ost-list",     .has_arg = required_argument },
3482         { .val = 'o',   .name = "ost_list",     .has_arg = required_argument },
3483 #endif
3484         { .val = 'p',   .name = "pool",         .has_arg = required_argument },
3485 /* find { .val = 'P',   .name = "print",        .has_arg = no_argument }, */
3486 /* getstripe { .val = 'q', .name = "quiet",     .has_arg = no_argument }, */
3487 /* getstripe { .val = 'R', .name = "raw",       .has_arg = no_argument }, */
3488         { .val = 'S',   .name = "stripe-size",  .has_arg = required_argument },
3489         { .val = 'S',   .name = "stripe_size",  .has_arg = required_argument },
3490 /* find { .val = 't',   .name = "type",         .has_arg = required_argument }*/
3491 /* dirstripe { .val = 'T', .name = "mdt-count", .has_arg = required_argument }*/
3492 /* find { .val = 'u',   .name = "uid",          .has_arg = required_argument }*/
3493 /* find { .val = 'U',   .name = "user",         .has_arg = required_argument }*/
3494         /* --verbose is only valid in migrate mode */
3495         { .val = 'v',   .name = "verbose",      .has_arg = no_argument},
3496         { .val = 'x',   .name = "xattr",        .has_arg = required_argument },
3497 /* dirstripe { .val = 'X',.name = "max-inherit",.has_arg = required_argument }*/
3498         { .val = 'y',   .name = "yaml",         .has_arg = required_argument },
3499         { .val = 'z',   .name = "ext-size",     .has_arg = required_argument},
3500         { .val = 'z',   .name = "extension-size", .has_arg = required_argument},
3501         { .name = NULL } };
3502
3503         setstripe_args_init(&lsa);
3504
3505         migrate_mode = (opc == SO_MIGRATE);
3506         mirror_mode = (opc == SO_MIRROR_CREATE || opc == SO_MIRROR_EXTEND);
3507         setstripe_mode = (opc == SO_SETSTRIPE);
3508         if (opc == SO_MIRROR_DELETE) {
3509                 delete = 1;
3510                 mirror_flags = MF_DESTROY;
3511         }
3512
3513         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
3514         progname = cmd;
3515         while ((c = getopt_long(argc, argv,
3516                                 "bc:C:dDE:f:hH:i:I:m:N::no:p:L:s:S:vx:y:z:",
3517                                 long_opts, NULL)) >= 0) {
3518                 size_units = 1;
3519                 switch (c) {
3520                 case 0:
3521                         /* Long options. */
3522                         break;
3523                 case LFS_COMP_ADD_OPT:
3524                         comp_add = 1;
3525                         break;
3526                 case LFS_COMP_DEL_OPT:
3527                         comp_del = 1;
3528                         break;
3529                 case LFS_COMP_FLAGS_OPT:
3530                         result = comp_str2flags(optarg, &lsa.lsa_comp_flags,
3531                                                 &lsa.lsa_comp_neg_flags);
3532                         if (result != 0)
3533                                 goto usage_error;
3534                         if (mirror_mode && lsa.lsa_comp_neg_flags) {
3535                                 fprintf(stderr,
3536                                         "%s: inverted flags are not supported\n",
3537                                         progname);
3538                                 goto usage_error;
3539                         }
3540                         break;
3541                 case LFS_COMP_SET_OPT:
3542                         comp_set = 1;
3543                         break;
3544                 case LFS_COMP_NO_VERIFY_OPT:
3545                         mirror_flags |= MF_NO_VERIFY;
3546                         break;
3547                 case LFS_MIRROR_ID_OPT: {
3548                         unsigned long int id;
3549
3550                         errno = 0;
3551                         id = strtoul(optarg, &end, 0);
3552                         if (errno != 0 || *end != '\0' || id == 0 ||
3553                             id > UINT16_MAX) {
3554                                 fprintf(stderr,
3555                                         "%s %s: invalid mirror ID '%s'\n",
3556                                         progname, argv[0], optarg);
3557                                 goto usage_error;
3558                         }
3559
3560                         mirror_id = (__u16)id;
3561                         break;
3562                 }
3563                 case LFS_LAYOUT_FLAGS_OPT: {
3564                         uint32_t neg_flags;
3565
3566                         /* check for numeric flags (foreign and mirror cases) */
3567                         if (setstripe_mode && !mirror_mode && !last_mirror) {
3568                                 errno = 0;
3569                                 flags = strtoul(optarg, &end, 16);
3570                                 if (errno != 0 || *end != '\0' ||
3571                                     flags >= UINT32_MAX) {
3572                                         fprintf(stderr,
3573                                                 "%s %s: invalid hex flags '%s'\n",
3574                                                 progname, argv[0], optarg);
3575                                         return CMD_HELP;
3576                                 }
3577                                 if (!foreign_mode) {
3578                                         fprintf(stderr,
3579                                                 "%s %s: hex flags must be specified with --foreign option\n",
3580                                                 progname, argv[0]);
3581                                         return CMD_HELP;
3582                                 }
3583                                 break;
3584                         }
3585
3586                         if (!mirror_mode || !last_mirror) {
3587                                 fprintf(stderr,
3588                                         "error: %s: --flags must be specified with --mirror-count|-N option\n",
3589                                         progname);
3590                                 goto usage_error;
3591                         }
3592
3593                         result = comp_str2flags(optarg, &last_mirror->m_flags,
3594                                                 &neg_flags);
3595                         if (result != 0)
3596                                 goto usage_error;
3597
3598                         if (neg_flags) {
3599                                 fprintf(stderr,
3600                                         "%s: inverted flags are not supported\n",
3601                                         progname);
3602                                 result = -EINVAL;
3603                                 goto usage_error;
3604                         }
3605                         if (last_mirror->m_flags & ~LCME_USER_MIRROR_FLAGS) {
3606                                 fprintf(stderr,
3607                                         "%s: unsupported mirror flags: %s\n",
3608                                         progname, optarg);
3609                                 result = -EINVAL;
3610                                 goto error;
3611                         }
3612                         break;
3613                 }
3614                 case LFS_LAYOUT_FOREIGN_OPT:
3615                         if (optarg) {
3616                                 /* check pure numeric */
3617                                 type = strtoul(optarg, &end, 0);
3618                                 if (*end) {
3619                                         /* check name */
3620                                         type = check_foreign_type_name(optarg);
3621                                         if (type == LU_FOREIGN_TYPE_UNKNOWN) {
3622                                                 fprintf(stderr,
3623                                                         "%s %s: unrecognized foreign type '%s'\n",
3624                                                         progname, argv[0],
3625                                                         optarg);
3626                                                 return CMD_HELP;
3627                                         }
3628                                 } else if (type >= UINT32_MAX) {
3629                                         fprintf(stderr,
3630                                                 "%s %s: invalid foreign type '%s'\n",
3631                                                 progname, argv[0], optarg);
3632                                         return CMD_HELP;
3633                                 }
3634                         }
3635                         foreign_mode = true;
3636                         break;
3637                 case LFS_MODE_OPT:
3638                         mode_opt = optarg;
3639                         if (mode_opt) {
3640                                 mode = strtoul(mode_opt, &end, 8);
3641                                 if (*end != '\0') {
3642                                         fprintf(stderr,
3643                                                 "%s %s: bad mode '%s'\n",
3644                                                 progname, argv[0], mode_opt);
3645                                         return CMD_HELP;
3646                                 }
3647                                 previous_umask = umask(0);
3648                         }
3649                         break;
3650                 case LFS_LAYOUT_COPY:
3651                         from_copy = true;
3652                         template = optarg;
3653                         break;
3654                 case 'b':
3655                         if (!migrate_mode) {
3656                                 fprintf(stderr,
3657                                         "%s %s: -b|--block valid only for migrate command\n",
3658                                         progname, argv[0]);
3659                                 goto usage_error;
3660                         }
3661                         migration_block = true;
3662                         break;
3663                 case 'C':
3664                         if (lsa.lsa_pattern == LLAPI_LAYOUT_MDT) {
3665                                 fprintf(stderr,
3666                                         "%s %s: -C|--overstripe-count incompatible with DoM layout\n",
3667                                         progname, argv[0]);
3668                                 goto usage_error;
3669                         }
3670                         lsa.lsa_pattern = LLAPI_LAYOUT_OVERSTRIPING;
3671                         fallthrough;
3672                 case 'c':
3673                         errno = 0;
3674                         lsa.lsa_stripe_count = strtoul(optarg, &end, 0);
3675                         if (errno != 0 || *end != '\0'|| optarg == end ||
3676                             lsa.lsa_stripe_count < -1 ||
3677                             lsa.lsa_stripe_count > LOV_MAX_STRIPE_COUNT) {
3678                                 fprintf(stderr,
3679                                         "%s %s: invalid stripe count '%s'\n",
3680                                         progname, argv[0], optarg);
3681                                 goto usage_error;
3682                         }
3683
3684                         if (lsa.lsa_stripe_count == -1)
3685                                 lsa.lsa_stripe_count = LLAPI_LAYOUT_WIDE;
3686                         break;
3687                 case 'd':
3688                         if (migrate_mode) {
3689                                 migrate_mdt_param.fp_max_depth = 1;
3690                         } else {
3691                                 /* delete the default striping pattern */
3692                                 delete = 1;
3693                                 if (opc == SO_MIRROR_SPLIT) {
3694                                         if (has_m_file) {
3695                                                 fprintf(stderr,
3696                                                       "%s %s: -d cannot used with -f\n",
3697                                                         progname, argv[0]);
3698                                                 goto usage_error;
3699                                         }
3700                                         mirror_flags |= MF_DESTROY;
3701                                 }
3702                         }
3703                         break;
3704                 case 'D':
3705                         if (!migrate_mode) {
3706                                 fprintf(stderr,
3707                                         "%s %s: -D|--non-direct is valid only for migrate command\n",
3708                                         progname, argv[0]);
3709                                 goto usage_error;
3710                         }
3711                         migration_flags |= LLAPI_MIGRATION_NONDIRECT;
3712                         break;
3713                 case 'E':
3714                         if (lsa.lsa_comp_end != 0) {
3715                                 result = comp_args_to_layout(lpp, &lsa, true);
3716                                 if (result) {
3717                                         fprintf(stderr, "%s: invalid layout\n",
3718                                                 progname);
3719                                         goto usage_error;
3720                                 }
3721
3722                                 setstripe_args_init_inherit(&lsa);
3723                         }
3724
3725                         if (arg_is_eof(optarg)) {
3726                                 lsa.lsa_comp_end = LUSTRE_EOF;
3727                         } else {
3728                                 result = llapi_parse_size(optarg,
3729                                                           &lsa.lsa_comp_end,
3730                                                           &size_units, 0);
3731                                 /* assume units of KB if too small */
3732                                 if (lsa.lsa_comp_end < 4096)
3733                                         lsa.lsa_comp_end *= 1024;
3734                                 if (result ||
3735                                     lsa.lsa_comp_end & (LOV_MIN_STRIPE_SIZE - 1)) {
3736                                         fprintf(stderr,
3737                                                 "%s %s: invalid component end '%s'\n",
3738                                                 progname, argv[0], optarg);
3739                                         goto usage_error;
3740                                 }
3741                         }
3742                         break;
3743                 case 'H':
3744                         if (!migrate_mode) {
3745                                 fprintf(stderr,
3746                                         "--mdt-hash is valid only for migrate command\n");
3747                                 return CMD_HELP;
3748                         }
3749
3750                         lsa.lsa_pattern = check_hashtype(optarg);
3751                         if (lsa.lsa_pattern == 0) {
3752                                 fprintf(stderr,
3753                                         "%s %s: bad stripe hash type '%s'\n",
3754                                         progname, argv[0], optarg);
3755                                 return CMD_HELP;
3756                         }
3757                         break;
3758                 case 'i':
3759                         errno = 0;
3760                         lsa.lsa_stripe_off = strtol(optarg, &end, 0);
3761                         if (errno != 0 || *end != '\0' || optarg == end ||
3762                             lsa.lsa_stripe_off < -1 ||
3763                             lsa.lsa_stripe_off > LOV_V1_INSANE_STRIPE_COUNT) {
3764                                 fprintf(stderr,
3765                                         "%s %s: invalid stripe offset '%s'\n",
3766                                         progname, argv[0], optarg);
3767                                 goto usage_error;
3768                         }
3769                         if (lsa.lsa_stripe_off == -1)
3770                                 lsa.lsa_stripe_off = LLAPI_LAYOUT_DEFAULT;
3771                         break;
3772                 case 'I':
3773                         comp_id = strtoul(optarg, &end, 0);
3774                         if (*end != '\0' || comp_id == 0 ||
3775                             comp_id > LCME_ID_MAX) {
3776                                 fprintf(stderr,
3777                                         "%s %s: invalid component ID '%s'\n",
3778                                         progname, argv[0], optarg);
3779                                 goto usage_error;
3780                         }
3781                         break;
3782                 case 'f':
3783                         if (opc != SO_MIRROR_EXTEND && opc != SO_MIRROR_SPLIT) {
3784                                 fprintf(stderr,
3785                                         "error: %s: invalid option: %s\n",
3786                                         progname, argv[optopt + 1]);
3787                                 goto usage_error;
3788                         }
3789                         if (opc == SO_MIRROR_EXTEND) {
3790                                 if (!last_mirror) {
3791                                         fprintf(stderr,
3792                                 "error: %s: '-N' must exist in front of '%s'\n",
3793                                                 progname, argv[optopt + 1]);
3794                                         goto usage_error;
3795                                 }
3796                                 last_mirror->m_file = optarg;
3797                                 last_mirror->m_count = 1;
3798                         } else {
3799                                 /* mirror split */
3800                                 if (!mirror_list)
3801                                         mirror_list = lfs_mirror_alloc();
3802                                 mirror_list->m_file = optarg;
3803                         }
3804                         has_m_file = true;
3805                         break;
3806                 case 'L':
3807                         if (strcmp(argv[optind - 1], "mdt") == 0) {
3808                                 /* Can be only the first component */
3809                                 if (layout) {
3810                                         result = -EINVAL;
3811                                         fprintf(stderr,
3812                                                 "error: 'mdt' layout can be only the first one\n");
3813                                         goto error;
3814                                 }
3815                                 if (lsa.lsa_comp_end > (1ULL << 30)) { /* 1Gb */
3816                                         result = -EFBIG;
3817                                         fprintf(stderr,
3818                                                 "error: 'mdt' layout size is too big\n");
3819                                         goto error;
3820                                 }
3821                                 lsa.lsa_pattern = LLAPI_LAYOUT_MDT;
3822                                 lsa.lsa_stripe_size = LLAPI_LAYOUT_DEFAULT;
3823                         } else if (strcmp(argv[optind - 1], "raid0") != 0) {
3824                                 result = -EINVAL;
3825                                 fprintf(stderr,
3826                                         "error: layout '%s' is unknown, supported layouts are: 'mdt', 'raid0'\n",
3827                                         argv[optind]);
3828                                 goto error;
3829                         }
3830                         break;
3831                 case 'm':
3832                         if (!migrate_mode) {
3833                                 fprintf(stderr,
3834                                         "%s %s: -m|--mdt-index is valid only for migrate command\n",
3835                                         progname, argv[0]);
3836                                 goto usage_error;
3837                         }
3838                         migrate_mdt_mode = true;
3839                         lsa.lsa_nr_tgts = parse_targets(tgts,
3840                                                 sizeof(tgts) / sizeof(__u32),
3841                                                 lsa.lsa_nr_tgts, optarg, NULL);
3842                         if (lsa.lsa_nr_tgts < 0) {
3843                                 fprintf(stderr,
3844                                         "%s: invalid MDT target(s) '%s'\n",
3845                                         progname, optarg);
3846                                 goto usage_error;
3847                         }
3848
3849                         lsa.lsa_tgts = tgts;
3850                         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
3851                                 lsa.lsa_stripe_off = tgts[0];
3852                         break;
3853                 case 'n':
3854                         if (!migrate_mode) {
3855                                 fprintf(stderr,
3856                                         "%s %s: -n|--non-block valid only for migrate command\n",
3857                                         progname, argv[0]);
3858                                 goto usage_error;
3859                         }
3860                         migration_flags |= LLAPI_MIGRATION_NONBLOCK;
3861                         break;
3862                 case 'N':
3863                         if (opc == SO_SETSTRIPE) {
3864                                 opc = SO_MIRROR_CREATE;
3865                                 mirror_mode = true;
3866                         }
3867                         mirror_count = 1;
3868                         if (optarg) {
3869                                 errno = 0;
3870                                 mirror_count = strtoul(optarg, &end, 0);
3871                                 if (errno != 0 || *end != '\0' ||
3872                                     mirror_count == 0 ||
3873                                     mirror_count > LUSTRE_MIRROR_COUNT_MAX) {
3874                                         fprintf(stderr,
3875                                                 "error: %s: bad mirror count: %s\n",
3876                                                 progname, optarg);
3877                                         result = -EINVAL;
3878                                         goto error;
3879                                 }
3880                         }
3881
3882                         new_mirror = lfs_mirror_alloc();
3883                         new_mirror->m_count = mirror_count;
3884
3885                         if (!mirror_list)
3886                                 mirror_list = new_mirror;
3887
3888                         if (last_mirror) {
3889                                 /* wrap up last mirror */
3890                                 if (!setstripe_args_specified(&lsa))
3891                                         last_mirror->m_inherit = true;
3892                                 if (lsa.lsa_comp_end == 0)
3893                                         lsa.lsa_comp_end = LUSTRE_EOF;
3894
3895                                 result = comp_args_to_layout(lpp, &lsa, true);
3896                                 if (result) {
3897                                         lfs_mirror_free(new_mirror);
3898                                         goto error;
3899                                 }
3900
3901                                 setstripe_args_init_inherit(&lsa);
3902
3903                                 last_mirror->m_next = new_mirror;
3904                         }
3905
3906                         last_mirror = new_mirror;
3907                         lpp = &last_mirror->m_layout;
3908                         break;
3909                 case 'o':
3910 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
3911                         if (strcmp(argv[optind - 1], "--ost-list") == 0)
3912                                 fprintf(stderr,
3913                                         "warning: '--ost-list' is deprecated, use '--ost' instead\n");
3914 #endif
3915                         if (lsa.lsa_pattern == LLAPI_LAYOUT_MDT) {
3916                                 fprintf(stderr,
3917                                         "%s %s: -o|--ost incompatible with DoM layout\n",
3918                                         progname, argv[0]);
3919                                 goto usage_error;
3920                         }
3921                         /*
3922                          * -o allows overstriping, and must note it because
3923                          * parse_targets is shared with MDT striping, which
3924                          * does not allow duplicates
3925                          */
3926                         lsa.lsa_pattern = LLAPI_LAYOUT_OVERSTRIPING;
3927                         lsa.lsa_nr_tgts = parse_targets(tgts,
3928                                                 sizeof(tgts) / sizeof(__u32),
3929                                                 lsa.lsa_nr_tgts, optarg,
3930                                                 &lsa.lsa_pattern);
3931                         if (lsa.lsa_nr_tgts < 0) {
3932                                 fprintf(stderr,
3933                                         "%s %s: invalid OST target(s) '%s'\n",
3934                                         progname, argv[0], optarg);
3935                                 goto usage_error;
3936                         }
3937
3938                         lsa.lsa_tgts = tgts;
3939                         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
3940                                 lsa.lsa_stripe_off = tgts[0];
3941                         break;
3942                 case 'p':
3943                         if (!optarg)
3944                                 goto usage_error;
3945
3946                         if (optarg[0] == '\0' || lov_pool_is_inherited(optarg))
3947                                 lsa.lsa_pool_name = NULL;
3948                         else
3949                                 lsa.lsa_pool_name = optarg;
3950                         break;
3951                 case 'S':
3952                         result = llapi_parse_size(optarg, &lsa.lsa_stripe_size,
3953                                                   &size_units, 0);
3954                         /* assume units of KB if too small to be valid */
3955                         if (lsa.lsa_stripe_size < 4096)
3956                                 lsa.lsa_stripe_size *= 1024;
3957                         if (result ||
3958                             lsa.lsa_stripe_size & (LOV_MIN_STRIPE_SIZE - 1)) {
3959                                 fprintf(stderr,
3960                                         "%s %s: invalid stripe size '%s'\n",
3961                                         progname, argv[0], optarg);
3962                                 goto usage_error;
3963                         }
3964                         break;
3965                 case 'v':
3966                         if (!migrate_mode) {
3967                                 fprintf(stderr,
3968                                         "%s %s: -v|--verbose valid only for migrate command\n",
3969                                         progname, argv[0]);
3970                                 goto usage_error;
3971                         }
3972                         migrate_mdt_param.fp_verbose = VERBOSE_DETAIL;
3973                         migration_flags = LLAPI_MIGRATION_VERBOSE;
3974                         break;
3975                 case 'x':
3976                         xattr = optarg;
3977                         break;
3978                 case 'y':
3979                         from_yaml = true;
3980                         template = optarg;
3981                         break;
3982                 case 'z':
3983                         result = llapi_parse_size(optarg,
3984                                                   &lsa.lsa_extension_size,
3985                                                   &size_units, 0);
3986                         if (result) {
3987                                 fprintf(stderr,
3988                                         "%s %s: invalid extension size '%s'\n",
3989                                         progname, argv[0], optarg);
3990                                 goto usage_error;
3991                         }
3992
3993                         lsa.lsa_extension_comp = true;
3994                         break;
3995                 default:
3996                         fprintf(stderr, "%s: unrecognized option '%s'\n",
3997                                 progname, argv[optind - 1]);
3998                 case 'h':
3999                         goto usage_error;
4000                 }
4001         }
4002
4003         fname = argv[optind];
4004
4005         if (optind == argc) {
4006                 fprintf(stderr, "%s %s: FILE must be specified\n",
4007                         progname, argv[0]);
4008                 goto usage_error;
4009         }
4010
4011         /* lfs migrate $filename should keep the file's layout by default */
4012         if (migrate_mode && !layout && !from_yaml &&
4013             !setstripe_args_specified(&lsa) && !lsa.lsa_pool_name)
4014                 from_copy = true;
4015
4016         if (xattr && !foreign_mode) {
4017                 /*
4018                  * only print a warning as this is harmless and will be ignored
4019                  */
4020                 fprintf(stderr,
4021                         "%s %s: xattr has been specified for non-foreign layout\n",
4022                         progname, argv[0]);
4023         } else if (foreign_mode && !xattr) {
4024                 fprintf(stderr,
4025                         "%s %s: xattr must be provided in foreign mode\n",
4026                         progname, argv[0]);
4027                 goto usage_error;
4028         }
4029
4030         if (foreign_mode && (!setstripe_mode || comp_add | comp_del ||
4031             comp_set || comp_id || delete || from_copy ||
4032             setstripe_args_specified(&lsa) || lsa.lsa_nr_tgts ||
4033             lsa.lsa_tgts)) {
4034                 fprintf(stderr,
4035                         "%s %s: only --xattr/--flags/--mode options are valid with --foreign\n",
4036                         progname, argv[0]);
4037                 return CMD_HELP;
4038         }
4039
4040         if (mirror_mode && mirror_count == 0) {
4041                 fprintf(stderr,
4042                         "error: %s: --mirror-count|-N option is required\n",
4043                         progname);
4044                 result = -EINVAL;
4045                 goto error;
4046         }
4047
4048         if (mirror_mode) {
4049                 if (!setstripe_args_specified(&lsa))
4050                         last_mirror->m_inherit = true;
4051                 if (lsa.lsa_comp_end == 0)
4052                         lsa.lsa_comp_end = LUSTRE_EOF;
4053         }
4054
4055         if (lsa.lsa_comp_end != 0) {
4056                 result = comp_args_to_layout(lpp, &lsa, true);
4057                 if (result) {
4058                         fprintf(stderr, "error: %s: invalid layout\n",
4059                                 progname);
4060                         result = -EINVAL;
4061                         goto error;
4062                 }
4063         }
4064
4065         if (mirror_flags & MF_NO_VERIFY) {
4066                 if (opc != SO_MIRROR_EXTEND) {
4067                         fprintf(stderr,
4068                                 "error: %s: --no-verify is valid only for lfs mirror extend command\n",
4069                                 progname);
4070                         result = -EINVAL;
4071                         goto error;
4072                 } else if (!has_m_file) {
4073                         fprintf(stderr,
4074                                 "error: %s: --no-verify must be specified with -f <victim_file> option\n",
4075                                 progname);
4076                         result = -EINVAL;
4077                         goto error;
4078                 }
4079         }
4080
4081         if (comp_set && !comp_id && !lsa.lsa_pool_name) {
4082                 fprintf(stderr,
4083                         "%s %s: --component-set doesn't have component-id set\n",
4084                         progname, argv[0]);
4085                 goto usage_error;
4086         }
4087
4088         if ((delete + comp_set + comp_del + comp_add) > 1) {
4089                 fprintf(stderr,
4090                         "%s %s: options --component-set, --component-del, --component-add and -d are mutually exclusive\n",
4091                         progname, argv[0]);
4092                 goto usage_error;
4093         }
4094
4095         if (delete && (setstripe_args_specified(&lsa) || comp_id != 0 ||
4096                        lsa.lsa_comp_flags != 0 || layout != NULL)) {
4097                 fprintf(stderr,
4098                         "%s %s: option -d is mutually exclusive with -s, -c, -o, -p, -I, -F and -E options\n",
4099                         progname, argv[0]);
4100                 goto usage_error;
4101         }
4102
4103         if ((comp_set || comp_del) &&
4104             (setstripe_args_specified(&lsa) || layout != NULL)) {
4105                 fprintf(stderr,
4106                         "%s %s: options --component-del and --component-set are mutually exclusive when used with -c, -E, -o, -p, or -s\n",
4107                         progname, argv[0]);
4108                 goto usage_error;
4109         }
4110
4111         if (comp_del && comp_id != 0 && lsa.lsa_comp_flags != 0) {
4112                 fprintf(stderr,
4113                         "%s %s: options -I and -F are mutually exclusive when used with --component-del\n",
4114                         progname, argv[0]);
4115                 goto usage_error;
4116         }
4117
4118         if (comp_add || comp_del) {
4119                 struct stat st;
4120
4121                 result = lstat(fname, &st);
4122                 if (result == 0 && S_ISDIR(st.st_mode)) {
4123                         fprintf(stderr,
4124                                 "%s setstripe: cannot use --component-add or --component-del for directory\n",
4125                                 progname);
4126                         goto usage_error;
4127                 }
4128
4129                 if (mirror_mode) {
4130                         fprintf(stderr,
4131                                 "error: %s: can't use --component-add or --component-del for mirror operation\n",
4132                                 progname);
4133                         goto usage_error;
4134                 }
4135         }
4136
4137         if (comp_add) {
4138                 if (!layout) {
4139                         fprintf(stderr,
4140                                 "%s %s: option -E must be specified with --component-add\n",
4141                                 progname, argv[0]);
4142                         goto usage_error;
4143                 }
4144         }
4145
4146         if (from_yaml && from_copy) {
4147                 fprintf(stderr,
4148                         "%s: can't specify --yaml and --copy together\n",
4149                         progname);
4150                 goto error;
4151         }
4152
4153         if ((from_yaml || from_copy) &&
4154             (setstripe_args_specified(&lsa) || layout != NULL)) {
4155                 fprintf(stderr,
4156                         "error: %s: can't specify --yaml or --copy with -c, -S, -i, -o, -p or -E options.\n",
4157                         argv[0]);
4158                 goto error;
4159         }
4160
4161         if ((migration_flags & LLAPI_MIGRATION_NONBLOCK) && migration_block) {
4162                 fprintf(stderr,
4163                         "%s %s: options --non-block and --block are mutually exclusive\n",
4164                         progname, argv[0]);
4165                 goto usage_error;
4166         }
4167
4168         if (!comp_del && !comp_set && opc != SO_MIRROR_SPLIT &&
4169             opc != SO_MIRROR_DELETE && comp_id != 0) {
4170                 fprintf(stderr,
4171                         "%s: option -I can only be used with --component-del or --component-set or lfs mirror split\n",
4172                         progname);
4173                 goto usage_error;
4174         }
4175
4176         if (migrate_mdt_mode) {
4177                 struct lmv_user_md *lmu;
4178
4179                 /* initialize migrate mdt parameters */
4180                 lmu = calloc(1, lmv_user_md_size(lsa.lsa_nr_tgts,
4181                                                  LMV_USER_MAGIC_SPECIFIC));
4182                 if (!lmu) {
4183                         fprintf(stderr,
4184                                 "%s %s: cannot allocate memory for lmv_user_md: %s\n",
4185                                 progname, argv[0], strerror(ENOMEM));
4186                         result = -ENOMEM;
4187                         goto error;
4188                 }
4189                 if (lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT)
4190                         lmu->lum_stripe_count = lsa.lsa_stripe_count;
4191                 if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT) {
4192                         fprintf(stderr,
4193                                 "%s %s: migrate should specify MDT index\n",
4194                                 progname, argv[0]);
4195                         free(lmu);
4196                         goto usage_error;
4197                 }
4198                 lmu->lum_stripe_offset = lsa.lsa_stripe_off;
4199                 if (lsa.lsa_pattern != LLAPI_LAYOUT_RAID0)
4200                         lmu->lum_hash_type = lsa.lsa_pattern;
4201                 else
4202                         lmu->lum_hash_type = LMV_HASH_TYPE_UNKNOWN;
4203                 if (lsa.lsa_pool_name) {
4204                         strncpy(lmu->lum_pool_name, lsa.lsa_pool_name,
4205                                 sizeof(lmu->lum_pool_name) - 1);
4206                         lmu->lum_pool_name[sizeof(lmu->lum_pool_name) - 1] = 0;
4207                 }
4208                 if (lsa.lsa_nr_tgts > 1) {
4209                         int i;
4210
4211                         if (lsa.lsa_stripe_count > 0 &&
4212                             lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT &&
4213                             lsa.lsa_stripe_count != lsa.lsa_nr_tgts) {
4214                                 fprintf(stderr,
4215                                         "error: %s: stripe count %lld doesn't match the number of MDTs: %d\n",
4216                                         progname, lsa.lsa_stripe_count,
4217                                         lsa.lsa_nr_tgts);
4218                                 free(lmu);
4219                                 goto usage_error;
4220                         }
4221
4222                         lmu->lum_magic = LMV_USER_MAGIC_SPECIFIC;
4223                         lmu->lum_stripe_count = lsa.lsa_nr_tgts;
4224                         for (i = 0; i < lsa.lsa_nr_tgts; i++)
4225                                 lmu->lum_objects[i].lum_mds = lsa.lsa_tgts[i];
4226                 } else {
4227                         lmu->lum_magic = LMV_USER_MAGIC;
4228                 }
4229
4230                 migrate_mdt_param.fp_lmv_md = lmu;
4231                 migrate_mdt_param.fp_migrate = 1;
4232         } else if (!layout) {
4233                 if (lsa_args_stripe_count_check(&lsa))
4234                         goto usage_error;
4235
4236                 /* initialize stripe parameters */
4237                 param = calloc(1, offsetof(typeof(*param),
4238                                lsp_osts[lsa.lsa_nr_tgts]));
4239                 if (!param) {
4240                         fprintf(stderr,
4241                                 "%s %s: cannot allocate memory for parameters: %s\n",
4242                                 progname, argv[0], strerror(ENOMEM));
4243                         result = -ENOMEM;
4244                         goto error;
4245                 }
4246
4247                 if (lsa.lsa_stripe_size != LLAPI_LAYOUT_DEFAULT)
4248                         param->lsp_stripe_size = lsa.lsa_stripe_size;
4249                 if (lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT) {
4250                         if (lsa.lsa_stripe_count == LLAPI_LAYOUT_WIDE)
4251                                 param->lsp_stripe_count = -1;
4252                         else
4253                                 param->lsp_stripe_count = lsa.lsa_stripe_count;
4254                 }
4255                 if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
4256                         param->lsp_stripe_offset = -1;
4257                 else
4258                         param->lsp_stripe_offset = lsa.lsa_stripe_off;
4259                 param->lsp_stripe_pattern =
4260                                 llapi_pattern_to_lov(lsa.lsa_pattern);
4261                 if (param->lsp_stripe_pattern == EINVAL) {
4262                         fprintf(stderr, "error: %s: invalid stripe pattern\n",
4263                                 argv[0]);
4264                         free(param);
4265                         goto usage_error;
4266                 }
4267                 param->lsp_pool = lsa.lsa_pool_name;
4268                 param->lsp_is_specific = false;
4269
4270                 if (lsa.lsa_nr_tgts > 0) {
4271                         param->lsp_is_specific = true;
4272                         param->lsp_stripe_count = lsa.lsa_nr_tgts;
4273                         memcpy(param->lsp_osts, tgts,
4274                                sizeof(*tgts) * lsa.lsa_nr_tgts);
4275                 }
4276         }
4277
4278         if (from_yaml) {
4279                 /* generate a layout from a YAML template */
4280                 result = lfs_comp_create_from_yaml(template, &layout,
4281                                                    &lsa, tgts);
4282                 if (result) {
4283                         fprintf(stderr,
4284                                 "error: %s: can't create composite layout from template file %s\n",
4285                                 argv[0], template);
4286                         goto error;
4287                 }
4288         }
4289
4290         if (layout != NULL || mirror_list != NULL) {
4291                 if (mirror_list)
4292                         result = mirror_adjust_first_extents(mirror_list);
4293                 else
4294                         result = layout_adjust_first_extent(fname, layout,
4295                                                             comp_add);
4296                 if (result == -ENODATA)
4297                         comp_add = 0;
4298                 else if (result != 0) {
4299                         fprintf(stderr, "error: %s: invalid layout\n",
4300                                 progname);
4301                         goto error;
4302                 }
4303         }
4304
4305         for (fname = argv[optind]; fname != NULL; fname = argv[++optind]) {
4306                 if (from_copy) {
4307                         layout = llapi_layout_get_by_path(template ?: fname, 0);
4308                         if (!layout) {
4309                                 fprintf(stderr,
4310                                         "%s: can't create composite layout from file %s: %s\n",
4311                                         progname, template ?: fname,
4312                                         strerror(errno));
4313                                 result = -errno;
4314                                 goto error;
4315                         }
4316                 }
4317
4318                 if (migrate_mdt_mode) {
4319                         result = llapi_migrate_mdt(fname, &migrate_mdt_param);
4320                 } else if (migrate_mode) {
4321                         result = lfs_migrate(fname, migration_flags, param,
4322                                              layout);
4323                 } else if (comp_set != 0) {
4324                         result = lfs_component_set(fname, comp_id,
4325                                                    lsa.lsa_pool_name,
4326                                                    lsa.lsa_comp_flags,
4327                                                    lsa.lsa_comp_neg_flags);
4328                 } else if (comp_del != 0) {
4329                         result = lfs_component_del(fname, comp_id,
4330                                                    lsa.lsa_comp_flags,
4331                                                    lsa.lsa_comp_neg_flags);
4332                 } else if (comp_add != 0) {
4333                         result = lfs_component_add(fname, layout);
4334                 } else if (opc == SO_MIRROR_CREATE) {
4335                         result = mirror_create(fname, mirror_list);
4336                 } else if (opc == SO_MIRROR_EXTEND) {
4337                         result = mirror_extend(fname, mirror_list,
4338                                                mirror_flags);
4339                 } else if (opc == SO_MIRROR_SPLIT || opc == SO_MIRROR_DELETE) {
4340                         if (!mirror_id && !comp_id && !lsa.lsa_pool_name) {
4341                                 fprintf(stderr,
4342                                         "%s: no mirror id, component id, or pool name specified to delete from '%s'\n",
4343                                         progname, fname);
4344                                 goto usage_error;
4345                         }
4346                         if (lsa.lsa_pool_name)
4347                                 mirror_flags |= MF_COMP_POOL;
4348                         else if (mirror_id != 0)
4349                                 comp_id = mirror_id;
4350                         else
4351                                 mirror_flags |= MF_COMP_ID;
4352                         if (has_m_file && !strcmp(fname, mirror_list->m_file)) {
4353                                 fprintf(stderr,
4354                                         "%s: the file specified by -f cannot be same as the source file '%s'\n",
4355                                         progname, fname);
4356                                 goto usage_error;
4357                         }
4358                         result = mirror_split(fname, comp_id, lsa.lsa_pool_name,
4359                                               mirror_flags,
4360                                               has_m_file ? mirror_list->m_file :
4361                                               NULL);
4362                 } else if (layout) {
4363                         result = lfs_component_create(fname, O_CREAT | O_WRONLY,
4364                                                       mode, layout);
4365                         if (result >= 0) {
4366                                 close(result);
4367                                 result = 0;
4368                         }
4369                 } else if (foreign_mode) {
4370                         result = llapi_file_create_foreign(fname, mode, type,
4371                                                            flags, xattr);
4372                         if (result >= 0) {
4373                                 close(result);
4374                                 result = 0;
4375                         }
4376                 } else {
4377                         result = llapi_file_open_param(fname,
4378                                                        O_CREAT | O_WRONLY,
4379                                                        mode, param);
4380                         if (result >= 0) {
4381                                 close(result);
4382                                 result = 0;
4383                         }
4384                 }
4385                 if (result) {
4386                         /* Save the first error encountered. */
4387                         if (result2 == 0)
4388                                 result2 = result;
4389                         continue;
4390                 }
4391         }
4392
4393         if (mode_opt)
4394                 umask(previous_umask);
4395
4396         free(param);
4397         free(migrate_mdt_param.fp_lmv_md);
4398         llapi_layout_free(layout);
4399         lfs_mirror_list_free(mirror_list);
4400         return result2;
4401 usage_error:
4402         result = CMD_HELP;
4403 error:
4404         llapi_layout_free(layout);
4405         lfs_mirror_list_free(mirror_list);
4406         return result;
4407 }
4408
4409 static int lfs_poollist(int argc, char **argv)
4410 {
4411         if (argc != 2)
4412                 return CMD_HELP;
4413
4414         return llapi_poollist(argv[1]);
4415 }
4416
4417 #define FP_DEFAULT_TIME_MARGIN (24 * 60 * 60)
4418 static time_t set_time(struct find_param *param, time_t *time, time_t *set,
4419                        char *str)
4420 {
4421         long long t = 0;
4422         int sign = 0;
4423         char *endptr = "AD";
4424         char *timebuf;
4425
4426         if (str[0] == '+')
4427                 sign = 1;
4428         else if (str[0] == '-')
4429                 sign = -1;
4430
4431         if (sign)
4432                 str++;
4433
4434         for (timebuf = str; *endptr && *(endptr + 1); timebuf = endptr + 1) {
4435                 long long val = strtoll(timebuf, &endptr, 0);
4436                 int unit = 1;
4437
4438                 switch (*endptr) {
4439                 case  'y':
4440                         unit *= 52; /* 52 weeks + 1 day below */
4441                         fallthrough;
4442                 case  'w':
4443                         unit *= 7;
4444                         if (param->fp_time_margin == FP_DEFAULT_TIME_MARGIN)
4445                                 param->fp_time_margin *= (1 + unit / 52);
4446                         unit += (*endptr == 'y'); /* +1 day for 365 days/year */
4447                         fallthrough;
4448                 case '\0': /* days are default unit if none used */
4449                         fallthrough;
4450                 case  'd':
4451                         unit *= 24;
4452                         fallthrough;
4453                 case  'h':
4454                         unit *= 60;
4455                         fallthrough;
4456                 case  'm':
4457                         unit *= 60;
4458                         fallthrough;
4459                 case  's':
4460                         break;
4461                         /* don't need to multiply by 1 for seconds */
4462                 default:
4463                         fprintf(stderr,
4464                                 "%s find: bad time string '%s': %s\n",
4465                                 progname, timebuf, strerror(EINVAL));
4466                         return LONG_MAX;
4467                 }
4468
4469                 if (param->fp_time_margin == 0 ||
4470                     (*endptr && unit < param->fp_time_margin))
4471                         param->fp_time_margin = unit;
4472
4473                 t += val * unit;
4474         }
4475         if (*time < t) {
4476                 if (sign != 0)
4477                         str--;
4478                 fprintf(stderr, "%s find: bad time '%s': too large\n",
4479                         progname, str);
4480                 return LONG_MAX;
4481         }
4482
4483         *set = *time - t;
4484
4485         return sign;
4486 }
4487
4488 static int str2quotaid(__u32 *id, const char *arg)
4489 {
4490         unsigned long int projid_tmp = 0;
4491         char *endptr = NULL;
4492
4493         projid_tmp = strtoul(arg, &endptr, 10);
4494         if (*endptr != '\0')
4495                 return -EINVAL;
4496         /* UINT32_MAX is not allowed - see projid_valid()/INVALID_PROJID */
4497         if (projid_tmp >= UINT32_MAX)
4498                 return -ERANGE;
4499
4500         *id = projid_tmp;
4501         return 0;
4502 }
4503
4504 static int name2uid(unsigned int *id, const char *name)
4505 {
4506         struct passwd *passwd;
4507
4508         passwd = getpwnam(name);
4509         if (!passwd)
4510                 return -ENOENT;
4511         *id = passwd->pw_uid;
4512
4513         return 0;
4514 }
4515
4516 static int name2gid(unsigned int *id, const char *name)
4517 {
4518         struct group *group;
4519
4520         group = getgrnam(name);
4521         if (!group)
4522                 return -ENOENT;
4523         *id = group->gr_gid;
4524
4525         return 0;
4526 }
4527
4528 static inline int name2projid(unsigned int *id, const char *name)
4529 {
4530         return -ENOTSUP;
4531 }
4532
4533 static int uid2name(char **name, unsigned int id)
4534 {
4535         struct passwd *passwd;
4536
4537         passwd = getpwuid(id);
4538         if (!passwd)
4539                 return -ENOENT;
4540         *name = passwd->pw_name;
4541
4542         return 0;
4543 }
4544
4545 static inline int gid2name(char **name, unsigned int id)
4546 {
4547         struct group *group;
4548
4549         group = getgrgid(id);
4550         if (!group)
4551                 return -ENOENT;
4552         *name = group->gr_name;
4553
4554         return 0;
4555 }
4556
4557 static int name2layout(__u32 *layout, char *name)
4558 {
4559         char *ptr, *layout_name;
4560
4561         *layout = 0;
4562         for (ptr = name; ; ptr = NULL) {
4563                 layout_name = strtok(ptr, ",");
4564                 if (!layout_name)
4565                         break;
4566                 if (strcmp(layout_name, "released") == 0)
4567                         *layout |= LOV_PATTERN_F_RELEASED;
4568                 else if (strcmp(layout_name, "raid0") == 0)
4569                         *layout |= LOV_PATTERN_RAID0;
4570                 else if (strcmp(layout_name, "mdt") == 0)
4571                         *layout |= LOV_PATTERN_MDT;
4572                 else if (strcmp(layout_name, "overstriping") == 0)
4573                         *layout |= LOV_PATTERN_OVERSTRIPING;
4574                 else
4575                         return -1;
4576         }
4577         return 0;
4578 }
4579
4580 static int parse_symbolic(const char *input, mode_t *outmode, const char **end)
4581 {
4582         int loop;
4583         int user, group, other;
4584         int who, all;
4585         char c, op;
4586         mode_t perm;
4587         mode_t usermask;
4588         mode_t previous_flags;
4589
4590         user = group = other = 0;
4591         all = 0;
4592         loop = 1;
4593         perm = 0;
4594         previous_flags = 0;
4595         *end = input;
4596         usermask = 0;
4597
4598         while (loop) {
4599                 switch (*input) {
4600                 case 'u':
4601                         user = 1;
4602                         break;
4603                 case 'g':
4604                         group = 1;
4605                         break;
4606                 case 'o':
4607                         other = 1;
4608                         break;
4609                 case 'a':
4610                         user = group = other = 1;
4611                         all = 1;
4612                         break;
4613                 default:
4614                         loop = 0;
4615                 }
4616
4617                 if (loop)
4618                         input++;
4619         }
4620
4621         who = user || group || other;
4622         if (!who) {
4623                 /* get the umask */
4624                 usermask = umask(0022);
4625                 umask(usermask);
4626                 usermask &= 07777;
4627         }
4628
4629         if (*input == '-' || *input == '+' || *input == '=')
4630                 op = *input++;
4631         else
4632                 /* operation is required */
4633                 return -1;
4634
4635         /* get the flags in *outmode */
4636         switch (*input) {
4637         case 'u':
4638                 previous_flags = (*outmode & 0700);
4639                 perm |= user  ? previous_flags : 0;
4640                 perm |= group ? (previous_flags >> 3) : 0;
4641                 perm |= other ? (previous_flags >> 6) : 0;
4642                 input++;
4643                 goto write_perm;
4644         case 'g':
4645                 previous_flags = (*outmode & 0070);
4646                 perm |= user  ? (previous_flags << 3) : 0;
4647                 perm |= group ? previous_flags : 0;
4648                 perm |= other ? (previous_flags >> 3) : 0;
4649                 input++;
4650                 goto write_perm;
4651         case 'o':
4652                 previous_flags = (*outmode & 0007);
4653                 perm |= user  ? (previous_flags << 6) : 0;
4654                 perm |= group ? (previous_flags << 3) : 0;
4655                 perm |= other ? previous_flags : 0;
4656                 input++;
4657                 goto write_perm;
4658         default:
4659                 break;
4660         }
4661
4662         /* this part is optional,
4663          * if empty perm = 0 and *outmode is not modified
4664          */
4665         loop = 1;
4666         while (loop) {
4667                 c = *input;
4668                 switch (c) {
4669                 case 'r':
4670                         perm |= user  ? 0400 : 0;
4671                         perm |= group ? 0040 : 0;
4672                         perm |= other ? 0004 : 0;
4673                         /* set read permission for uog except for umask's
4674                          * permissions
4675                          */
4676                         perm |= who   ? 0 : (0444 & ~usermask);
4677                         break;
4678                 case 'w':
4679                         perm |= user  ? 0200 : 0;
4680                         perm |= group ? 0020 : 0;
4681                         perm |= other ? 0002 : 0;
4682                         /* set write permission for uog except for umask'
4683                          * permissions
4684                          */
4685                         perm |= who   ? 0 : (0222 & ~usermask);
4686                         break;
4687                 case 'x':
4688                         perm |= user  ? 0100 : 0;
4689                         perm |= group ? 0010 : 0;
4690                         perm |= other ? 0001 : 0;
4691                         /* set execute permission for uog except for umask'
4692                          * permissions
4693                          */
4694                         perm |= who   ? 0 : (0111 & ~usermask);
4695                         break;
4696                 case 'X':
4697                         /*
4698                          * Adds execute permission to 'u', 'g' and/or 'g' if
4699                          * specified and either 'u', 'g' or 'o' already has
4700                          * execute permissions.
4701                          */
4702                         if ((*outmode & 0111) != 0) {
4703                                 perm |= user  ? 0100 : 0;
4704                                 perm |= group ? 0010 : 0;
4705                                 perm |= other ? 0001 : 0;
4706                                 perm |= !who  ? 0111 : 0;
4707                         }
4708                         break;
4709                 case 's':
4710                         /* s is ignored if o is given, but it's not an error */
4711                         if (other && !group && !user)
4712                                 break;
4713                         perm |= user  ? S_ISUID : 0;
4714                         perm |= group ? S_ISGID : 0;
4715                         break;
4716                 case 't':
4717                         /* 't' should be used when 'a' is given
4718                          * or who is empty
4719                          */
4720                         perm |= (!who || all) ? S_ISVTX : 0;
4721                         /* using ugo with t is not an error */
4722                         break;
4723                 default:
4724                         loop = 0;
4725                         break;
4726                 }
4727                 if (loop)
4728                         input++;
4729         }
4730
4731 write_perm:
4732         /* uog flags should be only one character long */
4733         if (previous_flags && (*input != '\0' && *input != ','))
4734                 return -1;
4735
4736         switch (op) {
4737         case '-':
4738                 /* remove the flags from outmode */
4739                 *outmode &= ~perm;
4740                 break;
4741         case '+':
4742                 /* add the flags to outmode */
4743                 *outmode |= perm;
4744                 break;
4745         case '=':
4746                 /* set the flags of outmode to perm */
4747                 if (perm != 0)
4748                         *outmode = perm;
4749                 break;
4750         }
4751
4752         *end = input;
4753         return 0;
4754 }
4755
4756 static int str2mode_t(const char *input, mode_t *outmode)
4757 {
4758         int ret;
4759         const char *iter;
4760
4761         ret = 0;
4762
4763         if (*input >= '0' && *input <= '7') {
4764                 /* parse octal representation */
4765                 char *end;
4766
4767                 iter = input;
4768
4769                 /* look for invalid digits in octal representation */
4770                 while (isdigit(*iter))
4771                         if (*iter++ > '7')
4772                                 return -1;
4773
4774                 errno = 0;
4775                 *outmode = strtoul(input, &end, 8);
4776
4777                 if (errno != 0 || *outmode > 07777) {
4778                         *outmode = 0;
4779                         ret = -1;
4780                 }
4781
4782         } else if (*input == '8' || *input == '9') {
4783                 /* error: invalid octal number */
4784                 ret = -1;
4785         } else {
4786                 /* parse coma seperated list of symbolic representation */
4787                 int rc;
4788                 const char *end;
4789
4790                 *outmode = 0;
4791                 rc = 0;
4792                 end = NULL;
4793
4794                 do {
4795                         rc = parse_symbolic(input, outmode, &end);
4796                         if (rc)
4797                                 return -1;
4798
4799                         input = end+1;
4800                 } while (*end == ',');
4801
4802                 if (*end != '\0')
4803                         ret = -1;
4804         }
4805         return ret;
4806 }
4807
4808 static int lfs_find(int argc, char **argv)
4809 {
4810         int c, rc;
4811         int ret = 0;
4812         time_t t;
4813         struct find_param param = {
4814                 .fp_max_depth = -1,
4815                 .fp_quiet = 1,
4816                 .fp_time_margin = FP_DEFAULT_TIME_MARGIN,
4817         };
4818         struct option long_opts[] = {
4819         { .val = 'A',   .name = "atime",        .has_arg = required_argument },
4820         { .val = 'b',   .name = "blocks",       .has_arg = required_argument },
4821         { .val = 'B',   .name = "btime",        .has_arg = required_argument },
4822         { .val = 'B',   .name = "Btime",        .has_arg = required_argument },
4823         { .val = LFS_COMP_COUNT_OPT,
4824                         .name = "comp-count",   .has_arg = required_argument },
4825         { .val = LFS_COMP_COUNT_OPT,
4826                         .name = "component-count",
4827                                                 .has_arg = required_argument },
4828         { .val = LFS_COMP_FLAGS_OPT,
4829                         .name = "comp-flags",   .has_arg = required_argument },
4830         { .val = LFS_COMP_FLAGS_OPT,
4831                         .name = "component-flags",
4832                                                 .has_arg = required_argument },
4833         { .val = LFS_COMP_START_OPT,
4834                         .name = "comp-start",   .has_arg = required_argument },
4835         { .val = LFS_COMP_START_OPT,
4836                         .name = "component-start",
4837                                                 .has_arg = required_argument },
4838         { .val = LFS_MIRROR_STATE_OPT,
4839                         .name = "mirror-state", .has_arg = required_argument },
4840         { .val = LFS_NEWERXY_OPT,
4841                         .name = "newer",        .has_arg = required_argument},
4842         { .val = LFS_NEWERXY_OPT,
4843                         .name = "neweraa",      .has_arg = required_argument},
4844         { .val = LFS_NEWERXY_OPT,
4845                         .name = "neweram",      .has_arg = required_argument},
4846         { .val = LFS_NEWERXY_OPT,
4847                         .name = "newerac",      .has_arg = required_argument},
4848         { .val = LFS_NEWERXY_OPT,
4849                         .name = "newerab",      .has_arg = required_argument},
4850         { .val = LFS_NEWERXY_OPT,
4851                         .name = "newerma",      .has_arg = required_argument},
4852         { .val = LFS_NEWERXY_OPT,
4853                         .name = "newermm",      .has_arg = required_argument},
4854         { .val = LFS_NEWERXY_OPT,
4855                         .name = "newermc",      .has_arg = required_argument},
4856         { .val = LFS_NEWERXY_OPT,
4857                         .name = "newermb",      .has_arg = required_argument},
4858         { .val = LFS_NEWERXY_OPT,
4859                         .name = "newerca",      .has_arg = required_argument},
4860         { .val = LFS_NEWERXY_OPT,
4861                         .name = "newercm",      .has_arg = required_argument},
4862         { .val = LFS_NEWERXY_OPT,
4863                         .name = "newercc",      .has_arg = required_argument},
4864         { .val = LFS_NEWERXY_OPT,
4865                         .name = "newercb",      .has_arg = required_argument},
4866         { .val = LFS_NEWERXY_OPT,
4867                         .name = "newerba",      .has_arg = required_argument},
4868         { .val = LFS_NEWERXY_OPT,
4869                         .name = "newerbm",      .has_arg = required_argument},
4870         { .val = LFS_NEWERXY_OPT,
4871                         .name = "newerbc",      .has_arg = required_argument},
4872         { .val = LFS_NEWERXY_OPT,
4873                         .name = "newerbb",      .has_arg = required_argument},
4874         { .val = LFS_NEWERXY_OPT,
4875                         .name = "newerBa",      .has_arg = required_argument},
4876         { .val = LFS_NEWERXY_OPT,
4877                         .name = "newerBm",      .has_arg = required_argument},
4878         { .val = LFS_NEWERXY_OPT,
4879                         .name = "newerBc",      .has_arg = required_argument},
4880         { .val = LFS_NEWERXY_OPT,
4881                         .name = "newerBB",      .has_arg = required_argument},
4882         { .val = LFS_NEWERXY_OPT,
4883                         .name = "newerat",      .has_arg = required_argument},
4884         { .val = LFS_NEWERXY_OPT,
4885                         .name = "newermt",      .has_arg = required_argument},
4886         { .val = LFS_NEWERXY_OPT,
4887                         .name = "newerct",      .has_arg = required_argument},
4888         { .val = LFS_NEWERXY_OPT,
4889                         .name = "newerbt",      .has_arg = required_argument},
4890         { .val = LFS_NEWERXY_OPT,
4891                         .name = "newerBt",      .has_arg = required_argument},
4892         { .val = 'c',   .name = "stripe-count", .has_arg = required_argument },
4893         { .val = 'c',   .name = "stripe_count", .has_arg = required_argument },
4894         { .val = 'C',   .name = "ctime",        .has_arg = required_argument },
4895 /* getstripe { .val = 'd', .name = "directory", .has_arg = no_argument }, */
4896         { .val = 'D',   .name = "maxdepth",     .has_arg = required_argument },
4897         { .val = 'E',   .name = "comp-end",     .has_arg = required_argument },
4898         { .val = 'E',   .name = "component-end",
4899                                                 .has_arg = required_argument },
4900 /* find { .val = 'F',   .name = "fid",          .has_arg = no_argument }, */
4901         { .val = LFS_LAYOUT_FOREIGN_OPT,
4902                         .name = "foreign",      .has_arg = optional_argument},
4903         { .val = 'g',   .name = "gid",          .has_arg = required_argument },
4904         { .val = 'G',   .name = "group",        .has_arg = required_argument },
4905         { .val = 'h',   .name = "help",         .has_arg = no_argument },
4906         { .val = 'H',   .name = "mdt-hash",     .has_arg = required_argument },
4907         { .val = 'i',   .name = "stripe-index", .has_arg = required_argument },
4908         { .val = 'i',   .name = "stripe_index", .has_arg = required_argument },
4909 /* getstripe { .val = 'I', .name = "comp-id",   .has_arg = required_argument }*/
4910         { .val = 'l',   .name = "lazy",         .has_arg = no_argument },
4911         { .val = 'L',   .name = "layout",       .has_arg = required_argument },
4912         { .val = 'm',   .name = "mdt",          .has_arg = required_argument },
4913         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument },
4914         { .val = 'm',   .name = "mdt_index",    .has_arg = required_argument },
4915         { .val = 'M',   .name = "mtime",        .has_arg = required_argument },
4916         { .val = 'n',   .name = "name",         .has_arg = required_argument },
4917         { .val = 'N',   .name = "mirror-count", .has_arg = required_argument },
4918 /* find { .val = 'o'    .name = "or", .has_arg = no_argument }, like find(1) */
4919         { .val = 'O',   .name = "obd",          .has_arg = required_argument },
4920         { .val = 'O',   .name = "ost",          .has_arg = required_argument },
4921         { .val = LFS_FIND_PERM,
4922                         .name = "perm",         .has_arg = required_argument },
4923         /* no short option for pool yet, can be 'p' after 2.18 */
4924         { .val = LFS_POOL_OPT,
4925                         .name = "pool",         .has_arg = required_argument },
4926         { .val = '0',   .name = "print0",       .has_arg = no_argument },
4927         { .val = 'P',   .name = "print",        .has_arg = no_argument },
4928         { .val = LFS_PRINTF_OPT,
4929                         .name = "printf",       .has_arg = required_argument },
4930         { .val = LFS_PROJID_OPT,
4931                         .name = "projid",       .has_arg = required_argument },
4932 /* getstripe { .val = 'q', .name = "quiet",     .has_arg = no_argument }, */
4933 /* getstripe { .val = 'r', .name = "recursive", .has_arg = no_argument }, */
4934 /* getstripe { .val = 'R', .name = "raw",       .has_arg = no_argument }, */
4935         { .val = 's',   .name = "size",         .has_arg = required_argument },
4936         { .val = 'S',   .name = "stripe-size",  .has_arg = required_argument },
4937         { .val = 'S',   .name = "stripe_size",  .has_arg = required_argument },
4938         { .val = 't',   .name = "type",         .has_arg = required_argument },
4939         { .val = 'T',   .name = "mdt-count",    .has_arg = required_argument },
4940         { .val = 'u',   .name = "uid",          .has_arg = required_argument },
4941         { .val = 'U',   .name = "user",         .has_arg = required_argument },
4942 /* getstripe { .val = 'v', .name = "verbose",   .has_arg = no_argument }, */
4943         { .val = 'z',   .name = "extension-size",
4944                                                 .has_arg = required_argument },
4945         { .val = 'z',   .name = "ext-size",     .has_arg = required_argument },
4946         { .name = NULL } };
4947         int optidx = 0;
4948         int pathstart = -1;
4949         int pathend = -1;
4950         int pathbad = -1;
4951         int neg_opt = 0;
4952         time_t *xtime;
4953         int *xsign;
4954         int isoption;
4955         char *endptr;
4956
4957         time(&t);
4958
4959         /* when getopt_long_only() hits '!' it returns 1, puts "!" in optarg */
4960         while ((c = getopt_long_only(argc, argv,
4961                 "-0A:b:B:c:C:D:E:g:G:hH:i:L:m:M:n:N:O:Ppqrs:S:t:T:u:U:z:",
4962                 long_opts, &optidx)) >= 0) {
4963                 xtime = NULL;
4964                 xsign = NULL;
4965                 if (neg_opt)
4966                         --neg_opt;
4967                 /* '!' is part of option */
4968                 /*
4969                  * when getopt_long_only() finds a string which is not
4970                  * an option nor a known option argument it returns 1
4971                  * in that case if we already have found pathstart and pathend
4972                  * (i.e. we have the list of pathnames),
4973                  * the only supported value is "!"
4974                  */
4975                 isoption = (c != 1) || (strcmp(optarg, "!") == 0);
4976                 if (!isoption && pathend != -1) {
4977                         fprintf(stderr,
4978                                 "err: %s: filename|dirname must either precede options or follow options\n",
4979                                 argv[0]);
4980                         ret = CMD_HELP;
4981                         goto err;
4982                 }
4983                 if (!isoption && pathstart == -1)
4984                         pathstart = optind - 1;
4985                 if (isoption && pathstart != -1 && pathend == -1)
4986                         pathend = optind - 2;
4987                 switch (c) {
4988                 case 0:
4989                         /* Long options. */
4990                         break;
4991                 case 1:
4992                         /*
4993                          * unknown; opt is "!" or path component,
4994                          * checking done above.
4995                          */
4996                         if (strcmp(optarg, "!") == 0)
4997                                 neg_opt = 2;
4998                         break;
4999                 case 'A':
5000                         xtime = &param.fp_atime;
5001                         xsign = &param.fp_asign;
5002                         param.fp_exclude_atime = !!neg_opt;
5003                         /* no break, this falls through to 'B' for btime */
5004                         fallthrough;
5005                 case 'B':
5006                         if (c == 'B') {
5007                                 xtime = &param.fp_btime;
5008                                 xsign = &param.fp_bsign;
5009                                 param.fp_exclude_btime = !!neg_opt;
5010                         }
5011                         /* no break, this falls through to 'C' for ctime */
5012                         fallthrough;
5013                 case 'C':
5014                         if (c == 'C') {
5015                                 xtime = &param.fp_ctime;
5016                                 xsign = &param.fp_csign;
5017                                 param.fp_exclude_ctime = !!neg_opt;
5018                         }
5019                         /* no break, this falls through to 'M' for mtime */
5020                         fallthrough;
5021                 case 'M':
5022                         if (c == 'M') {
5023                                 xtime = &param.fp_mtime;
5024                                 xsign = &param.fp_msign;
5025                                 param.fp_exclude_mtime = !!neg_opt;
5026                         }
5027                         rc = set_time(&param, &t, xtime, optarg);
5028                         if (rc == LONG_MAX) {
5029                                 ret = -1;
5030                                 goto err;
5031                         }
5032                         if (rc)
5033                                 *xsign = rc;
5034                         break;
5035                 case 'b':
5036                         if (optarg[0] == '+') {
5037                                 param.fp_blocks_sign = -1;
5038                                 optarg++;
5039                         } else if (optarg[0] == '-') {
5040                                 param.fp_blocks_sign =  1;
5041                                 optarg++;
5042                         }
5043
5044                         param.fp_blocks_units = 1024;
5045                         ret = llapi_parse_size(optarg, &param.fp_blocks,
5046                                                &param.fp_blocks_units, 0);
5047                         if (ret) {
5048                                 fprintf(stderr, "error: bad blocks '%s'\n",
5049                                         optarg);
5050                                 goto err;
5051                         }
5052                         param.fp_check_blocks = 1;
5053                         param.fp_exclude_blocks = !!neg_opt;
5054                         break;
5055                 case LFS_COMP_COUNT_OPT:
5056                         if (optarg[0] == '+') {
5057                                 param.fp_comp_count_sign = -1;
5058                                 optarg++;
5059                         } else if (optarg[0] == '-') {
5060                                 param.fp_comp_count_sign =  1;
5061                                 optarg++;
5062                         }
5063
5064                         errno = 0;
5065                         param.fp_comp_count = strtoul(optarg, &endptr, 0);
5066                         if (errno != 0 || *endptr != '\0' ||
5067                             param.fp_comp_count > UINT32_MAX) {
5068                                 fprintf(stderr,
5069                                         "error: bad component count '%s'\n",
5070                                         optarg);
5071                                 goto err;
5072                         }
5073                         param.fp_check_comp_count = 1;
5074                         param.fp_exclude_comp_count = !!neg_opt;
5075                         break;
5076                 case LFS_COMP_FLAGS_OPT:
5077                         rc = comp_str2flags(optarg, &param.fp_comp_flags,
5078                                             &param.fp_comp_neg_flags);
5079                         if (rc) {
5080                                 fprintf(stderr,
5081                                         "error: bad component flags '%s'\n",
5082                                         optarg);
5083                                 goto err;
5084                         }
5085                         param.fp_check_comp_flags = 1;
5086                         if (neg_opt) {
5087                                 __u32 flags = param.fp_comp_neg_flags;
5088
5089                                 param.fp_comp_neg_flags = param.fp_comp_flags;
5090                                 param.fp_comp_flags = flags;
5091                         }
5092                         break;
5093                 case LFS_COMP_START_OPT:
5094                         if (optarg[0] == '+') {
5095                                 param.fp_comp_start_sign = -1;
5096                                 optarg++;
5097                         } else if (optarg[0] == '-') {
5098                                 param.fp_comp_start_sign =  1;
5099                                 optarg++;
5100                         }
5101
5102                         rc = llapi_parse_size(optarg, &param.fp_comp_start,
5103                                               &param.fp_comp_start_units, 0);
5104                         if (rc) {
5105                                 fprintf(stderr,
5106                                         "error: bad component start '%s'\n",
5107                                         optarg);
5108                                 goto err;
5109                         }
5110                         param.fp_check_comp_start = 1;
5111                         param.fp_exclude_comp_start = !!neg_opt;
5112                         break;
5113                 case LFS_MIRROR_STATE_OPT:
5114                         rc = mirror_str2state(optarg, &param.fp_mirror_state,
5115                                               &param.fp_mirror_neg_state);
5116                         if (rc) {
5117                                 fprintf(stderr,
5118                                         "error: bad mirrored file state '%s'\n",
5119                                         optarg);
5120                                 goto err;
5121                         }
5122                         param.fp_check_mirror_state = 1;
5123                         if (neg_opt) {
5124                                 __u16 state = param.fp_mirror_neg_state;
5125
5126                                 param.fp_mirror_neg_state =
5127                                         param.fp_mirror_state;
5128                                 param.fp_mirror_state = state;
5129                         }
5130                         break;
5131                 case 'c':
5132                         if (optarg[0] == '+') {
5133                                 param.fp_stripe_count_sign = -1;
5134                                 optarg++;
5135                         } else if (optarg[0] == '-') {
5136                                 param.fp_stripe_count_sign =  1;
5137                                 optarg++;
5138                         }
5139
5140                         errno = 0;
5141                         param.fp_stripe_count = strtoul(optarg, &endptr, 0);
5142                         if (errno != 0 || *endptr != '\0' ||
5143                             param.fp_stripe_count > LOV_MAX_STRIPE_COUNT) {
5144                                 fprintf(stderr,
5145                                         "error: bad stripe_count '%s'\n",
5146                                         optarg);
5147                                 ret = -1;
5148                                 goto err;
5149                         }
5150                         param.fp_check_stripe_count = 1;
5151                         param.fp_exclude_stripe_count = !!neg_opt;
5152                         break;
5153                 case 'D':
5154                         errno = 0;
5155                         param.fp_max_depth = strtol(optarg, 0, 0);
5156                         if (errno != 0 || param.fp_max_depth < 0) {
5157                                 fprintf(stderr,
5158                                         "error: bad maxdepth '%s'\n",
5159                                         optarg);
5160                                 ret = -1;
5161                                 goto err;
5162                         }
5163                         break;
5164                 case 'E':
5165                         if (optarg[0] == '+') {
5166                                 param.fp_comp_end_sign = -1;
5167                                 optarg++;
5168                         } else if (optarg[0] == '-') {
5169                                 param.fp_comp_end_sign =  1;
5170                                 optarg++;
5171                         }
5172
5173                         if (arg_is_eof(optarg)) {
5174                                 param.fp_comp_end = LUSTRE_EOF;
5175                                 param.fp_comp_end_units = 1;
5176                                 rc = 0;
5177                         } else {
5178                                 rc = llapi_parse_size(optarg,
5179                                                 &param.fp_comp_end,
5180                                                 &param.fp_comp_end_units, 0);
5181                                 /* assume units of KB if too small */
5182                                 if (param.fp_comp_end < 4096)
5183                                         param.fp_comp_end *= 1024;
5184                         }
5185                         if (rc) {
5186                                 fprintf(stderr,
5187                                         "error: bad component end '%s'\n",
5188                                         optarg);
5189                                 goto err;
5190                         }
5191                         param.fp_check_comp_end = 1;
5192                         param.fp_exclude_comp_end = !!neg_opt;
5193                         break;
5194                 case LFS_LAYOUT_FOREIGN_OPT: {
5195                         /* all types by default */
5196                         uint32_t type = LU_FOREIGN_TYPE_UNKNOWN;
5197
5198                         if (optarg) {
5199                                 /* check pure numeric */
5200                                 type = strtoul(optarg, &endptr, 0);
5201                                 if (*endptr) {
5202                                         /* check name */
5203                                         type = check_foreign_type_name(optarg);
5204                                         if (type == LU_FOREIGN_TYPE_UNKNOWN) {
5205                                                 fprintf(stderr,
5206                                                         "%s %s: unknown foreign type '%s'\n",
5207                                                         progname, argv[0],
5208                                                         optarg);
5209                                                 return CMD_HELP;
5210                                         }
5211                                 } else if (type >= UINT32_MAX) {
5212                                         fprintf(stderr,
5213                                                 "%s %s: invalid foreign type '%s'\n",
5214                                                 progname, argv[0], optarg);
5215                                         return CMD_HELP;
5216                                 }
5217                         }
5218                         param.fp_foreign_type = type;
5219                         param.fp_check_foreign = 1;
5220                         param.fp_exclude_foreign = !!neg_opt;
5221                         break;
5222                 }
5223                 case LFS_NEWERXY_OPT: {
5224                         char x = 'm';
5225                         char y = 'm';
5226                         int xidx;
5227                         int negidx;
5228                         time_t *newery;
5229                         time_t ref = time(NULL);
5230
5231                         /* no need to check bad options, they won't get here */
5232                         if (strlen(long_opts[optidx].name) == 7) {
5233                                 x = long_opts[optidx].name[5];
5234                                 y = long_opts[optidx].name[6];
5235                         }
5236
5237                         if (y == 't') {
5238                                 static const char *const fmts[] = {
5239                                         "%Y-%m-%d %H:%M:%S",
5240                                         "%Y-%m-%d %H:%M",
5241                                         "%Y-%m-%d",
5242                                         "%H:%M:%S", /* sometime today */
5243                                         "%H:%M",
5244                                         "@%s",
5245                                         "%s",
5246                                         NULL };
5247                                 struct tm tm;
5248                                 bool found = false;
5249                                 int i;
5250
5251                                 for (i = 0; fmts[i] != NULL; i++) {
5252                                         char *ptr;
5253
5254                                         /* Init for times relative to today */
5255                                         if (strncmp(fmts[i], "%H", 2) == 0) {
5256                                                 localtime_r(&ref, &tm);
5257                                         } else {
5258                                                 memset(&tm, 0, sizeof(tm));
5259                                                 tm.tm_isdst = -1;
5260                                         }
5261                                         ptr = strptime(optarg, fmts[i], &tm);
5262                                         /* Skip spaces */
5263                                         while (ptr && isspace(*ptr))
5264                                                 ptr++;
5265                                         if (ptr == optarg + strlen(optarg)) {
5266                                                 found = true;
5267                                                 break;
5268                                         }
5269                                 }
5270
5271                                 if (!found) {
5272                                         fprintf(stderr,
5273                                                 "%s: invalid time '%s'\n",
5274                                                 progname, optarg);
5275                                         fprintf(stderr,
5276                                                 "supported formats are:\n  ");
5277                                         for (i = 0; fmts[i] != NULL; i++)
5278                                                 fprintf(stderr, "'%s', ",
5279                                                         fmts[i]);
5280                                         fprintf(stderr, "\n");
5281                                         ret = -EINVAL;
5282                                         goto err;
5283                                 }
5284
5285                                 ref = mktime(&tm);
5286                         } else if (y == 'b' || y == 'B') {
5287                                 lstatx_t stx;
5288
5289                                 rc = llapi_get_lum_file(optarg, NULL, &stx,
5290                                                         NULL, 0);
5291                                 if (rc || !(stx.stx_mask & STATX_BTIME)) {
5292                                         if (!(stx.stx_mask & STATX_BTIME))
5293                                                 ret = -EOPNOTSUPP;
5294                                         else
5295                                                 ret = -errno;
5296                                         fprintf(stderr,
5297                                                 "%s: get btime failed '%s': %s\n",
5298                                                 progname, optarg,
5299                                                 strerror(-ret));
5300                                         goto err;
5301                                 }
5302
5303                                 ref = stx.stx_btime.tv_sec;
5304                         } else {
5305                                 struct stat statbuf;
5306
5307                                 if (stat(optarg, &statbuf) < 0) {
5308                                         fprintf(stderr,
5309                                                 "%s: cannot stat file '%s': %s\n",
5310                                                 progname, optarg,
5311                                                 strerror(errno));
5312                                         ret = -errno;
5313                                         goto err;
5314                                 }
5315
5316                                 switch (y) {
5317                                 case 'a':
5318                                         ref = statbuf.st_atime;
5319                                         break;
5320                                 case 'm':
5321                                         ref = statbuf.st_mtime;
5322                                         break;
5323                                 case 'c':
5324                                         ref = statbuf.st_ctime;
5325                                         break;
5326                                 default:
5327                                         fprintf(stderr,
5328                                                 "%s: invalid Y argument: '%c'\n",
5329                                                 progname, x);
5330                                         ret = -EINVAL;
5331                                         goto err;
5332                                 }
5333                         }
5334
5335                         switch (x) {
5336                         case 'a':
5337                                 xidx = NEWERXY_ATIME;
5338                                 break;
5339                         case 'm':
5340                                 xidx = NEWERXY_MTIME;
5341                                 break;
5342                         case 'c':
5343                                 xidx = NEWERXY_CTIME;
5344                                 break;
5345                         case 'b':
5346                         case 'B':
5347                                 xidx = NEWERXY_BTIME;
5348                                 break;
5349                         default:
5350                                 fprintf(stderr,
5351                                         "%s: invalid X argument: '%c'\n",
5352                                         progname, x);
5353                                 ret = -EINVAL;
5354                                 goto err;
5355                         }
5356
5357                         negidx = !!neg_opt;
5358                         newery = &param.fp_newery[xidx][negidx];
5359
5360                         if (*newery == 0) {
5361                                 *newery = ref;
5362                         } else {
5363                                 if (negidx)
5364                                         *newery = *newery > ref ? ref : *newery;
5365                                 else
5366                                         *newery = *newery > ref ? *newery : ref;
5367                         }
5368                         param.fp_newerxy = 1;
5369                         break;
5370                 }
5371                 case 'g':
5372                 case 'G':
5373                         rc = name2gid(&param.fp_gid, optarg);
5374                         if (rc) {
5375                                 if (str2quotaid(&param.fp_gid, optarg)) {
5376                                         fprintf(stderr,
5377                                                 "Group/GID: %s cannot be found.\n",
5378                                                 optarg);
5379                                         ret = -1;
5380                                         goto err;
5381                                 }
5382                         }
5383                         param.fp_exclude_gid = !!neg_opt;
5384                         param.fp_check_gid = 1;
5385                         break;
5386                 case 'H':
5387                         rc = mdthash_input(optarg, &param.fp_hash_inflags,
5388                                            &param.fp_hash_exflags,
5389                                            &param.fp_hash_type);
5390                         if (rc) {
5391                                 ret = -1;
5392                                 goto err;
5393                         }
5394                         if (param.fp_hash_inflags || param.fp_hash_exflags)
5395                                 param.fp_check_hash_flag = 1;
5396                         param.fp_exclude_hash_type = !!neg_opt;
5397                         break;
5398                 case 'l':
5399                         param.fp_lazy = 1;
5400                         break;
5401                 case 'L':
5402                         ret = name2layout(&param.fp_layout, optarg);
5403                         if (ret)
5404                                 goto err;
5405                         param.fp_exclude_layout = !!neg_opt;
5406                         param.fp_check_layout = 1;
5407                         break;
5408                 case 'u':
5409                 case 'U':
5410                         rc = name2uid(&param.fp_uid, optarg);
5411                         if (rc) {
5412                                 if (str2quotaid(&param.fp_uid, optarg)) {
5413                                         fprintf(stderr,
5414                                                 "User/UID: %s cannot be found.\n",
5415                                                 optarg);
5416                                         ret = -1;
5417                                         goto err;
5418                                 }
5419                         }
5420                         param.fp_exclude_uid = !!neg_opt;
5421                         param.fp_check_uid = 1;
5422                         break;
5423                 case 'n':
5424                         param.fp_pattern = (char *)optarg;
5425                         param.fp_exclude_pattern = !!neg_opt;
5426                         break;
5427                 case 'N':
5428                         if (optarg[0] == '+') {
5429                                 param.fp_mirror_count_sign = -1;
5430                                 optarg++;
5431                         } else if (optarg[0] == '-') {
5432                                 param.fp_mirror_count_sign =  1;
5433                                 optarg++;
5434                         }
5435
5436                         errno = 0;
5437                         param.fp_mirror_count = strtoul(optarg, &endptr, 0);
5438                         if (errno != 0 || *endptr != '\0' ||
5439                             param.fp_mirror_count > LUSTRE_MIRROR_COUNT_MAX) {
5440                                 fprintf(stderr,
5441                                         "error: bad mirror count '%s'\n",
5442                                         optarg);
5443                                 goto err;
5444                         }
5445                         param.fp_check_mirror_count = 1;
5446                         param.fp_exclude_mirror_count = !!neg_opt;
5447                         break;
5448                 case 'm':
5449                 case 'i':
5450                 case 'O': {
5451                         char *buf, *token, *next, *p;
5452                         int len = 1;
5453                         void *tmp;
5454
5455                         buf = strdup(optarg);
5456                         if (!buf) {
5457                                 ret = -ENOMEM;
5458                                 goto err;
5459                         }
5460
5461                         param.fp_exclude_obd = !!neg_opt;
5462
5463                         token = buf;
5464                         while (token && *token) {
5465                                 token = strchr(token, ',');
5466                                 if (token) {
5467                                         len++;
5468                                         token++;
5469                                 }
5470                         }
5471                         if (c == 'm') {
5472                                 param.fp_exclude_mdt = !!neg_opt;
5473                                 param.fp_num_alloc_mdts += len;
5474                                 tmp = realloc(param.fp_mdt_uuid,
5475                                               param.fp_num_alloc_mdts *
5476                                               sizeof(*param.fp_mdt_uuid));
5477                                 if (!tmp) {
5478                                         ret = -ENOMEM;
5479                                         goto err_free;
5480                                 }
5481
5482                                 param.fp_mdt_uuid = tmp;
5483                         } else {
5484                                 param.fp_exclude_obd = !!neg_opt;
5485                                 param.fp_num_alloc_obds += len;
5486                                 tmp = realloc(param.fp_obd_uuid,
5487                                               param.fp_num_alloc_obds *
5488                                               sizeof(*param.fp_obd_uuid));
5489                                 if (!tmp) {
5490                                         ret = -ENOMEM;
5491                                         goto err_free;
5492                                 }
5493
5494                                 param.fp_obd_uuid = tmp;
5495                         }
5496                         for (token = buf; token && *token; token = next) {
5497                                 struct obd_uuid *puuid;
5498
5499                                 if (c == 'm') {
5500                                         puuid =
5501                                         &param.fp_mdt_uuid[param.fp_num_mdts++];
5502                                 } else {
5503                                         puuid =
5504                                         &param.fp_obd_uuid[param.fp_num_obds++];
5505                                 }
5506                                 p = strchr(token, ',');
5507                                 next = 0;
5508                                 if (p) {
5509                                         *p = 0;
5510                                         next = p+1;
5511                                 }
5512
5513                                 if (strlen(token) > sizeof(puuid->uuid) - 1) {
5514                                         ret = -E2BIG;
5515                                         goto err_free;
5516                                 }
5517
5518                                 strncpy(puuid->uuid, token,
5519                                         sizeof(puuid->uuid));
5520                         }
5521 err_free:
5522                         if (buf)
5523                                 free(buf);
5524                         break;
5525                 }
5526 #if LUSTRE_VERSION_CODE >= OBD_OCD_VERSION(2, 18, 53, 0)
5527                 case 'p':
5528 #endif
5529                 case LFS_POOL_OPT:
5530                         if (strlen(optarg) > LOV_MAXPOOLNAME) {
5531                                 fprintf(stderr,
5532                                         "Pool name %s is too long (max %d)\n",
5533                                         optarg, LOV_MAXPOOLNAME);
5534                                 ret = -1;
5535                                 goto err;
5536                         }
5537                         /*
5538                          * We do check for empty pool because empty pool
5539                          * is used to find V1 LOV attributes
5540                          */
5541                         strncpy(param.fp_poolname, optarg, LOV_MAXPOOLNAME);
5542                         param.fp_poolname[LOV_MAXPOOLNAME] = '\0';
5543                         param.fp_exclude_pool = !!neg_opt;
5544                         param.fp_check_pool = 1;
5545                         break;
5546 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 14, 53, 0)
5547                 case 'p': /* want this for --pool, to match getstripe/find */
5548                         fprintf(stderr,
5549                                 "warning: -p deprecated, use --print0 or -0\n");
5550 #endif
5551                 case '0':
5552                         param.fp_zero_end = 1;
5553                         break;
5554                 case 'P': /* we always print, this option is a no-op */
5555                         break;
5556                 case LFS_PRINTF_OPT:
5557                         param.fp_format_printf_str = optarg;
5558                         break;
5559                 case LFS_PROJID_OPT:
5560                         rc = name2projid(&param.fp_projid, optarg);
5561                         if (rc) {
5562                                 if (str2quotaid(&param.fp_projid, optarg)) {
5563                                         fprintf(stderr,
5564                                                 "Invalid project ID: %s\n",
5565                                                 optarg);
5566                                         ret = -1;
5567                                         goto err;
5568                                 }
5569                         }
5570                         param.fp_exclude_projid = !!neg_opt;
5571                         param.fp_check_projid = 1;
5572                         break;
5573                 case 's':
5574                         if (optarg[0] == '+') {
5575                                 param.fp_size_sign = -1;
5576                                 optarg++;
5577                         } else if (optarg[0] == '-') {
5578                                 param.fp_size_sign =  1;
5579                                 optarg++;
5580                         }
5581
5582                         ret = llapi_parse_size(optarg, &param.fp_size,
5583                                                &param.fp_size_units, 0);
5584                         if (ret) {
5585                                 fprintf(stderr, "error: bad file size '%s'\n",
5586                                         optarg);
5587                                 goto err;
5588                         }
5589                         param.fp_check_size = 1;
5590                         param.fp_exclude_size = !!neg_opt;
5591                         break;
5592                 case 'S':
5593                         if (optarg[0] == '+') {
5594                                 param.fp_stripe_size_sign = -1;
5595                                 optarg++;
5596                         } else if (optarg[0] == '-') {
5597                                 param.fp_stripe_size_sign =  1;
5598                                 optarg++;
5599                         }
5600
5601                         ret = llapi_parse_size(optarg, &param.fp_stripe_size,
5602                                                &param.fp_stripe_size_units, 0);
5603                         /* assume units of KB if too small to be valid */
5604                         if (param.fp_stripe_size < 4096)
5605                                 param.fp_stripe_size *= 1024;
5606                         if (ret) {
5607                                 fprintf(stderr, "error: bad stripe_size '%s'\n",
5608                                         optarg);
5609                                 goto err;
5610                         }
5611                         param.fp_check_stripe_size = 1;
5612                         param.fp_exclude_stripe_size = !!neg_opt;
5613                         break;
5614                 case 't':
5615                         param.fp_exclude_type = !!neg_opt;
5616                         switch (optarg[0]) {
5617                         case 'b':
5618                                 param.fp_type = S_IFBLK;
5619                                 break;
5620                         case 'c':
5621                                 param.fp_type = S_IFCHR;
5622                                 break;
5623                         case 'd':
5624                                 param.fp_type = S_IFDIR;
5625                                 break;
5626                         case 'f':
5627                                 param.fp_type = S_IFREG;
5628                                 break;
5629                         case 'l':
5630                                 param.fp_type = S_IFLNK;
5631                                 break;
5632                         case 'p':
5633                                 param.fp_type = S_IFIFO;
5634                                 break;
5635                         case 's':
5636                                 param.fp_type = S_IFSOCK;
5637                                 break;
5638                         default:
5639                                 fprintf(stderr, "%s: bad type '%s'\n",
5640                                         progname, optarg);
5641                                 ret = CMD_HELP;
5642                                 goto err;
5643                         }
5644                         break;
5645                 case LFS_FIND_PERM:
5646                         param.fp_exclude_perm = !!neg_opt;
5647                         param.fp_perm_sign = LFS_FIND_PERM_EXACT;
5648                         if (*optarg == '/') {
5649                                 param.fp_perm_sign = LFS_FIND_PERM_ANY;
5650                                 optarg++;
5651                         } else if (*optarg == '-') {
5652                                 param.fp_perm_sign = LFS_FIND_PERM_ALL;
5653                                 optarg++;
5654                         }
5655
5656                         if (str2mode_t(optarg, &param.fp_perm)) {
5657                                 fprintf(stderr, "error: invalid mode '%s'\n",
5658                                         optarg);
5659                                 ret = -1;
5660                                 goto err;
5661                         }
5662                         break;
5663                 case 'T':
5664                         if (optarg[0] == '+') {
5665                                 param.fp_mdt_count_sign = -1;
5666                                 optarg++;
5667                         } else if (optarg[0] == '-') {
5668                                 param.fp_mdt_count_sign =  1;
5669                                 optarg++;
5670                         }
5671
5672                         errno = 0;
5673                         param.fp_mdt_count = strtoul(optarg, &endptr, 0);
5674                         if (errno != 0 || *endptr != '\0' ||
5675                             param.fp_mdt_count >= UINT32_MAX) {
5676                                 fprintf(stderr, "error: bad mdt_count '%s'\n",
5677                                         optarg);
5678                                 ret = -1;
5679                                 goto err;
5680                         }
5681                         param.fp_check_mdt_count = 1;
5682                         param.fp_exclude_mdt_count = !!neg_opt;
5683                         break;
5684                 case 'z':
5685                         if (optarg[0] == '+') {
5686                                 param.fp_ext_size_sign = -1;
5687                                 optarg++;
5688                         } else if (optarg[0] == '-') {
5689                                 param.fp_ext_size_sign =  1;
5690                                 optarg++;
5691                         }
5692
5693                         ret = llapi_parse_size(optarg, &param.fp_ext_size,
5694                                                &param.fp_ext_size_units, 0);
5695                         if (ret) {
5696                                 fprintf(stderr, "error: bad ext-size '%s'\n",
5697                                         optarg);
5698                                 goto err;
5699                         }
5700                         param.fp_ext_size /= SEL_UNIT_SIZE;
5701                         param.fp_ext_size_units /= SEL_UNIT_SIZE;
5702                         param.fp_check_ext_size = 1;
5703                         param.fp_exclude_ext_size = !!neg_opt;
5704                         break;
5705                 default:
5706                         fprintf(stderr, "%s: unrecognized option '%s'\n",
5707                                 progname, argv[optind - 1]);
5708                 case 'h':
5709                         ret = CMD_HELP;
5710                         goto err;
5711                 }
5712         }
5713         if (!param.fp_verbose)
5714                 param.fp_verbose = VERBOSE_DEFAULT;
5715
5716         if (pathstart == -1) {
5717                 fprintf(stderr, "error: %s: no filename|pathname\n",
5718                         argv[0]);
5719                 ret = CMD_HELP;
5720                 goto err;
5721         } else if (pathend == -1) {
5722                 /* no options */
5723                 pathend = argc;
5724         }
5725
5726         do {
5727                 rc = llapi_find(argv[pathstart], &param);
5728                 if (rc && !ret) {
5729                         ret = rc;
5730                         pathbad = pathstart;
5731                 }
5732         } while (++pathstart < pathend);
5733
5734         if (ret)
5735                 fprintf(stderr, "%s: failed for '%s': %s\n",
5736                         progname, argv[pathbad], strerror(-rc));
5737
5738 err:
5739         if (param.fp_obd_uuid && param.fp_num_alloc_obds)
5740                 free(param.fp_obd_uuid);
5741
5742         if (param.fp_mdt_uuid && param.fp_num_alloc_mdts)
5743                 free(param.fp_mdt_uuid);
5744
5745         return ret;
5746 }
5747
5748 static int lfs_getstripe_internal(int argc, char **argv,
5749                                   struct find_param *param)
5750 {
5751         struct option long_opts[] = {
5752 /* find { .val = 'A',   .name = "atime",        .has_arg = required_argument }*/
5753 /* find { .val = 'b',   .name = "blocks",       .has_arg = required_argument }*/
5754 /* find { .val = 'B',   .name = "btime",        .has_arg = required_argument }*/
5755 /* find { .val = 'B',   .name = "Btime",        .has_arg = required_argument }*/
5756         { .val = LFS_COMP_COUNT_OPT,
5757                         .name = "comp-count",   .has_arg = no_argument },
5758         { .val = LFS_COMP_COUNT_OPT,
5759                 .name = "component-count",      .has_arg = no_argument },
5760         { .val = LFS_COMP_FLAGS_OPT,
5761                         .name = "comp-flags",   .has_arg = optional_argument },
5762         { .val = LFS_COMP_FLAGS_OPT,
5763                 .name = "component-flags",      .has_arg = optional_argument },
5764         { .val = LFS_COMP_START_OPT,
5765                         .name = "comp-start",   .has_arg = optional_argument },
5766         { .val = LFS_COMP_START_OPT,
5767                 .name = "component-start",      .has_arg = optional_argument },
5768         { .val = LFS_MIRROR_INDEX_OPT,
5769                 .name = "mirror-index",         .has_arg = required_argument },
5770         { .val = LFS_MIRROR_ID_OPT,
5771                 .name = "mirror-id",            .has_arg = required_argument },
5772         { .val = 'c',   .name = "stripe-count", .has_arg = no_argument },
5773         { .val = 'c',   .name = "stripe_count", .has_arg = no_argument },
5774 /* find { .val = 'C',   .name = "ctime",        .has_arg = required_argument }*/
5775         { .val = 'd',   .name = "directory",    .has_arg = no_argument },
5776         { .val = 'D',   .name = "default",      .has_arg = no_argument },
5777         { .val = 'E',   .name = "comp-end",     .has_arg = optional_argument },
5778         { .val = 'E',   .name = "component-end", .has_arg = optional_argument },
5779         { .val = 'F',   .name = "fid",          .has_arg = no_argument },
5780         { .val = 'g',   .name = "generation",   .has_arg = no_argument },
5781 /* find { .val = 'G',   .name = "group",        .has_arg = required_argument }*/
5782         { .val = 'h',   .name = "help",         .has_arg = no_argument },
5783 /* dirstripe { .val = 'H', .name = "mdt-hash",  .has_arg = required_argument }*/
5784         { .val = 'i',   .name = "stripe-index", .has_arg = no_argument },
5785         { .val = 'i',   .name = "stripe_index", .has_arg = no_argument },
5786         { .val = 'I',   .name = "comp-id",      .has_arg = optional_argument },
5787         { .val = 'I',   .name = "component-id", .has_arg = optional_argument },
5788 /* find { .val = 'l',   .name = "lazy",         .has_arg = no_argument }, */
5789         { .val = 'L',   .name = "layout",       .has_arg = no_argument },
5790         { .val = 'm',   .name = "mdt",          .has_arg = no_argument },
5791         { .val = 'm',   .name = "mdt-index",    .has_arg = no_argument },
5792         { .val = 'm',   .name = "mdt_index",    .has_arg = no_argument },
5793 /* find { .val = 'M',   .name = "mtime",        .has_arg = required_argument }*/
5794 /* find { .val = 'n',   .name = "name",         .has_arg = required_argument }*/
5795         { .val = 'N',   .name = "mirror-count", .has_arg = no_argument },
5796         { .val = 'O',   .name = "obd",          .has_arg = required_argument },
5797         { .val = 'O',   .name = "ost",          .has_arg = required_argument },
5798         { .val = 'p',   .name = "pool",         .has_arg = no_argument },
5799 /* find { .val = 'P',   .name = "print",        .has_arg = no_argument }, */
5800         { .val = 'q',   .name = "quiet",        .has_arg = no_argument },
5801         { .val = 'r',   .name = "recursive",    .has_arg = no_argument },
5802         { .val = 'R',   .name = "raw",          .has_arg = no_argument },
5803         { .val = 'S',   .name = "stripe-size",  .has_arg = no_argument },
5804         { .val = 'S',   .name = "stripe_size",  .has_arg = no_argument },
5805 /* find { .val = 't',   .name = "type",         .has_arg = required_argument }*/
5806 /* dirstripe { .val = 'T', .name = "mdt-count", .has_arg = required_argument }*/
5807 /* find { .val = 'u',   .name = "uid",          .has_arg = required_argument }*/
5808 /* find { .val = 'U',   .name = "user",         .has_arg = required_argument }*/
5809         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
5810 /* dirstripe { .val = 'X',.name = "max-inherit",.has_arg = required_argument }*/
5811         { .val = 'y',   .name = "yaml",         .has_arg = no_argument },
5812         { .val = 'z',   .name = "extension-size", .has_arg = no_argument },
5813         { .val = 'z',   .name = "ext-size",     .has_arg = no_argument },
5814         { .name = NULL } };
5815         int c, rc;
5816         int neg_opt = 0;
5817         int pathstart = -1, pathend = -1;
5818         int isoption;
5819         char *end, *tmp;
5820
5821         while ((c = getopt_long(argc, argv,
5822                         "-cdDE::FghiI::LmMNoO:pqrRsSvyz",
5823                         long_opts, NULL)) != -1) {
5824                 if (neg_opt)
5825                         --neg_opt;
5826
5827                 /* '!' is part of option */
5828                 isoption = (c != 1) || (strcmp(optarg, "!") == 0);
5829                 if (!isoption && pathend != -1) {
5830                         fprintf(stderr,
5831                                 "error: %s: filename|dirname must either precede options or follow options\n",
5832                                 argv[0]);
5833                         return CMD_HELP;
5834                 }
5835                 if (!isoption && pathstart == -1)
5836                         pathstart = optind - 1;
5837                 if (isoption && pathstart != -1 && pathend == -1)
5838                         pathend = optind - 2;
5839
5840                 switch (c) {
5841                 case 1:
5842                         /* unknown: opt is "!" */
5843                         if (strcmp(optarg, "!") == 0)
5844                                 neg_opt = 2;
5845                         break;
5846                 case 'c':
5847                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
5848                                 param->fp_verbose |= VERBOSE_COUNT;
5849                                 param->fp_max_depth = 0;
5850                         }
5851                         break;
5852                 case LFS_COMP_COUNT_OPT:
5853                         param->fp_verbose |= VERBOSE_COMP_COUNT;
5854                         param->fp_max_depth = 0;
5855                         break;
5856                 case LFS_COMP_FLAGS_OPT:
5857                         if (optarg) {
5858                                 rc = comp_str2flags(optarg,
5859                                                     &param->fp_comp_flags,
5860                                                     &param->fp_comp_neg_flags);
5861                                 if (rc != 0) {
5862                                         fprintf(stderr,
5863                                                 "error: %s bad component flags '%s'.\n",
5864                                                 argv[0], optarg);
5865                                         return CMD_HELP;
5866                                 }
5867                                 param->fp_check_comp_flags = 1;
5868                         } else {
5869                                 param->fp_verbose |= VERBOSE_COMP_FLAGS;
5870                                 param->fp_max_depth = 0;
5871                         }
5872                         break;
5873                 case LFS_COMP_START_OPT:
5874                         if (optarg) {
5875                                 tmp = optarg;
5876                                 if (tmp[0] == '+') {
5877                                         param->fp_comp_start_sign = -1;
5878                                         tmp++;
5879                                 } else if (tmp[0] == '-') {
5880                                         param->fp_comp_start_sign = 1;
5881                                         tmp++;
5882                                 }
5883                                 rc = llapi_parse_size(tmp,
5884                                                 &param->fp_comp_start,
5885                                                 &param->fp_comp_start_units, 0);
5886                                 if (rc != 0) {
5887                                         fprintf(stderr,
5888                                                 "error: %s bad component start '%s'.\n",
5889                                                 argv[0], tmp);
5890                                         return CMD_HELP;
5891                                 }
5892                                 param->fp_check_comp_start = 1;
5893                         } else {
5894                                 param->fp_verbose |= VERBOSE_COMP_START;
5895                                 param->fp_max_depth = 0;
5896                         }
5897                         break;
5898                 case LFS_MIRROR_INDEX_OPT: {
5899                         unsigned long int mirror_index;
5900
5901                         if (optarg[0] == '+') {
5902                                 param->fp_mirror_index_sign = -1;
5903                                 optarg++;
5904                         } else if (optarg[0] == '-') {
5905                                 param->fp_mirror_index_sign = 1;
5906                                 optarg++;
5907                         }
5908
5909                         errno = 0;
5910                         mirror_index = strtoul(optarg, &end, 0);
5911                         if (errno != 0 || *end != '\0' ||
5912                             mirror_index > UINT16_MAX || (mirror_index == 0 &&
5913                             param->fp_mirror_index_sign == 0 && neg_opt == 0)) {
5914                                 fprintf(stderr,
5915                                         "%s %s: invalid mirror index '%s'\n",
5916                                         progname, argv[0], optarg);
5917                                 return CMD_HELP;
5918                         }
5919
5920                         param->fp_mirror_index = (__u16)mirror_index;
5921
5922                         if (param->fp_mirror_id != 0) {
5923                                 fprintf(stderr,
5924                                         "%s %s: can't specify both mirror index and mirror ID\n",
5925                                         progname, argv[0]);
5926                                 return CMD_HELP;
5927                         }
5928                         param->fp_check_mirror_index = 1;
5929                         param->fp_exclude_mirror_index = !!neg_opt;
5930                         break;
5931                 }
5932                 case LFS_MIRROR_ID_OPT: {
5933                         unsigned long int mirror_id;
5934
5935                         if (optarg[0] == '+') {
5936                                 param->fp_mirror_id_sign = -1;
5937                                 optarg++;
5938                         } else if (optarg[0] == '-') {
5939                                 param->fp_mirror_id_sign = 1;
5940                                 optarg++;
5941                         }
5942
5943                         errno = 0;
5944                         mirror_id = strtoul(optarg, &end, 0);
5945                         if (errno != 0 || *end != '\0' ||
5946                             mirror_id > UINT16_MAX || (mirror_id == 0 &&
5947                             param->fp_mirror_id_sign == 0 && neg_opt == 0)) {
5948                                 fprintf(stderr,
5949                                         "%s %s: invalid mirror ID '%s'\n",
5950                                         progname, argv[0], optarg);
5951                                 return CMD_HELP;
5952                         }
5953
5954                         param->fp_mirror_id = (__u16)mirror_id;
5955
5956                         if (param->fp_mirror_index != 0) {
5957                                 fprintf(stderr,
5958                                         "%s %s: can't specify both mirror index and mirror ID\n",
5959                                         progname, argv[0]);
5960                                 return CMD_HELP;
5961                         }
5962                         param->fp_check_mirror_id = 1;
5963                         param->fp_exclude_mirror_id = !!neg_opt;
5964                         break;
5965                 }
5966                 case 'd':
5967                         param->fp_max_depth = 0;
5968                         break;
5969                 case 'D':
5970                         param->fp_get_default_lmv = 1;
5971                         break;
5972                 case 'E':
5973                         if (optarg) {
5974                                 tmp = optarg;
5975                                 if (tmp[0] == '+') {
5976                                         param->fp_comp_end_sign = -1;
5977                                         tmp++;
5978                                 } else if (tmp[0] == '-') {
5979                                         param->fp_comp_end_sign = 1;
5980                                         tmp++;
5981                                 }
5982
5983                                 if (arg_is_eof(tmp)) {
5984                                         param->fp_comp_end = LUSTRE_EOF;
5985                                         param->fp_comp_end_units = 1;
5986                                         rc = 0;
5987                                 } else {
5988                                         rc = llapi_parse_size(tmp,
5989                                                 &param->fp_comp_end,
5990                                                 &param->fp_comp_end_units, 0);
5991                                         /* assume units of KB if too small */
5992                                         if (param->fp_comp_end < 4096)
5993                                                 param->fp_comp_end *= 1024;
5994                                 }
5995                                 if (rc != 0) {
5996                                         fprintf(stderr,
5997                                                 "error: %s bad component end '%s'.\n",
5998                                                 argv[0], tmp);
5999                                         return CMD_HELP;
6000                                 }
6001                                 param->fp_check_comp_end = 1;
6002                         } else {
6003                                 param->fp_verbose |= VERBOSE_COMP_END;
6004                                 param->fp_max_depth = 0;
6005                         }
6006                         break;
6007                 case 'F':
6008                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6009                                 param->fp_verbose |= VERBOSE_DFID;
6010                                 param->fp_max_depth = 0;
6011                         }
6012                         break;
6013                 case 'g':
6014                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6015                                 param->fp_verbose |= VERBOSE_GENERATION;
6016                                 param->fp_max_depth = 0;
6017                         }
6018                         break;
6019                 case 'i':
6020                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6021                                 param->fp_verbose |= VERBOSE_STRIPE_OFFSET;
6022                                 param->fp_max_depth = 0;
6023                         }
6024                         break;
6025                 case 'I':
6026                         if (optarg) {
6027                                 param->fp_comp_id = strtoul(optarg, &end, 0);
6028                                 if (*end != '\0' || param->fp_comp_id == 0 ||
6029                                     param->fp_comp_id > LCME_ID_MAX) {
6030                                         fprintf(stderr,
6031                                                 "error: %s bad component id '%s'\n",
6032                                                 argv[0], optarg);
6033                                         return CMD_HELP;
6034                                 }
6035                                 param->fp_check_comp_id = 1;
6036                         } else {
6037                                 param->fp_max_depth = 0;
6038                                 param->fp_verbose |= VERBOSE_COMP_ID;
6039                         }
6040                         break;
6041                 case 'L':
6042                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6043                                 param->fp_verbose |= VERBOSE_PATTERN;
6044                                 param->fp_max_depth = 0;
6045                         }
6046                         break;
6047 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
6048                 case 'M':
6049                         fprintf(stderr,
6050                                 "warning: '-M' deprecated, use '--mdt-index' or '-m' instead\n");
6051 #endif
6052                 case 'm':
6053                         if (!(param->fp_verbose & VERBOSE_DETAIL))
6054                                 param->fp_max_depth = 0;
6055                         param->fp_verbose |= VERBOSE_MDTINDEX;
6056                         break;
6057                 case 'N':
6058                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6059                                 param->fp_verbose |= VERBOSE_MIRROR_COUNT;
6060                                 param->fp_max_depth = 0;
6061                         }
6062                         break;
6063                 case 'O':
6064                         if (param->fp_obd_uuid) {
6065                                 fprintf(stderr,
6066                                         "error: %s: only one obduuid allowed",
6067                                         argv[0]);
6068                                 return CMD_HELP;
6069                         }
6070                         param->fp_obd_uuid = (struct obd_uuid *)optarg;
6071                         break;
6072                 case 'p':
6073                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6074                                 param->fp_verbose |= VERBOSE_POOL;
6075                                 param->fp_max_depth = 0;
6076                         }
6077                         break;
6078                 case 'q':
6079                         param->fp_quiet++;
6080                         break;
6081                 case 'r':
6082                         param->fp_recursive = 1;
6083                         break;
6084                 case 'R':
6085                         param->fp_raw = 1;
6086                         break;
6087                 case 'S':
6088                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6089                                 param->fp_verbose |= VERBOSE_STRIPE_SIZE;
6090                                 param->fp_max_depth = 0;
6091                         }
6092                         break;
6093                 case 'v':
6094                         param->fp_verbose = VERBOSE_DEFAULT | VERBOSE_DETAIL;
6095                         break;
6096                 case 'y':
6097                         param->fp_yaml = 1;
6098                         break;
6099                 case 'z':
6100                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6101                                 param->fp_verbose |= VERBOSE_EXT_SIZE;
6102                                 param->fp_max_depth = 0;
6103                         }
6104                         break;
6105                 default:
6106                         fprintf(stderr, "%s: unrecognized option '%s'\n",
6107                                 progname, argv[optind - 1]);
6108                 case 'h':
6109                         return CMD_HELP;
6110                 }
6111         }
6112
6113         if (pathstart == -1) {
6114                 fprintf(stderr, "error: %s: no filename|pathname\n",
6115                                 argv[0]);
6116                 return CMD_HELP;
6117         } else if (pathend == -1) {
6118                 /* no options */
6119                 pathend = argc;
6120         }
6121
6122         if (pathend > argc)
6123                 return CMD_HELP;
6124
6125         if (param->fp_recursive)
6126                 param->fp_max_depth = -1;
6127         else if (param->fp_verbose & VERBOSE_DETAIL)
6128                 param->fp_max_depth = 1;
6129
6130         if (!param->fp_verbose)
6131                 param->fp_verbose = VERBOSE_DEFAULT;
6132         if (param->fp_quiet)
6133                 param->fp_verbose = VERBOSE_OBJID;
6134
6135         do {
6136                 rc = llapi_getstripe(argv[pathstart], param);
6137         } while (++pathstart < pathend && !rc);
6138
6139         if (rc)
6140                 fprintf(stderr, "error: %s failed for %s.\n",
6141                         argv[0], argv[optind - 1]);
6142         return rc;
6143 }
6144
6145 static int lfs_tgts(int argc, char **argv)
6146 {
6147         char mntdir[PATH_MAX] = {'\0'}, path[PATH_MAX] = {'\0'};
6148         struct find_param param;
6149         int index = 0, rc = 0;
6150
6151         if (argc > 2)
6152                 return CMD_HELP;
6153
6154         if (argc == 2 && !realpath(argv[1], path)) {
6155                 rc = -errno;
6156                 fprintf(stderr, "error: invalid path '%s': %s\n",
6157                         argv[1], strerror(-rc));
6158                 return rc;
6159         }
6160
6161         while (!llapi_search_mounts(path, index++, mntdir, NULL)) {
6162                 /* Check if we have a mount point */
6163                 if (mntdir[0] == '\0')
6164                         continue;
6165
6166                 memset(&param, 0, sizeof(param));
6167                 if (!strcmp(argv[0], "mdts"))
6168                         param.fp_get_lmv = 1;
6169
6170                 rc = llapi_ostlist(mntdir, &param);
6171                 if (rc) {
6172                         fprintf(stderr, "error: %s: failed on %s\n",
6173                                 argv[0], mntdir);
6174                 }
6175                 if (path[0] != '\0')
6176                         break;
6177                 memset(mntdir, 0, PATH_MAX);
6178         }
6179
6180         return rc;
6181 }
6182
6183 static int lfs_getstripe(int argc, char **argv)
6184 {
6185         struct find_param param = { 0 };
6186
6187         param.fp_max_depth = 1;
6188         return lfs_getstripe_internal(argc, argv, &param);
6189 }
6190
6191 /* functions */
6192 static int lfs_getdirstripe(int argc, char **argv)
6193 {
6194         struct find_param param = { 0 };
6195         struct option long_opts[] = {
6196         { .val = 'c',   .name = "mdt-count",     .has_arg = no_argument },
6197         { .val = 'D',   .name = "default",       .has_arg = no_argument },
6198         { .val = 'h',   .name = "help",         .has_arg = no_argument },
6199         { .val = 'H',   .name = "mdt-hash",      .has_arg = no_argument },
6200         { .val = 'i',   .name = "mdt-index",     .has_arg = no_argument },
6201         { .val = 'm',   .name = "mdt-index",     .has_arg = no_argument },
6202         { .val = 'O',   .name = "obd",           .has_arg = required_argument },
6203         { .val = 'r',   .name = "recursive",     .has_arg = no_argument },
6204         { .val = 'T',   .name = "mdt-count",     .has_arg = no_argument },
6205         { .val = 'v',   .name = "verbose",       .has_arg = no_argument },
6206         { .val = 'X',   .name = "max-inherit",   .has_arg = no_argument },
6207         { .val = 'y',   .name = "yaml",          .has_arg = no_argument },
6208         { .val = LFS_INHERIT_RR_OPT,
6209                         .name = "max-inherit-rr", .has_arg = no_argument },
6210         { .name = NULL } };
6211         int c, rc;
6212
6213         param.fp_get_lmv = 1;
6214
6215         while ((c = getopt_long(argc, argv,
6216                                 "cDhHimO:rtTvXy", long_opts, NULL)) != -1) {
6217                 switch (c) {
6218                 case 'c':
6219                 case 'T':
6220                         param.fp_verbose |= VERBOSE_COUNT;
6221                         break;
6222                 case 'D':
6223                         param.fp_get_default_lmv = 1;
6224                         break;
6225 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
6226                 case 't':
6227                         fprintf(stderr,
6228                                 "warning: '-t' deprecated, use '--mdt-hash' or '-H' instead\n");
6229                         fallthrough;
6230 #endif
6231                 case 'H':
6232                         param.fp_verbose |= VERBOSE_HASH_TYPE;
6233                         break;
6234                 case 'i':
6235                         fallthrough;
6236                 case 'm':
6237                         param.fp_verbose |= VERBOSE_STRIPE_OFFSET;
6238                         break;
6239                 case 'O':
6240                         if (param.fp_obd_uuid) {
6241                                 fprintf(stderr,
6242                                         "%s: only one obduuid allowed",
6243                                         progname);
6244                                 return CMD_HELP;
6245                         }
6246                         param.fp_obd_uuid = (struct obd_uuid *)optarg;
6247                         break;
6248                 case 'r':
6249                         param.fp_recursive = 1;
6250                         break;
6251                 case 'v':
6252                         param.fp_verbose |= VERBOSE_DETAIL;
6253                         break;
6254                 case 'X':
6255                         param.fp_verbose |= VERBOSE_INHERIT;
6256                         break;
6257                 case LFS_INHERIT_RR_OPT:
6258                         param.fp_verbose |= VERBOSE_INHERIT_RR;
6259                         break;
6260                 case 'y':
6261                         param.fp_yaml = 1;
6262                         break;
6263                 default:
6264                         fprintf(stderr, "%s: unrecognized option '%s'\n",
6265                                 progname, argv[optind - 1]);
6266                         fallthrough;
6267                 case 'h':
6268                         return CMD_HELP;
6269                 }
6270         }
6271
6272         if (optind >= argc)
6273                 return CMD_HELP;
6274
6275         if (param.fp_recursive)
6276                 param.fp_max_depth = -1;
6277
6278         if (!param.fp_verbose)
6279                 param.fp_verbose = VERBOSE_DEFAULT;
6280
6281         do {
6282                 rc = llapi_getstripe(argv[optind], &param);
6283         } while (++optind < argc && !rc);
6284
6285         if (rc)
6286                 fprintf(stderr, "error: %s failed for %s.\n",
6287                         argv[0], argv[optind - 1]);
6288         return rc;
6289 }
6290
6291 enum mntdf_flags {
6292         MNTDF_INODES    = 0x0001,
6293         MNTDF_COOKED    = 0x0002,
6294         MNTDF_LAZY      = 0x0004,
6295         MNTDF_VERBOSE   = 0x0008,
6296         MNTDF_SHOW      = 0x0010,
6297         MNTDF_DECIMAL   = 0x0020,
6298 };
6299
6300 #define COOK(value, base)                                       \
6301 ({                                                              \
6302         int radix = 0;                                          \
6303         while (value > base) {                                  \
6304                 value /= base;                                  \
6305                 radix++;                                        \
6306         }                                                       \
6307         radix;                                                  \
6308 })
6309 #define UUF     "%-20s"
6310 #define CSF     "%11s"
6311 #define CDF     "%11llu"
6312 #define HDF     "%8.1f%c"
6313 #define RSF     "%4s"
6314 #define RDF     "%3d%%"
6315
6316 static inline int obd_statfs_ratio(const struct obd_statfs *st, bool inodes)
6317 {
6318         double avail, used, ratio = 0;
6319
6320         if (inodes) {
6321                 avail = st->os_ffree;
6322                 used = st->os_files - st->os_ffree;
6323         } else {
6324                 avail = st->os_bavail;
6325                 used = st->os_blocks - st->os_bfree;
6326         }
6327         if (avail + used > 0)
6328                 ratio = used / (used + avail) * 100;
6329
6330         /* Round up to match df(1) usage percentage */
6331         return (ratio - (int)ratio) > 0 ? (int)(ratio + 1) : (int)ratio;
6332 }
6333
6334 /*
6335  * This is to identify various problem states for "lfs df" if .osn_err = true,
6336  * so only show flags reflecting those states by default. Informational states
6337  * are only shown with "-v" and use lower-case names to distinguish them.
6338  * UNUSED[12] were for "EROFS = 30" until 1.6 but are now available for use.
6339  */
6340 static struct obd_statfs_state_names {
6341         enum obd_statfs_state   osn_state;
6342         const char              osn_name;
6343         bool                    osn_err;
6344 } oss_names[] = {
6345         { .osn_state = OS_STATFS_DEGRADED,   .osn_name = 'D', .osn_err = true },
6346         { .osn_state = OS_STATFS_READONLY,   .osn_name = 'R', .osn_err = true },
6347         { .osn_state = OS_STATFS_NOPRECREATE,.osn_name = 'N', .osn_err = true },
6348         { .osn_state = OS_STATFS_UNUSED1,    .osn_name = '?', .osn_err = true },
6349         { .osn_state = OS_STATFS_UNUSED2,    .osn_name = '?', .osn_err = true },
6350         { .osn_state = OS_STATFS_ENOSPC,     .osn_name = 'S', .osn_err = true },
6351         { .osn_state = OS_STATFS_ENOINO,     .osn_name = 'I', .osn_err = true },
6352         { .osn_state = OS_STATFS_SUM,        .osn_name = 'a', /* aggregate */ },
6353         { .osn_state = OS_STATFS_NONROT,     .osn_name = 'f', /* flash */     },
6354 };
6355
6356 static int showdf(char *mntdir, struct obd_statfs *stat,
6357                   char *uuid, enum mntdf_flags flags,
6358                   char *type, int index, int rc)
6359 {
6360         long long avail, used, total;
6361         int ratio = 0;
6362         char *suffix = flags & MNTDF_DECIMAL ? "kMGTPEZY" : "KMGTPEZY";
6363         /* Note if we have >2^64 bytes/fs these buffers will need to be grown */
6364         char tbuf[3 * sizeof(__u64)];
6365         char ubuf[3 * sizeof(__u64)];
6366         char abuf[3 * sizeof(__u64)];
6367         char rbuf[3 * sizeof(__u64)];
6368
6369         if (!uuid || !stat)
6370                 return -EINVAL;
6371
6372         switch (rc) {
6373         case 0:
6374                 if (flags & MNTDF_INODES) {
6375                         avail = stat->os_ffree;
6376                         used = stat->os_files - stat->os_ffree;
6377                         total = stat->os_files;
6378                 } else {
6379                         int shift = flags & MNTDF_COOKED ? 0 : 10;
6380
6381                         avail = (stat->os_bavail * stat->os_bsize) >> shift;
6382                         used  = ((stat->os_blocks - stat->os_bfree) *
6383                                  stat->os_bsize) >> shift;
6384                         total = (stat->os_blocks * stat->os_bsize) >> shift;
6385                 }
6386
6387                 ratio = obd_statfs_ratio(stat, flags & MNTDF_INODES);
6388
6389                 if (flags & MNTDF_COOKED) {
6390                         int base = flags & MNTDF_DECIMAL ? 1000 : 1024;
6391                         double cook_val;
6392                         int i;
6393
6394                         cook_val = (double)total;
6395                         i = COOK(cook_val, base);
6396                         if (i > 0)
6397                                 snprintf(tbuf, sizeof(tbuf), HDF, cook_val,
6398                                          suffix[i - 1]);
6399                         else
6400                                 snprintf(tbuf, sizeof(tbuf), CDF, total);
6401
6402                         cook_val = (double)used;
6403                         i = COOK(cook_val, base);
6404                         if (i > 0)
6405                                 snprintf(ubuf, sizeof(ubuf), HDF, cook_val,
6406                                          suffix[i - 1]);
6407                         else
6408                                 snprintf(ubuf, sizeof(ubuf), CDF, used);
6409
6410                         cook_val = (double)avail;
6411                         i = COOK(cook_val, base);
6412                         if (i > 0)
6413                                 snprintf(abuf, sizeof(abuf), HDF, cook_val,
6414                                          suffix[i - 1]);
6415                         else
6416                                 snprintf(abuf, sizeof(abuf), CDF, avail);
6417                 } else {
6418                         snprintf(tbuf, sizeof(tbuf), CDF, total);
6419                         snprintf(ubuf, sizeof(tbuf), CDF, used);
6420                         snprintf(abuf, sizeof(tbuf), CDF, avail);
6421                 }
6422
6423                 sprintf(rbuf, RDF, ratio);
6424                 printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s",
6425                        uuid, tbuf, ubuf, abuf, rbuf, mntdir);
6426                 if (type)
6427                         printf("[%s:%d]", type, index);
6428
6429                 if (stat->os_state) {
6430                         uint32_t i;
6431
6432                         printf(" ");
6433                         for (i = 0; i < ARRAY_SIZE(oss_names); i++) {
6434                                 if (oss_names[i].osn_state & stat->os_state &&
6435                                     (oss_names[i].osn_err ||
6436                                      flags & MNTDF_VERBOSE))
6437                                         printf("%c", oss_names[i].osn_name);
6438                         }
6439                 }
6440
6441                 printf("\n");
6442                 break;
6443         case -ENODATA:
6444                 printf(UUF": inactive device\n", uuid);
6445                 break;
6446         default:
6447                 printf(UUF": %s\n", uuid, strerror(-rc));
6448                 break;
6449         }
6450
6451         return 0;
6452 }
6453
6454 struct ll_stat_type {
6455         int   st_op;
6456         char *st_name;
6457 };
6458
6459 #define LL_STATFS_MAX   LOV_MAX_STRIPE_COUNT
6460
6461 struct ll_statfs_data {
6462         int                     sd_index;
6463         struct obd_statfs       sd_st;
6464 };
6465
6466 struct ll_statfs_buf {
6467         int                     sb_count;
6468         struct ll_statfs_data   sb_buf[LL_STATFS_MAX];
6469 };
6470
6471 static int mntdf(char *mntdir, char *fsname, char *pool, enum mntdf_flags flags,
6472                  int ops, struct ll_statfs_buf *lsb)
6473 {
6474         struct obd_statfs stat_buf, sum = { .os_bsize = 1 };
6475         struct obd_uuid uuid_buf;
6476         char *poolname = NULL;
6477         struct ll_stat_type types[] = {
6478                 { .st_op = LL_STATFS_LMV,       .st_name = "MDT" },
6479                 { .st_op = LL_STATFS_LOV,       .st_name = "OST" },
6480                 { .st_name = NULL } };
6481         struct ll_stat_type *tp;
6482         __u64 ost_files = 0;
6483         __u64 ost_ffree = 0;
6484         __u32 index;
6485         __u32 type;
6486         int fd;
6487         int rc = 0;
6488         int rc2;
6489
6490         if (pool) {
6491                 poolname = strchr(pool, '.');
6492                 if (poolname) {
6493                         if (strncmp(fsname, pool, strlen(fsname))) {
6494                                 fprintf(stderr, "filesystem name incorrect\n");
6495                                 return -ENODEV;
6496                         }
6497                         poolname++;
6498                 } else
6499                         poolname = pool;
6500         }
6501
6502         fd = open(mntdir, O_RDONLY);
6503         if (fd < 0) {
6504                 rc = -errno;
6505                 fprintf(stderr, "%s: cannot open '%s': %s\n", progname, mntdir,
6506                         strerror(errno));
6507                 return rc;
6508         }
6509
6510         if (flags & MNTDF_SHOW) {
6511                 if (flags & MNTDF_INODES)
6512                         printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s\n",
6513                                "UUID", "Inodes", "IUsed", "IFree",
6514                                "IUse%", "Mounted on");
6515                 else
6516                         printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s\n",
6517                                "UUID",
6518                                flags & MNTDF_COOKED ? "bytes" : "1K-blocks",
6519                                "Used", "Available", "Use%", "Mounted on");
6520         }
6521
6522         for (tp = types; tp->st_name != NULL; tp++) {
6523                 bool have_ost = false;
6524
6525                 if (!(tp->st_op & ops))
6526                         continue;
6527
6528                 for (index = 0; index < LOV_ALL_STRIPES &&
6529                      (!lsb || lsb->sb_count < LL_STATFS_MAX); index++) {
6530                         memset(&stat_buf, 0, sizeof(struct obd_statfs));
6531                         memset(&uuid_buf, 0, sizeof(struct obd_uuid));
6532                         type = flags & MNTDF_LAZY ?
6533                                 tp->st_op | LL_STATFS_NODELAY : tp->st_op;
6534                         rc2 = llapi_obd_fstatfs(fd, type, index,
6535                                                 &stat_buf, &uuid_buf);
6536                         if (rc2 == -ENODEV)
6537                                 break;
6538                         if (rc2 == -EAGAIN)
6539                                 continue;
6540                         if (rc2 == -ENODATA) { /* Inactive device, OK. */
6541                                 if (!(flags & MNTDF_VERBOSE))
6542                                         continue;
6543                         } else if (rc2 < 0 && rc == 0) {
6544                                 rc = rc2;
6545                         }
6546
6547                         /*
6548                          * If we have OSTs then don't report MDT block counts.
6549                          * For MDT-only filesystems the expectation is that all
6550                          * layouts have a DoM component.  For filesystems with
6551                          * OSTs, files are not necessarily going to store data
6552                          * on MDTs, and MDT space is limited to a fraction of
6553                          * OST space, so don't include it in the summary.
6554                          */
6555                         if (tp->st_op == LL_STATFS_LOV && !have_ost) {
6556                                 have_ost = true;
6557                                 sum.os_blocks = 0;
6558                                 sum.os_bfree = 0;
6559                                 sum.os_bavail = 0;
6560                         }
6561
6562                         if (poolname && tp->st_op == LL_STATFS_LOV &&
6563                             llapi_search_ost(fsname, poolname,
6564                                              obd_uuid2str(&uuid_buf)) != 1)
6565                                 continue;
6566
6567                         /*
6568                          * the llapi_obd_fstatfs() call may have returned with
6569                          * an error, but if it filled in uuid_buf we will at
6570                          * lease use that to print out a message for that OBD.
6571                          * If we didn't get anything in the uuid_buf, then fill
6572                          * it in so that we can print an error message.
6573                          */
6574                         if (uuid_buf.uuid[0] == '\0')
6575                                 snprintf(uuid_buf.uuid, sizeof(uuid_buf.uuid),
6576                                          "%s%04x", tp->st_name, index);
6577                         if (!rc && lsb) {
6578                                 lsb->sb_buf[lsb->sb_count].sd_index = index;
6579                                 lsb->sb_buf[lsb->sb_count].sd_st = stat_buf;
6580                                 lsb->sb_count++;
6581                         }
6582                         if (flags & MNTDF_SHOW)
6583                                 showdf(mntdir, &stat_buf,
6584                                        obd_uuid2str(&uuid_buf), flags,
6585                                        tp->st_name, index, rc2);
6586
6587                         if (rc2)
6588                                 continue;
6589
6590                         if (tp->st_op == LL_STATFS_LMV) {
6591                                 sum.os_ffree += stat_buf.os_ffree;
6592                                 sum.os_files += stat_buf.os_files;
6593                         } else /* if (tp->st_op == LL_STATFS_LOV) */ {
6594                                 ost_files += stat_buf.os_files;
6595                                 ost_ffree += stat_buf.os_ffree;
6596                         }
6597                         sum.os_blocks += stat_buf.os_blocks *
6598                                          stat_buf.os_bsize;
6599                         sum.os_bfree  += stat_buf.os_bfree *
6600                                          stat_buf.os_bsize;
6601                         sum.os_bavail += stat_buf.os_bavail *
6602                                          stat_buf.os_bsize;
6603                 }
6604         }
6605
6606         close(fd);
6607
6608         /*
6609          * If we have _some_ OSTs, but don't have as many free objects on the
6610          * OST as inodes on the MDTs, reduce the reported number of inodes
6611          * to compensate, so that the "inodes in use" number is correct.
6612          * This should be kept in sync with ll_statfs_internal().
6613          */
6614         if (ost_files && ost_ffree < sum.os_ffree) {
6615                 sum.os_files = (sum.os_files - sum.os_ffree) + ost_ffree;
6616                 sum.os_ffree = ost_ffree;
6617         }
6618         if (flags & MNTDF_SHOW) {
6619                 printf("\n");
6620                 showdf(mntdir, &sum, "filesystem_summary:", flags, NULL, 0, 0);
6621                 printf("\n");
6622         }
6623
6624         return rc;
6625 }
6626
6627 enum {
6628         LAYOUT_INHERIT_UNSET    = -2,
6629 };
6630
6631 /* functions */
6632 static int lfs_setdirstripe(int argc, char **argv)
6633 {
6634         char *dname;
6635         struct lfs_setstripe_args lsa = { 0 };
6636         struct llapi_stripe_param *param = NULL;
6637         __u32 mdts[LMV_MAX_STRIPE_COUNT] = { 0 };
6638         char *end;
6639         int c;
6640         char *mode_opt = NULL;
6641         bool default_stripe = false;
6642         bool delete = false;
6643         bool foreign_mode = false;
6644         mode_t mode = S_IRWXU | S_IRWXG | S_IRWXO;
6645         mode_t previous_mode = 0;
6646         char *xattr = NULL;
6647         __u32 type = LU_FOREIGN_TYPE_SYMLINK, flags = 0;
6648         int max_inherit = LAYOUT_INHERIT_UNSET;
6649         int max_inherit_rr = LAYOUT_INHERIT_UNSET;
6650         struct option long_opts[] = {
6651         { .val = 'c',   .name = "count",        .has_arg = required_argument },
6652         { .val = 'c',   .name = "mdt-count",    .has_arg = required_argument },
6653         { .val = 'd',   .name = "delete",       .has_arg = no_argument },
6654         { .val = 'D',   .name = "default",      .has_arg = no_argument },
6655         { .val = 'D',   .name = "default_stripe", .has_arg = no_argument },
6656         { .val = LFS_LAYOUT_FLAGS_OPT,
6657                         .name = "flags",        .has_arg = required_argument },
6658         { .val = LFS_LAYOUT_FOREIGN_OPT,
6659                         .name = "foreign",      .has_arg = optional_argument},
6660         { .val = 'h',   .name = "help",         .has_arg = no_argument },
6661         { .val = 'H',   .name = "mdt-hash",     .has_arg = required_argument },
6662 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 17, 53, 0)
6663         { .val = 'i',   .name = "mdt-index",    .has_arg = required_argument },
6664         { .val = 'i',   .name = "mdt",          .has_arg = required_argument },
6665 #else
6666 /* find { .val = 'l',   .name = "lazy",         .has_arg = no_argument }, */
6667         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument },
6668         { .val = 'm',   .name = "mdt",          .has_arg = required_argument },
6669 #endif
6670 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
6671         { .val = 'i',   .name = "index",        .has_arg = required_argument },
6672 #endif
6673         { .val = 'o',   .name = "mode",         .has_arg = required_argument },
6674 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
6675         { .val = 't',   .name = "hash-type",    .has_arg = required_argument },
6676 #endif
6677         { .val = 'T',   .name = "mdt-count",    .has_arg = required_argument },
6678         { .val = 'x',   .name = "xattr",        .has_arg = required_argument },
6679         { .val = 'X',   .name = "max-inherit",  .has_arg = required_argument },
6680         { .val = LFS_INHERIT_RR_OPT,
6681                         .name = "max-inherit-rr", .has_arg = required_argument},
6682 /* setstripe { .val = 'y', .name = "yaml",      .has_arg = no_argument }, */
6683         { .name = NULL } };
6684         int result = 0;
6685
6686         setstripe_args_init(&lsa);
6687
6688         while ((c = getopt_long(argc, argv, "c:dDi:hH:m:o:t:T:x:X:",
6689                                 long_opts, NULL)) >= 0) {
6690                 switch (c) {
6691                 case 0:
6692                         /* Long options. */
6693                         break;
6694                 case 'c':
6695                 case 'T':
6696                         errno = 0;
6697                         lsa.lsa_stripe_count = strtoul(optarg, &end, 0);
6698                         if (errno != 0 || *end != '\0' ||
6699                             lsa.lsa_stripe_count < -1 ||
6700                             lsa.lsa_stripe_count > LOV_MAX_STRIPE_COUNT) {
6701                                 fprintf(stderr,
6702                                         "%s: invalid stripe count '%s'\n",
6703                                         progname, optarg);
6704                                 return CMD_HELP;
6705                         }
6706                         break;
6707                 case 'd':
6708                         delete = true;
6709                         default_stripe = true;
6710                         break;
6711                 case 'D':
6712                         default_stripe = true;
6713                         break;
6714                 case LFS_LAYOUT_FOREIGN_OPT:
6715                         if (optarg) {
6716                                 /* check pure numeric */
6717                                 type = strtoul(optarg, &end, 0);
6718                                 if (*end) {
6719                                         /* check name */
6720                                         type = check_foreign_type_name(optarg);
6721                                         if (type == LU_FOREIGN_TYPE_UNKNOWN) {
6722                                                 fprintf(stderr,
6723                                                         "%s %s: unknown foreign type '%s'\n",
6724                                                         progname, argv[0],
6725                                                         optarg);
6726                                                 return CMD_HELP;
6727                                         }
6728                                 } else if (type >= UINT32_MAX) {
6729                                         fprintf(stderr,
6730                                                 "%s %s: invalid foreign type '%s'\n",
6731                                                 progname, argv[0], optarg);
6732                                         return CMD_HELP;
6733                                 }
6734                         }
6735                         foreign_mode = true;
6736                         break;
6737                 case LFS_LAYOUT_FLAGS_OPT:
6738                         errno = 0;
6739                         flags = strtoul(optarg, &end, 16);
6740                         if (errno != 0 || *end != '\0' ||
6741                             flags >= UINT32_MAX) {
6742                                 fprintf(stderr,
6743                                         "%s %s: invalid hex flags '%s'\n",
6744                                         progname, argv[0], optarg);
6745                                 return CMD_HELP;
6746                         }
6747                         if (!foreign_mode) {
6748                                 fprintf(stderr,
6749                                         "%s %s: hex flags must be specified with --foreign option\n",
6750                                         progname, argv[0]);
6751                                 return CMD_HELP;
6752                         }
6753                         break;
6754 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
6755                 case 't':
6756                         fprintf(stderr,
6757                                 "warning: '--hash-type' and '-t' deprecated, use '--mdt-hash' or '-H' instead\n");
6758                         fallthrough;
6759 #endif
6760                 case 'H':
6761                         lsa.lsa_pattern = check_hashtype(optarg);
6762                         if (lsa.lsa_pattern == 0) {
6763                                 fprintf(stderr,
6764                                         "%s %s: bad directory hash type '%s'\n",
6765                                         progname, argv[0], optarg);
6766                                 return CMD_HELP;
6767                         }
6768                         break;
6769                 case 'i':
6770 #if LUSTRE_VERSION_CODE >= OBD_OCD_VERSION(2, 17, 53, 0)
6771                 case 'm':
6772 #endif
6773 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
6774                         if (strcmp(argv[optind - 1], "--index") == 0)
6775                                 fprintf(stderr,
6776                                         "%s %s: warning: '--index' deprecated, use '--mdt-index' instead\n",
6777                                         progname, argv[0]);
6778 #endif
6779                         lsa.lsa_nr_tgts = parse_targets(mdts,
6780                                                 sizeof(mdts) / sizeof(__u32),
6781                                                 lsa.lsa_nr_tgts, optarg, NULL);
6782                         if (lsa.lsa_nr_tgts < 0) {
6783                                 fprintf(stderr,
6784                                         "%s %s: invalid MDT target(s) '%s'\n",
6785                                         progname, argv[0], optarg);
6786                                 return CMD_HELP;
6787                         }
6788
6789                         lsa.lsa_tgts = mdts;
6790                         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
6791                                 lsa.lsa_stripe_off = mdts[0];
6792                         break;
6793 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 15, 53, 0)
6794                 case 'm':
6795                         fprintf(stderr,
6796                                 "warning: '-m' is deprecated, use '--mode' or '-o' instead\n");
6797 #endif
6798                 case 'o':
6799                         mode_opt = optarg;
6800                         break;
6801                 case 'x':
6802                         xattr = optarg;
6803                         break;
6804                 case 'X':
6805                         errno = 0;
6806                         max_inherit = strtol(optarg, &end, 10);
6807                         if (errno != 0 || *end != '\0' || max_inherit < -2) {
6808                                 fprintf(stderr,
6809                                         "%s %s: invalid max-inherit '%s'\n",
6810                                         progname, argv[0], optarg);
6811                                 return CMD_HELP;
6812                         }
6813                         if (max_inherit == 0) {
6814                                 max_inherit = LMV_INHERIT_NONE;
6815                         } else if (max_inherit == -1) {
6816                                 max_inherit = LMV_INHERIT_UNLIMITED;
6817                         } else if (max_inherit > LMV_INHERIT_MAX) {
6818                                 fprintf(stderr,
6819                                         "%s %s: max-inherit %d exceeds maximum %u\n",
6820                                         progname, argv[0], max_inherit,
6821                                         LMV_INHERIT_MAX);
6822                                 return CMD_HELP;
6823                         }
6824                         break;
6825                 case LFS_INHERIT_RR_OPT:
6826                         if (!default_stripe) {
6827                                 fprintf(stderr,
6828                                         "%s %s: '--max-inherit-rr' must be specified with '-D'\n",
6829                                         progname, argv[0]);
6830                                 return CMD_HELP;
6831                         }
6832                         errno = 0;
6833                         max_inherit_rr = strtol(optarg, &end, 10);
6834                         if (errno != 0 || *end != '\0' || max_inherit_rr < -2) {
6835                                 fprintf(stderr,
6836                                         "%s %s: invalid max-inherit-rr '%s'\n",
6837                                         progname, argv[0], optarg);
6838                                 return CMD_HELP;
6839                         }
6840                         if (max_inherit_rr == 0) {
6841                                 max_inherit_rr = LMV_INHERIT_RR_NONE;
6842                         } else if (max_inherit_rr == -1) {
6843                                 max_inherit_rr = LMV_INHERIT_RR_UNLIMITED;
6844                         } else if (max_inherit_rr > LMV_INHERIT_RR_MAX) {
6845                                 fprintf(stderr,
6846                                         "%s %s: max-inherit-rr %d exceeds maximum %u\n",
6847                                         progname, argv[0], max_inherit_rr,
6848                                         LMV_INHERIT_RR_MAX);
6849                                 return CMD_HELP;
6850                         }
6851                         break;
6852                 default:
6853                         fprintf(stderr, "%s: unrecognized option '%s'\n",
6854                                 progname, argv[optind - 1]);
6855                         fallthrough;
6856                 case 'h':
6857                         return CMD_HELP;
6858                 }
6859         }
6860
6861         if (optind == argc) {
6862                 fprintf(stderr, "%s %s: DIR must be specified\n",
6863                         progname, argv[0]);
6864                 return CMD_HELP;
6865         }
6866
6867         if (xattr && !foreign_mode) {
6868                 /*
6869                  * only print a warning as this is armless and will be
6870                  * ignored
6871                  */
6872                 fprintf(stderr,
6873                         "%s %s: xattr has been specified for non-foreign layout\n",
6874                         progname, argv[0]);
6875         } else if (foreign_mode && !xattr) {
6876                 fprintf(stderr,
6877                         "%s %s: xattr must be provided in foreign mode\n",
6878                         progname, argv[0]);
6879                 return CMD_HELP;
6880         }
6881
6882         if (foreign_mode && (delete || default_stripe || lsa.lsa_nr_tgts ||
6883             lsa.lsa_tgts || setstripe_args_specified(&lsa))) {
6884                 fprintf(stderr,
6885                         "%s %s: only --xattr/--flags/--mode options are valid with --foreign\n",
6886                         progname, argv[0]);
6887                 return CMD_HELP;
6888         }
6889
6890         if (!delete && lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT &&
6891             lsa.lsa_stripe_count == LLAPI_LAYOUT_DEFAULT && !foreign_mode) {
6892                 /* if no parameters set, create directory on least-used MDTs */
6893                 lsa.lsa_stripe_off = LMV_OFFSET_DEFAULT;
6894                 lsa.lsa_stripe_count = 1;
6895         }
6896
6897         if (delete &&
6898             (lsa.lsa_stripe_off != LLAPI_LAYOUT_DEFAULT ||
6899              lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT)) {
6900                 fprintf(stderr,
6901                         "%s %s: cannot specify -d with -c or -i options\n",
6902                         progname, argv[0]);
6903                 return CMD_HELP;
6904         }
6905
6906         if (mode_opt) {
6907                 mode = strtoul(mode_opt, &end, 8);
6908                 if (*end != '\0') {
6909                         fprintf(stderr,
6910                                 "%s %s: bad MODE '%s'\n",
6911                                 progname, argv[0], mode_opt);
6912                         return CMD_HELP;
6913                 }
6914                 previous_mode = umask(0);
6915         }
6916
6917         /* check max-inherit and warn user in some cases */
6918         if (default_stripe &&
6919             (lsa.lsa_stripe_count < 0 || lsa.lsa_stripe_count > 1)) {
6920                 if (max_inherit == LMV_INHERIT_UNLIMITED)
6921                         fprintf(stderr,
6922                         "%s %s: unrecommended max-inherit=-1 when default stripe-count=%lld\n",
6923                         progname, argv[0], lsa.lsa_stripe_count);
6924                 else if (max_inherit > LMV_INHERIT_DEFAULT_STRIPED + 2 &&
6925                          max_inherit != LMV_INHERIT_NONE)
6926                         fprintf(stderr,
6927                                 "%s %s: unrecommended max-inherit=%d when default stripe-count=%lld\n",
6928                                 progname, argv[0], max_inherit,
6929                                 lsa.lsa_stripe_count);
6930         }
6931
6932         if (max_inherit_rr != LAYOUT_INHERIT_UNSET &&
6933             lsa.lsa_stripe_off != LLAPI_LAYOUT_DEFAULT &&
6934             lsa.lsa_stripe_off != LMV_OFFSET_DEFAULT) {
6935                 fprintf(stderr,
6936                         "%s %s: max-inherit-rr needs mdt-index=-1, not %lld\n",
6937                         progname, argv[0], lsa.lsa_stripe_off);
6938                 return CMD_HELP;
6939         }
6940
6941         /* foreign LMV/dir case */
6942         if (foreign_mode) {
6943                 if (argc > optind + 1) {
6944                         fprintf(stderr,
6945                                 "%s %s: cannot specify multiple foreign dirs\n",
6946                                 progname, argv[0]);
6947                         return CMD_HELP;
6948                 }
6949
6950                 dname = argv[optind];
6951                 result = llapi_dir_create_foreign(dname, mode, type, flags,
6952                                                   xattr);
6953                 if (result != 0)
6954                         fprintf(stderr,
6955                                 "%s mkdir: can't create foreign dir '%s': %s\n",
6956                                 progname, dname, strerror(-result));
6957                 return result;
6958         }
6959
6960         /*
6961          * initialize stripe parameters, in case param is converted to specific,
6962          * i.e, 'lfs mkdir -i -1 -c N', always allocate space for lsp_tgts.
6963          */
6964         param = calloc(1, offsetof(typeof(*param),
6965                        lsp_tgts[lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT ?
6966                                 lsa.lsa_stripe_count : lsa.lsa_nr_tgts]));
6967         if (!param) {
6968                 fprintf(stderr,
6969                         "%s %s: cannot allocate memory for parameters: %s\n",
6970                         progname, argv[0], strerror(ENOMEM));
6971                 return CMD_HELP;
6972         }
6973
6974         /* if "lfs setdirstripe -D -i -1" is used, assume 1-stripe directory */
6975         if (default_stripe && lsa.lsa_stripe_off == LMV_OFFSET_DEFAULT &&
6976             (lsa.lsa_stripe_count == LLAPI_LAYOUT_DEFAULT ||
6977              lsa.lsa_stripe_count == 0))
6978                 lsa.lsa_stripe_count = 1;
6979         if (lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT)
6980                 param->lsp_stripe_count = lsa.lsa_stripe_count;
6981         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
6982                 param->lsp_stripe_offset = LMV_OFFSET_DEFAULT;
6983         else
6984                 param->lsp_stripe_offset = lsa.lsa_stripe_off;
6985         if (lsa.lsa_pattern != LLAPI_LAYOUT_RAID0)
6986                 param->lsp_stripe_pattern = lsa.lsa_pattern;
6987         else
6988                 param->lsp_stripe_pattern = LMV_HASH_TYPE_UNKNOWN;
6989         param->lsp_pool = lsa.lsa_pool_name;
6990         param->lsp_is_specific = false;
6991         if (max_inherit == LAYOUT_INHERIT_UNSET) {
6992                 if (lsa.lsa_stripe_count == 0 || lsa.lsa_stripe_count == 1)
6993                         max_inherit = LMV_INHERIT_DEFAULT_PLAIN;
6994                 else
6995                         max_inherit = LMV_INHERIT_DEFAULT_STRIPED;
6996         }
6997         param->lsp_max_inherit = max_inherit;
6998         if (default_stripe) {
6999
7000                 if (max_inherit_rr == LAYOUT_INHERIT_UNSET)
7001                         max_inherit_rr = LMV_INHERIT_RR_DEFAULT;
7002                 param->lsp_max_inherit_rr = max_inherit_rr;
7003         }
7004         if (strcmp(argv[0], "mkdir") == 0)
7005                 param->lsp_is_create = true;
7006         if (lsa.lsa_nr_tgts > 1) {
7007                 if (lsa.lsa_stripe_count > 0 &&
7008                     lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT &&
7009                     lsa.lsa_stripe_count != lsa.lsa_nr_tgts) {
7010                         fprintf(stderr,
7011                                 "error: %s: stripe count %lld doesn't match the number of MDTs: %d\n",
7012                                 argv[0], lsa.lsa_stripe_count,
7013                                 lsa.lsa_nr_tgts);
7014                         free(param);
7015                         return CMD_HELP;
7016                 }
7017
7018                 param->lsp_is_specific = true;
7019                 param->lsp_stripe_count = lsa.lsa_nr_tgts;
7020                 memcpy(param->lsp_tgts, mdts, sizeof(*mdts) * lsa.lsa_nr_tgts);
7021         }
7022
7023         dname = argv[optind];
7024         do {
7025                 if (default_stripe) {
7026                         result = llapi_dir_set_default_lmv(dname, param);
7027                         if (result)
7028                                 fprintf(stderr,
7029                                         "%s setdirstripe: cannot set default stripe on dir '%s': %s\n",
7030                                         progname, dname, strerror(-result));
7031                         continue;
7032                 }
7033
7034                 result = llapi_dir_create(dname, mode, param);
7035                 if (result)
7036                         fprintf(stderr,
7037                                 "%s setdirstripe: cannot create dir '%s': %s\n",
7038                                 progname, dname, strerror(-result));
7039         } while (!result && (dname = argv[++optind]));
7040
7041         if (mode_opt)
7042                 umask(previous_mode);
7043
7044         free(param);
7045         return result;
7046 }
7047
7048 /* functions */
7049 static int lfs_rmentry(int argc, char **argv)
7050 {
7051         char *dname;
7052         int   index;
7053         int   result = 0;
7054
7055         if (argc <= 1) {
7056                 fprintf(stderr, "error: %s: missing dirname\n",
7057                         argv[0]);
7058                 return CMD_HELP;
7059         }
7060
7061         index = 1;
7062         dname = argv[index];
7063         while (dname) {
7064                 result = llapi_direntry_remove(dname);
7065                 if (result) {
7066                         fprintf(stderr,
7067                                 "error: %s: remove dir entry '%s' failed\n",
7068                                 argv[0], dname);
7069                         break;
7070                 }
7071                 dname = argv[++index];
7072         }
7073         return result;
7074 }
7075
7076 static int lfs_unlink_foreign(int argc, char **argv)
7077 {
7078         char *name;
7079         int   index;
7080         int   result = 0;
7081
7082         if (argc <= 1) {
7083                 fprintf(stderr, "error: %s: missing pathname\n",
7084                         argv[0]);
7085                 return CMD_HELP;
7086         }
7087
7088         index = 1;
7089         name = argv[index];
7090         while (name != NULL) {
7091                 result = llapi_unlink_foreign(name);
7092                 if (result) {
7093                         fprintf(stderr,
7094                                 "error: %s: unlink foreign entry '%s' failed\n",
7095                                 argv[0], name);
7096                         break;
7097                 }
7098                 name = argv[++index];
7099         }
7100         return result;
7101 }
7102
7103 static int lfs_mv(int argc, char **argv)
7104 {
7105         struct lmv_user_md lmu = { LMV_USER_MAGIC };
7106         struct find_param param = {
7107                 .fp_max_depth = -1,
7108                 .fp_mdt_index = -1,
7109         };
7110         char *end;
7111         int c;
7112         int rc = 0;
7113         struct option long_opts[] = {
7114         { .val = 'm',   .name = "mdt",          .has_arg = required_argument },
7115         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument },
7116         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
7117         { .name = NULL } };
7118
7119         while ((c = getopt_long(argc, argv, "m:M:v", long_opts, NULL)) != -1) {
7120                 switch (c) {
7121 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
7122                 case 'M':
7123                         fprintf(stderr,
7124                                 "warning: '-M' deprecated, use '--mdt-index' or '-m' instead\n");
7125 #endif
7126                 case 'm':
7127                         errno = 0;
7128                         lmu.lum_stripe_offset = strtoul(optarg, &end, 0);
7129                         if (errno != 0 || *end != '\0' ||
7130                             lmu.lum_stripe_offset >= UINT32_MAX) {
7131                                 fprintf(stderr, "%s mv: bad MDT index '%s'\n",
7132                                         progname, optarg);
7133                                 return CMD_HELP;
7134                         }
7135                         break;
7136                 case 'v':
7137                         param.fp_verbose = VERBOSE_DETAIL;
7138                         break;
7139                 default:
7140                         fprintf(stderr, "%s mv: unrecognized option '%s'\n",
7141                                 progname, argv[optind - 1]);
7142                         return CMD_HELP;
7143                 }
7144         }
7145
7146         if (lmu.lum_stripe_offset == LMV_OFFSET_DEFAULT) {
7147                 fprintf(stderr, "%s mv: MDT index must be specified\n",
7148                         progname);
7149                 return CMD_HELP;
7150         }
7151
7152         if (optind >= argc) {
7153                 fprintf(stderr, "%s mv: DIR must be specified\n", progname);
7154                 return CMD_HELP;
7155         }
7156
7157         lmu.lum_hash_type = LMV_HASH_TYPE_UNKNOWN;
7158
7159         /* initialize migrate mdt parameters */
7160         param.fp_lmv_md = &lmu;
7161         param.fp_migrate = 1;
7162         rc = llapi_migrate_mdt(argv[optind], &param);
7163         if (rc != 0)
7164                 fprintf(stderr, "%s mv: cannot migrate '%s' to MDT%04x: %s\n",
7165                         progname, argv[optind], lmu.lum_stripe_offset,
7166                         strerror(-rc));
7167         return rc;
7168 }
7169
7170 static int lfs_osts(int argc, char **argv)
7171 {
7172         return lfs_tgts(argc, argv);
7173 }
7174
7175 static int lfs_mdts(int argc, char **argv)
7176 {
7177         return lfs_tgts(argc, argv);
7178 }
7179
7180 static int lfs_df(int argc, char **argv)
7181 {
7182         char mntdir[PATH_MAX] = {'\0'}, path[PATH_MAX] = {'\0'};
7183         enum mntdf_flags flags = MNTDF_SHOW;
7184         int ops = LL_STATFS_LMV | LL_STATFS_LOV;
7185         int c, rc = 0, rc1 = 0, index = 0, arg_idx = 0;
7186         char fsname[PATH_MAX] = "", *pool_name = NULL;
7187         struct option long_opts[] = {
7188         { .val = 'h',   .name = "human-readable", .has_arg = no_argument },
7189         { .val = 'H',   .name = "si",           .has_arg = no_argument },
7190         { .val = 'i',   .name = "inodes",       .has_arg = no_argument },
7191         { .val = 'l',   .name = "lazy",         .has_arg = no_argument },
7192         { .val = 'p',   .name = "pool",         .has_arg = required_argument },
7193         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
7194         { .name = NULL} };
7195
7196         while ((c = getopt_long(argc, argv, "hHilp:v", long_opts, NULL)) != -1) {
7197                 switch (c) {
7198                 case 'h':
7199                         flags = (flags & ~MNTDF_DECIMAL) | MNTDF_COOKED;
7200                         break;
7201                 case 'H':
7202                         flags |= MNTDF_COOKED | MNTDF_DECIMAL;
7203                         break;
7204                 case 'i':
7205                         flags |= MNTDF_INODES;
7206                         break;
7207                 case 'l':
7208                         flags |= MNTDF_LAZY;
7209                         break;
7210                 case 'p':
7211                         pool_name = optarg;
7212                         break;
7213                 case 'v':
7214                         flags |= MNTDF_VERBOSE;
7215                         break;
7216                 default:
7217                         fprintf(stderr, "%s: unrecognized option '%s'\n",
7218                                 progname, argv[optind - 1]);
7219                         return CMD_HELP;
7220                 }
7221         }
7222
7223         /* Handle case where path is not specified */
7224         if (optind == argc) {
7225                 while (!llapi_search_mounts(path, index++, mntdir, fsname)) {
7226                         /* Check if we have a mount point */
7227                         if (mntdir[0] == '\0')
7228                                 continue;
7229
7230                         rc = mntdf(mntdir, fsname, pool_name, flags, ops, NULL);
7231                         if (rc || path[0] != '\0')
7232                                 break;
7233
7234                         fsname[0] = '\0'; /* avoid matching in next loop */
7235                         mntdir[0] = '\0'; /* avoid matching in next loop */
7236                         path[0] = '\0'; /* clean for next loop */
7237                 }
7238                 return rc;
7239         }
7240
7241         /* Loop through all the remaining arguments. These are Lustre FS
7242          * paths.
7243          */
7244         for (arg_idx = optind; arg_idx <= argc - 1; arg_idx++) {
7245                 bool valid = false;
7246
7247                 fsname[0] = '\0'; /* start clean */
7248                 mntdir[0] = '\0'; /* start clean */
7249                 path[0] = '\0';   /* start clean */
7250
7251                 /* path does not exists at all */
7252                 if (!realpath(argv[arg_idx], path)) {
7253                         rc = -errno;
7254                         fprintf(stderr, "error: invalid path '%s': %s\n",
7255                                 argv[arg_idx], strerror(-rc));
7256                         /* save first seen error */
7257                         if (!rc1)
7258                                 rc1 = rc;
7259
7260                         continue;
7261                 }
7262
7263                 /* path exists but may not be a Lustre filesystem */
7264                 while (!llapi_search_mounts(path, index++, mntdir, fsname)) {
7265                         /* Check if we have a mount point */
7266                         if (mntdir[0] == '\0')
7267                                 continue;
7268
7269                         rc = mntdf(mntdir, fsname, pool_name, flags, ops, NULL);
7270                         if (rc || path[0] != '\0') {
7271                                 valid = true;
7272
7273                                 /* save first seen error */
7274                                 if (!rc1)
7275                                         rc1 = rc;
7276                                 break;
7277                         }
7278                 }
7279
7280                 if (!valid) {
7281                         llapi_printf(LLAPI_MSG_ERROR,
7282                                      "%s:%s Not a Lustre filesystem\n",
7283                                      argv[0], argv[arg_idx]);
7284                         /* save first seen error */
7285                         if (!rc1)
7286                                 rc1 = -EOPNOTSUPP;
7287                 }
7288         }
7289
7290         return rc1;
7291 }
7292
7293 static int print_instance(const char *mntdir, char *buf, size_t buflen,
7294                           bool opt_instance, bool opt_fsname, bool opt_mntdir)
7295 {
7296         int rc = 0;
7297
7298         if (opt_fsname == opt_instance) { /* both true or both false */
7299                 rc = llapi_getname(mntdir, buf, buflen);
7300         } else if (opt_fsname) {
7301                 /*
7302                  * llapi_search_mounts() fills @buf with fsname, but that is not
7303                  * called if explicit paths are specified on the command-line
7304                  */
7305                 if (buf[0] == '\0')
7306                         rc = llapi_get_fsname(mntdir, buf, buflen);
7307         } else /* if (opt_instance) */ {
7308                 rc = llapi_get_instance(mntdir, buf, buflen);
7309         }
7310
7311         if (rc < 0) {
7312                 fprintf(stderr, "cannot get instance for '%s': %s\n",
7313                         mntdir, strerror(-rc));
7314                 return rc;
7315         }
7316
7317         if (opt_mntdir)
7318                 printf("%s %s\n", buf, mntdir);
7319         else
7320                 printf("%s\n", buf);
7321
7322         return 0;
7323 }
7324
7325 static int lfs_getname(int argc, char **argv)
7326 {
7327         struct option long_opts[] = {
7328         { .val = 'h',   .name = "help",         .has_arg = no_argument },
7329         { .val = 'i',   .name = "instance",     .has_arg = no_argument },
7330         { .val = 'n',   .name = "fsname",       .has_arg = no_argument },
7331         { .name = NULL} };
7332         bool opt_instance = false, opt_fsname = false;
7333         char fsname[PATH_MAX] = "";
7334         int rc = 0, rc2, c;
7335
7336         while ((c = getopt_long(argc, argv, "hin", long_opts, NULL)) != -1) {
7337                 switch (c) {
7338                 case 'i':
7339                         opt_instance = true;
7340                         break;
7341                 case 'n':
7342                         opt_fsname = true;
7343                         break;
7344                 default:
7345                         fprintf(stderr, "%s: unrecognized option '%s'\n",
7346                                 progname, argv[optind - 1]);
7347                         fallthrough;
7348                 case 'h':
7349                         return CMD_HELP;
7350                 }
7351         }
7352
7353         if (optind == argc) { /* no paths specified, get all paths. */
7354                 char mntdir[PATH_MAX] = "", path[PATH_MAX] = "";
7355                 int index = 0;
7356
7357                 while (!llapi_search_mounts(path, index++, mntdir, fsname)) {
7358                         rc2 = print_instance(mntdir, fsname, sizeof(fsname),
7359                                              opt_instance, opt_fsname, true);
7360                         if (!rc)
7361                                 rc = rc2;
7362                         path[0] = fsname[0] = mntdir[0] = '\0';
7363                 }
7364         } else { /* paths specified, only attempt to search these. */
7365                 bool opt_mntdir;
7366
7367                 /* if only one path is given, print only requested info */
7368                 opt_mntdir = argc - optind > 1 || (opt_instance == opt_fsname);
7369
7370                 for (; optind < argc; optind++) {
7371                         rc2 = print_instance(argv[optind], fsname,
7372                                              sizeof(fsname), opt_instance,
7373                                              opt_fsname, opt_mntdir);
7374                         if (!rc)
7375                                 rc = rc2;
7376                         fsname[0] = '\0';
7377                 }
7378         }
7379
7380         return rc;
7381 }
7382
7383 static int lfs_check(int argc, char **argv)
7384 {
7385         char mntdir[PATH_MAX] = {'\0'}, path[PATH_MAX] = {'\0'};
7386         int num_types = 1;
7387         char *obd_types[3];
7388         char obd_type1[4];
7389         char obd_type2[4];
7390         char obd_type3[4];
7391         int rc;
7392
7393         if (argc < 2 || argc > 3) {
7394                 fprintf(stderr, "%s check: server type must be specified\n",
7395                         progname);
7396                 return CMD_HELP;
7397         }
7398
7399         obd_types[0] = obd_type1;
7400         obd_types[1] = obd_type2;
7401         obd_types[2] = obd_type3;
7402
7403         if (strcmp(argv[1], "osts") == 0) {
7404                 strcpy(obd_types[0], "osc");
7405         } else if (strcmp(argv[1], "mdts") == 0 ||
7406                    strcmp(argv[1], "mds") == 0) {
7407                 strcpy(obd_types[0], "mdc");
7408         } else if (strcmp(argv[1], "mgts") == 0) {
7409                 strcpy(obd_types[0], "mgc");
7410         } else if (strcmp(argv[1], "all") == 0 ||
7411                    strcmp(argv[1], "servers") == 0) {
7412                 num_types = 3;
7413                 strcpy(obd_types[0], "osc");
7414                 strcpy(obd_types[1], "mdc");
7415                 strcpy(obd_types[2], "mgc");
7416         } else {
7417                 fprintf(stderr, "%s check: unrecognized option '%s'\n",
7418                         progname, argv[1]);
7419                 return CMD_HELP;
7420         }
7421
7422         if (argc >= 3 && !realpath(argv[2], path)) {
7423                 rc = -errno;
7424                 fprintf(stderr, "error: invalid path '%s': %s\n",
7425                         argv[2], strerror(-rc));
7426                 return rc;
7427         }
7428
7429         rc = llapi_search_mounts(path, 0, mntdir, NULL);
7430         if (rc < 0 || mntdir[0] == '\0') {
7431                 fprintf(stderr,
7432                         "%s check: cannot find mounted Lustre filesystem: %s\n",
7433                         progname, (rc < 0) ? strerror(-rc) : strerror(ENODEV));
7434                 return rc;
7435         }
7436
7437         rc = llapi_target_check(num_types, obd_types, path);
7438         if (rc)
7439                 fprintf(stderr, "%s check: cannot check target '%s': %s\n",
7440                         progname, argv[1], strerror(-rc));
7441
7442         return rc;
7443 }
7444
7445 #ifdef HAVE_SYS_QUOTA_H
7446 #define ADD_OVERFLOW(a, b) \
7447                      ((((a) + (b)) < (a)) ? \
7448                       ((a) = ULONG_MAX) : ((a) = (a) + (b)))
7449
7450 /* Convert format time string "XXwXXdXXhXXmXXs" into seconds value
7451  * returns the value or ULONG_MAX on integer overflow or incorrect format
7452  * Notes:
7453  *        1. the order of specifiers is arbitrary (may be: 5w3s or 3s5w)
7454  *        2. specifiers may be encountered multiple times (2s3s is 5 seconds)
7455  *        3. empty integer value is interpreted as 0
7456  */
7457 static unsigned long str2sec(const char *timestr)
7458 {
7459         const char spec[] = "smhdw";
7460         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
7461         unsigned long val = 0;
7462         char *tail;
7463
7464         if (strpbrk(timestr, spec) == NULL) {
7465                 /*
7466                  * no specifiers inside the time string,
7467                  * should treat it as an integer value
7468                  */
7469                 val = strtoul(timestr, &tail, 10);
7470                 return *tail ? ULONG_MAX : val;
7471         }
7472
7473         /* format string is XXwXXdXXhXXmXXs */
7474         while (*timestr) {
7475                 unsigned long v;
7476                 int ind;
7477                 char *ptr;
7478
7479                 v = strtoul(timestr, &tail, 10);
7480                 if (v == ULONG_MAX || *tail == '\0')
7481                         /*
7482                          * value too large (ULONG_MAX or more)
7483                          * or missing specifier
7484                          */
7485                         goto error;
7486
7487                 ptr = strchr(spec, *tail);
7488                 if (!ptr)
7489                         /* unknown specifier */
7490                         goto error;
7491
7492                 ind = ptr - spec;
7493
7494                 /* check if product will overflow the type */
7495                 if (!(v < ULONG_MAX / mult[ind]))
7496                         goto error;
7497
7498                 ADD_OVERFLOW(val, mult[ind] * v);
7499                 if (val == ULONG_MAX)
7500                         goto error;
7501
7502                 timestr = tail + 1;
7503         }
7504
7505         return val;
7506
7507 error:
7508         return ULONG_MAX;
7509 }
7510
7511 #define ARG2ULL(nr, str, def_units)                                     \
7512 do {                                                                    \
7513         unsigned long long limit, units = def_units;                    \
7514         int rc;                                                         \
7515                                                                         \
7516         rc = llapi_parse_size(str, &limit, &units, 1);                  \
7517         if (rc < 0) {                                                   \
7518                 fprintf(stderr, "%s: invalid limit '%s'\n",             \
7519                         progname, str);                                 \
7520                 return CMD_HELP;                                        \
7521         }                                                               \
7522         nr = limit;                                                     \
7523 } while (0)
7524
7525 static inline int has_times_option(int argc, char **argv)
7526 {
7527         int i;
7528
7529         for (i = 1; i < argc; i++)
7530                 if (!strcmp(argv[i], "-t"))
7531                         return 1;
7532
7533         return 0;
7534 }
7535
7536 static inline int lfs_verify_poolarg(char *pool)
7537 {
7538         if (strnlen(optarg, LOV_MAXPOOLNAME + 1) > LOV_MAXPOOLNAME) {
7539                 fprintf(stderr,
7540                         "Pool name '%.*s' is longer than %d\n",
7541                         LOV_MAXPOOLNAME, pool, LOV_MAXPOOLNAME);
7542                 return 1;
7543         }
7544         return 0;
7545 }
7546
7547 /* special grace time, only notify the user when its quota is over soft limit
7548  * but doesn't block new writes until the hard limit is reached.
7549  */
7550 #define NOTIFY_GRACE            "notify"
7551 #define NOTIFY_GRACE_TIME       LQUOTA_GRACE_MASK
7552
7553 #ifndef toqb
7554 static inline __u64 lustre_stoqb(size_t space)
7555 {
7556         return (space + QIF_DQBLKSIZE - 1) >> QIF_DQBLKSIZE_BITS;
7557 }
7558 #else
7559 #define lustre_stoqb   toqb
7560 #endif
7561
7562 int lfs_setquota_times(int argc, char **argv, struct if_quotactl *qctl)
7563 {
7564         int c, rc;
7565         char *mnt, *obd_type = (char *)qctl->obd_type;
7566         struct obd_dqblk *dqb = &qctl->qc_dqblk;
7567         struct obd_dqinfo *dqi = &qctl->qc_dqinfo;
7568         struct option long_opts[] = {
7569         { .val = 'b',   .name = "block-grace",  .has_arg = required_argument },
7570         { .val = 'g',   .name = "group",        .has_arg = no_argument },
7571         { .val = 'h',   .name = "help",         .has_arg = no_argument },
7572         { .val = 'i',   .name = "inode-grace",  .has_arg = required_argument },
7573         { .val = 'p',   .name = "projid",       .has_arg = no_argument },
7574         { .val = 't',   .name = "times",        .has_arg = no_argument },
7575         { .val = 'u',   .name = "user",         .has_arg = no_argument },
7576         { .val = LFS_POOL_OPT,
7577                         .name = "pool",         .has_arg = required_argument },
7578         { .name = NULL } };
7579         int qtype;
7580
7581         qctl->qc_cmd  = LUSTRE_Q_SETINFO;
7582         qctl->qc_type = ALLQUOTA;
7583
7584         while ((c = getopt_long(argc, argv, "b:ghi:ptu",
7585                                 long_opts, NULL)) != -1) {
7586                 switch (c) {
7587                 case 'u':
7588                         qtype = USRQUOTA;
7589                         goto quota_type;
7590                 case 'g':
7591                         qtype = GRPQUOTA;
7592                         goto quota_type;
7593                 case 'p':
7594                         qtype = PRJQUOTA;
7595 quota_type:
7596                         if (qctl->qc_type != ALLQUOTA) {
7597                                 fprintf(stderr,
7598                                         "%s: -u/g/p cannot be used more than once\n",
7599                                         progname);
7600                                 return CMD_HELP;
7601                         }
7602                         qctl->qc_type = qtype;
7603                         break;
7604                 case 'b':
7605                         if (strncmp(optarg, NOTIFY_GRACE,
7606                                     strlen(NOTIFY_GRACE)) == 0) {
7607                                 dqi->dqi_bgrace = NOTIFY_GRACE_TIME;
7608                         } else {
7609                                 dqi->dqi_bgrace = str2sec(optarg);
7610                                 if (dqi->dqi_bgrace >= NOTIFY_GRACE_TIME) {
7611                                         fprintf(stderr,
7612                                                 "%s: bad block-grace: %s\n",
7613                                                 progname, optarg);
7614                                         return CMD_HELP;
7615                                 }
7616                         }
7617                         dqb->dqb_valid |= QIF_BTIME;
7618                         break;
7619                 case 'i':
7620                         if (strncmp(optarg, NOTIFY_GRACE,
7621                                     strlen(NOTIFY_GRACE)) == 0) {
7622                                 dqi->dqi_igrace = NOTIFY_GRACE_TIME;
7623                         } else {
7624                                 dqi->dqi_igrace = str2sec(optarg);
7625                                 if (dqi->dqi_igrace >= NOTIFY_GRACE_TIME) {
7626                                         fprintf(stderr,
7627                                                 "%s: bad inode-grace: %s\n",
7628                                                 progname, optarg);
7629                                         return CMD_HELP;
7630                                 }
7631                         }
7632                         dqb->dqb_valid |= QIF_ITIME;
7633                         break;
7634                 case 't': /* Yes, of course! */
7635                         break;
7636                 case LFS_POOL_OPT:
7637                         if (lfs_verify_poolarg(optarg))
7638                                 return -1;
7639                         strncpy(qctl->qc_poolname, optarg, LOV_MAXPOOLNAME);
7640                         qctl->qc_cmd  = LUSTRE_Q_SETINFOPOOL;
7641                         break;
7642                 /* getopt prints error message for us when opterr != 0 */
7643                 default:
7644                         fprintf(stderr, "%s: unrecognized option '%s'\n",
7645                                 progname, argv[optind - 1]);
7646                         fallthrough;
7647                 case 'h':
7648                         return CMD_HELP;
7649                 }
7650         }
7651
7652         if (qctl->qc_type == ALLQUOTA) {
7653                 fprintf(stderr, "%s: neither -u, -g nor -p specified\n",
7654                         progname);
7655                 return CMD_HELP;
7656         }
7657
7658         if (optind != argc - 1) {
7659                 fprintf(stderr, "%s: unexpected parameter '%s'\n",
7660                         progname, argv[optind + 1]);
7661                 return CMD_HELP;
7662         }
7663
7664         mnt = argv[optind];
7665         rc = llapi_quotactl(mnt, qctl);
7666         if (rc) {
7667                 if (*obd_type)
7668                         fprintf(stderr, "%s %s ", obd_type,
7669                                 obd_uuid2str(&qctl->obd_uuid));
7670                 fprintf(stderr, "setquota failed: %s\n", strerror(-rc));
7671                 return rc;
7672         }
7673
7674         return 0;
7675 }
7676
7677 #define BSLIMIT (1 << 0)
7678 #define BHLIMIT (1 << 1)
7679 #define ISLIMIT (1 << 2)
7680 #define IHLIMIT (1 << 3)
7681
7682 int lfs_setquota(int argc, char **argv)
7683 {
7684         int c, rc = 0;
7685         struct if_quotactl *qctl;
7686         char *mnt, *obd_type;
7687         struct obd_dqblk *dqb;
7688         struct option long_opts[] = {
7689         { .val = 'b',   .name = "block-softlimit",
7690                                                 .has_arg = required_argument },
7691         { .val = 'B',   .name = "block-hardlimit",
7692                                                 .has_arg = required_argument },
7693         { .val = 'd',   .name = "default",      .has_arg = no_argument },
7694         { .val = LFS_SETQUOTA_DELETE,
7695                         .name = "delete",       .has_arg = no_argument },
7696         { .val = 'g',   .name = "group",        .has_arg = required_argument },
7697         { .val = 'G',   .name = "default-grp",  .has_arg = no_argument },
7698         { .val = 'h',   .name = "help",         .has_arg = no_argument },
7699         { .val = 'i',   .name = "inode-softlimit",
7700                                                 .has_arg = required_argument },
7701         { .val = 'I',   .name = "inode-hardlimit",
7702                                                 .has_arg = required_argument },
7703         { .val = 'p',   .name = "projid",       .has_arg = required_argument },
7704         { .val = 'P',   .name = "default-prj",  .has_arg = no_argument },
7705         { .val = 'u',   .name = "user",         .has_arg = required_argument },
7706         { .val = 'U',   .name = "default-usr",  .has_arg = no_argument },
7707         { .val = LFS_POOL_OPT,
7708                         .name = "pool",         .has_arg = required_argument },
7709         { .name = NULL } };
7710         unsigned int limit_mask = 0;
7711         bool use_default = false;
7712         int qtype, qctl_len;
7713
7714         qctl_len = sizeof(*qctl) + LOV_MAXPOOLNAME + 1;
7715         qctl = malloc(qctl_len);
7716         if (!qctl)
7717                 return -ENOMEM;
7718
7719         memset(qctl, 0, qctl_len);
7720         obd_type = (char *)qctl->obd_type;
7721         dqb = &qctl->qc_dqblk;
7722
7723         if (has_times_option(argc, argv)) {
7724                 rc = lfs_setquota_times(argc, argv, qctl);
7725                 goto out;
7726         }
7727
7728         qctl->qc_cmd  = LUSTRE_Q_SETQUOTA;
7729         qctl->qc_type = ALLQUOTA; /* ALLQUOTA makes no sense for setquota,
7730                                    * so it can be used as a marker that qc_type
7731                                    * isn't reinitialized from command line
7732                                    */
7733         while ((c = getopt_long(argc, argv, "b:B:dDg:Ghi:I:p:Pu:U",
7734                 long_opts, NULL)) != -1) {
7735                 switch (c) {
7736                 case 'U':
7737                         qctl->qc_cmd = LUSTRE_Q_SETDEFAULT;
7738                         qtype = USRQUOTA;
7739                         qctl->qc_id = 0;
7740                         goto quota_type_def;
7741                 case 'u':
7742                         qtype = USRQUOTA;
7743                         rc = name2uid(&qctl->qc_id, optarg);
7744                         goto quota_type;
7745                 case 'G':
7746                         qctl->qc_cmd = LUSTRE_Q_SETDEFAULT;
7747                         qtype = GRPQUOTA;
7748                         qctl->qc_id = 0;
7749                         goto quota_type_def;
7750                 case 'g':
7751                         qtype = GRPQUOTA;
7752                         rc = name2gid(&qctl->qc_id, optarg);
7753                         goto quota_type;
7754                 case 'P':
7755                         qctl->qc_cmd = LUSTRE_Q_SETDEFAULT;
7756                         qtype = PRJQUOTA;
7757                         qctl->qc_id = 0;
7758                         goto quota_type_def;
7759                 case 'p':
7760                         qtype = PRJQUOTA;
7761                         rc = name2projid(&qctl->qc_id, optarg);
7762 quota_type:
7763                         if (rc) {
7764                                 if (str2quotaid(&qctl->qc_id, optarg)) {
7765                                         fprintf(stderr,
7766                                                 "%s setquota: invalid id '%s'\n",
7767                                                 progname, optarg);
7768                                         rc = -1;
7769                                         goto out;
7770                                 }
7771                         }
7772
7773                         if (qctl->qc_id == 0) {
7774                                 fprintf(stderr,
7775                                         "%s setquota: can't set quota for root usr/group/project.\n",
7776                                         progname);
7777                                 rc = -1;
7778                                 goto out;
7779                         }
7780
7781 quota_type_def:
7782                         if (qctl->qc_type != ALLQUOTA) {
7783                                 fprintf(stderr,
7784                                         "%s setquota: only one of -u, -U, -g, -G, -p or -P may be specified\n",
7785                                         progname);
7786                                 rc = CMD_HELP;
7787                                 goto out;
7788                         }
7789                         qctl->qc_type = qtype;
7790                         break;
7791 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
7792                 case 'd':
7793 #if LUSTRE_VERSION_CODE > OBD_OCD_VERSION(2, 15, 53, 0)
7794                         fprintf(stderr, "'-d' deprecatd, use '-D' or '--default'\n");
7795 #endif
7796                         /* falltrrough */
7797 #endif
7798                 case 'D':
7799                         use_default = true;
7800                         qctl->qc_cmd = LUSTRE_Q_SETDEFAULT;
7801                         break;
7802                 case LFS_SETQUOTA_DELETE:
7803                         qctl->qc_cmd = LUSTRE_Q_DELETEQID;
7804                         break;
7805                 case 'b':
7806                         ARG2ULL(dqb->dqb_bsoftlimit, optarg, 1024);
7807                         dqb->dqb_bsoftlimit >>= 10;
7808                         limit_mask |= BSLIMIT;
7809                         if (dqb->dqb_bsoftlimit &&
7810                             dqb->dqb_bsoftlimit <= 1024) /* <= 1M? */
7811                                 fprintf(stderr,
7812                                         "%s setquota: warning: block softlimit '%llu' smaller than minimum qunit size\nSee '%s help setquota' or Lustre manual for details\n",
7813                                         progname,
7814                                         (unsigned long long)dqb->dqb_bsoftlimit,
7815                                         progname);
7816                         break;
7817                 case 'B':
7818                         ARG2ULL(dqb->dqb_bhardlimit, optarg, 1024);
7819                         dqb->dqb_bhardlimit >>= 10;
7820                         limit_mask |= BHLIMIT;
7821                         if (dqb->dqb_bhardlimit &&
7822                             dqb->dqb_bhardlimit <= 1024) /* <= 1M? */
7823                                 fprintf(stderr,
7824                                         "%s setquota: warning: block hardlimit '%llu' smaller than minimum qunit size\n"
7825                                         "See '%s help setquota' or Lustre manual for details\n",
7826                                         progname,
7827                                         (unsigned long long)dqb->dqb_bhardlimit,
7828                                         progname);
7829                         break;
7830                 case 'i':
7831                         ARG2ULL(dqb->dqb_isoftlimit, optarg, 1);
7832                         limit_mask |= ISLIMIT;
7833                         if (dqb->dqb_isoftlimit &&
7834                             dqb->dqb_isoftlimit <= 1024) /* <= 1K inodes? */
7835                                 fprintf(stderr,
7836                                         "%s setquota: warning: inode softlimit '%llu' smaller than minimum qunit size\nSee '%s help setquota' or Lustre manual for details\n",
7837                                         progname,
7838                                         (unsigned long long)dqb->dqb_isoftlimit,
7839                                         progname);
7840                         break;
7841                 case 'I':
7842                         ARG2ULL(dqb->dqb_ihardlimit, optarg, 1);
7843                         limit_mask |= IHLIMIT;
7844                         if (dqb->dqb_ihardlimit &&
7845                             dqb->dqb_ihardlimit <= 1024) /* <= 1K inodes? */
7846                                 fprintf(stderr,
7847                                         "%s setquota: warning: inode hardlimit '%llu' smaller than minimum qunit size\nSee '%s help setquota' or Lustre manual for details\n",
7848                                         progname,
7849                                         (unsigned long long)dqb->dqb_ihardlimit,
7850                                         progname);
7851                         break;
7852                 case LFS_POOL_OPT:
7853                         if (lfs_verify_poolarg(optarg)) {
7854                                 rc = -1;
7855                                 goto out;
7856                         }
7857                         strncpy(qctl->qc_poolname, optarg, LOV_MAXPOOLNAME);
7858                         qctl->qc_cmd = qctl->qc_cmd == LUSTRE_Q_SETDEFAULT ?
7859                                                 LUSTRE_Q_SETDEFAULT_POOL :
7860                                                 LUSTRE_Q_SETQUOTAPOOL;
7861                         break;
7862                 default:
7863                         fprintf(stderr,
7864                                 "%s setquota: unrecognized option '%s'\n",
7865                                 progname, argv[optind - 1]);
7866                         fallthrough;
7867                 case 'h':
7868                         rc = CMD_HELP;
7869                         goto out;
7870                 }
7871         }
7872
7873         if (qctl->qc_type == ALLQUOTA) {
7874                 fprintf(stderr,
7875                         "%s setquota: either -u or -g must be specified\n",
7876                         progname);
7877                 rc = CMD_HELP;
7878                 goto out;
7879         }
7880
7881         if (!use_default && qctl->qc_cmd != LUSTRE_Q_DELETEQID &&
7882             limit_mask == 0) {
7883                 fprintf(stderr,
7884                         "%s setquota: at least one limit must be specified\n",
7885                         progname);
7886                 rc = CMD_HELP;
7887                 goto out;
7888         }
7889
7890         if ((use_default || qctl->qc_cmd == LUSTRE_Q_DELETEQID)  &&
7891             limit_mask != 0) {
7892                 fprintf(stderr,
7893                         "%s setquota: limits should not be specified when using default quota or deleting quota ID\n",
7894                         progname);
7895                 rc = CMD_HELP;
7896                 goto out;
7897         }
7898
7899         if (use_default && qctl->qc_id == 0) {
7900                 fprintf(stderr,
7901                         "%s setquota: can not set default quota for root user/group/project\n",
7902                         progname);
7903                 rc = CMD_HELP;
7904                 goto out;
7905         }
7906
7907         if (qctl->qc_cmd == LUSTRE_Q_DELETEQID  && qctl->qc_id == 0) {
7908                 fprintf(stderr,
7909                         "%s setquota: can not delete root user/group/project\n",
7910                         progname);
7911                 rc = CMD_HELP;
7912                 goto out;
7913         }
7914
7915         if (optind != argc - 1) {
7916                 fprintf(stderr,
7917                         "%s setquota: filesystem not specified or unexpected argument '%s'\n",
7918                         progname, argv[optind]);
7919                 rc = CMD_HELP;
7920                 goto out;
7921         }
7922
7923         mnt = argv[optind];
7924
7925         if (use_default) {
7926                 dqb->dqb_bhardlimit = 0;
7927                 dqb->dqb_bsoftlimit = 0;
7928                 dqb->dqb_ihardlimit = 0;
7929                 dqb->dqb_isoftlimit = 0;
7930                 dqb->dqb_itime = 0;
7931                 dqb->dqb_btime = 0;
7932                 dqb->dqb_valid |= QIF_LIMITS | QIF_TIMES;
7933                 /* do not set inode limits for Pool Quotas */
7934                 if (qctl->qc_cmd  == LUSTRE_Q_SETDEFAULT_POOL)
7935                         dqb->dqb_valid ^= QIF_ILIMITS | QIF_ITIME;
7936         } else if ((!(limit_mask & BHLIMIT) ^ !(limit_mask & BSLIMIT)) ||
7937                    (!(limit_mask & IHLIMIT) ^ !(limit_mask & ISLIMIT))) {
7938                 /* sigh, we can't just set blimits/ilimits */
7939                 struct if_quotactl *tmp_qctl;
7940
7941                 tmp_qctl = calloc(1, sizeof(*qctl) + LOV_MAXPOOLNAME + 1);
7942                 if (!tmp_qctl)
7943                         goto out;
7944
7945                 if (qctl->qc_cmd == LUSTRE_Q_SETQUOTAPOOL) {
7946                         tmp_qctl->qc_cmd = LUSTRE_Q_GETQUOTAPOOL;
7947                         strncpy(tmp_qctl->qc_poolname, qctl->qc_poolname,
7948                                 LOV_MAXPOOLNAME);
7949                 } else {
7950                         tmp_qctl->qc_cmd  = LUSTRE_Q_GETQUOTA;
7951                 }
7952                 tmp_qctl->qc_type = qctl->qc_type;
7953                 tmp_qctl->qc_id = qctl->qc_id;
7954
7955                 rc = llapi_quotactl(mnt, tmp_qctl);
7956                 if (rc < 0) {
7957                         free(tmp_qctl);
7958                         goto out;
7959                 }
7960
7961                 if (!(limit_mask & BHLIMIT))
7962                         dqb->dqb_bhardlimit = tmp_qctl->qc_dqblk.dqb_bhardlimit;
7963                 if (!(limit_mask & BSLIMIT))
7964                         dqb->dqb_bsoftlimit = tmp_qctl->qc_dqblk.dqb_bsoftlimit;
7965                 if (!(limit_mask & IHLIMIT))
7966                         dqb->dqb_ihardlimit = tmp_qctl->qc_dqblk.dqb_ihardlimit;
7967                 if (!(limit_mask & ISLIMIT))
7968                         dqb->dqb_isoftlimit = tmp_qctl->qc_dqblk.dqb_isoftlimit;
7969
7970                 /* Keep grace times if we have got no softlimit arguments */
7971                 if ((limit_mask & BHLIMIT) && !(limit_mask & BSLIMIT)) {
7972                         dqb->dqb_valid |= QIF_BTIME;
7973                         dqb->dqb_btime = tmp_qctl->qc_dqblk.dqb_btime;
7974                 }
7975
7976                 if ((limit_mask & IHLIMIT) && !(limit_mask & ISLIMIT)) {
7977                         dqb->dqb_valid |= QIF_ITIME;
7978                         dqb->dqb_itime = tmp_qctl->qc_dqblk.dqb_itime;
7979                 }
7980                 free(tmp_qctl);
7981         }
7982
7983         dqb->dqb_valid |= (limit_mask & (BHLIMIT | BSLIMIT)) ? QIF_BLIMITS : 0;
7984         dqb->dqb_valid |= (limit_mask & (IHLIMIT | ISLIMIT)) ? QIF_ILIMITS : 0;
7985
7986         rc = llapi_quotactl(mnt, qctl);
7987         if (rc) {
7988                 if (*obd_type)
7989                         fprintf(stderr,
7990                                 "%s setquota: cannot quotactl '%s' '%s': %s\n",
7991                                 progname, obd_type,
7992                                 obd_uuid2str(&qctl->obd_uuid), strerror(-rc));
7993                 else
7994                         fprintf(stderr,
7995                                 "%s setquota: quotactl failed: %s\n",
7996                                 progname, strerror(-rc));
7997         }
7998 out:
7999         if (rc)
8000                 fprintf(stderr, "setquota failed: %s\n", strerror(-rc));
8001
8002         free(qctl);
8003         return rc;
8004 }
8005
8006 /* Converts seconds value into format string
8007  * result is returned in buf
8008  * Notes:
8009  *        1. result is in descenting order: 1w2d3h4m5s
8010  *        2. zero fields are not filled (except for p. 3): 5d1s
8011  *        3. zero seconds value is presented as "0s"
8012  */
8013 static char *__sec2str(time_t seconds, char *buf)
8014 {
8015         const char spec[] = "smhdw";
8016         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
8017         unsigned long c;
8018         char *tail = buf;
8019         int i;
8020
8021         for (i = ARRAY_SIZE(mult) - 1 ; i >= 0; i--) {
8022                 c = seconds / mult[i];
8023
8024                 if (c > 0 || (i == 0 && buf == tail))
8025                         tail += scnprintf(tail, 40-(tail-buf), "%lu%c", c,
8026                                           spec[i]);
8027
8028                 seconds %= mult[i];
8029         }
8030
8031         return tail;
8032 }
8033
8034 static void sec2str(time_t seconds, char *buf, int rc)
8035 {
8036         char *tail = buf;
8037
8038         if (rc)
8039                 *tail++ = '[';
8040
8041         tail = __sec2str(seconds, tail);
8042
8043         if (rc && tail - buf < 39) {
8044                 *tail++ = ']';
8045                 *tail++ = 0;
8046         }
8047 }
8048
8049 static void diff2str(time_t seconds, char *buf, time_t now)
8050 {
8051         buf[0] = 0;
8052         if (!seconds)
8053                 return;
8054         if (seconds <= now) {
8055                 strcpy(buf, "expired");
8056                 return;
8057         }
8058         __sec2str(seconds - now, buf);
8059 }
8060
8061 static void print_quota_title(char *name, struct if_quotactl *qctl,
8062                               bool human_readable, bool show_default)
8063 {
8064         if (show_default) {
8065                 printf("Disk default %s quota:\n", qtype_name(qctl->qc_type));
8066                 printf("%15s %8s%8s%8s %8s%8s%8s\n",
8067                        "Filesystem", "bquota", "blimit", "bgrace",
8068                        "iquota", "ilimit", "igrace");
8069         } else {
8070                 printf("Disk quotas for %s %s (%cid %u):\n",
8071                        qtype_name(qctl->qc_type), name,
8072                        *qtype_name(qctl->qc_type), qctl->qc_id);
8073                 printf("%15s%8s %7s%8s%8s%8s %7s%8s%8s\n",
8074                        "Filesystem", human_readable ? "used" : "kbytes",
8075                        "quota", "limit", "grace",
8076                        "files", "quota", "limit", "grace");
8077         }
8078 }
8079
8080 static void kbytes2str(__u64 num, char *buf, int buflen, bool h)
8081 {
8082         if (!h) {
8083                 snprintf(buf, buflen, "%ju", (uintmax_t)num);
8084         } else {
8085                 if (num >> 40)
8086                         snprintf(buf, buflen, "%5.4gP",
8087                                  (double)num / ((__u64)1 << 40));
8088                 else if (num >> 30)
8089                         snprintf(buf, buflen, "%5.4gT",
8090                                  (double)num / (1 << 30));
8091                 else if (num >> 20)
8092                         snprintf(buf, buflen, "%5.4gG",
8093                                  (double)num / (1 << 20));
8094                 else if (num >> 10)
8095                         snprintf(buf, buflen, "%5.4gM",
8096                                  (double)num / (1 << 10));
8097                 else
8098                         snprintf(buf, buflen, "%ju%s", (uintmax_t)num, "k");
8099         }
8100 }
8101
8102 #ifdef HAVE_NATIVE_CLIENT
8103 /* In the current Lustre implementation, the grace time is either the time
8104  * or the timestamp to be used after some quota ID exceeds the soft limt,
8105  * 48 bits should be enough, its high 16 bits can be used as quota flags.
8106  */
8107 #define LQUOTA_GRACE_BITS       48
8108 #define LQUOTA_GRACE_MASK       ((1ULL << LQUOTA_GRACE_BITS) - 1)
8109 #define LQUOTA_GRACE_MAX        LQUOTA_GRACE_MASK
8110 #define LQUOTA_GRACE(t)         (t & LQUOTA_GRACE_MASK)
8111 #define LQUOTA_FLAG(t)          (t >> LQUOTA_GRACE_BITS)
8112 #define LQUOTA_GRACE_FLAG(t, f) ((__u64)t | (__u64)f << LQUOTA_GRACE_BITS)
8113 #endif
8114
8115 #define STRBUF_LEN      24
8116 static void print_quota(char *mnt, struct if_quotactl *qctl, int type,
8117                         int rc, bool h, bool show_default)
8118 {
8119         time_t now;
8120
8121         time(&now);
8122
8123         if (qctl->qc_cmd == LUSTRE_Q_GETQUOTA || qctl->qc_cmd == Q_GETOQUOTA ||
8124             qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL ||
8125             qctl->qc_cmd == LUSTRE_Q_GETDEFAULT ||
8126             qctl->qc_cmd == LUSTRE_Q_GETDEFAULT_POOL) {
8127                 int bover = 0, iover = 0;
8128                 struct obd_dqblk *dqb = &qctl->qc_dqblk;
8129                 char numbuf[3][STRBUF_LEN + 2]; /* 2 for brackets or wildcard */
8130                 char timebuf[40];
8131                 char strbuf[STRBUF_LEN];
8132
8133                 dqb->dqb_btime &= LQUOTA_GRACE_MASK;
8134                 dqb->dqb_itime &= LQUOTA_GRACE_MASK;
8135
8136                 if (dqb->dqb_bhardlimit &&
8137                     lustre_stoqb(dqb->dqb_curspace) >= dqb->dqb_bhardlimit) {
8138                         bover = 1;
8139                 } else if (dqb->dqb_bsoftlimit && dqb->dqb_btime) {
8140                         if (dqb->dqb_btime > now)
8141                                 bover = 2;
8142                         else
8143                                 bover = 3;
8144                 }
8145
8146                 if (dqb->dqb_ihardlimit &&
8147                     dqb->dqb_curinodes >= dqb->dqb_ihardlimit) {
8148                         iover = 1;
8149                 } else if (dqb->dqb_isoftlimit && dqb->dqb_itime) {
8150                         if (dqb->dqb_itime > now)
8151                                 iover = 2;
8152                         else
8153                                 iover = 3;
8154                 }
8155
8156                 if (strlen(mnt) > 15)
8157                         printf("%s\n%15s", mnt, "");
8158                 else
8159                         printf("%15s", mnt);
8160
8161                 if (show_default)
8162                         snprintf(timebuf, sizeof(timebuf), "%llu",
8163                                  (unsigned long long)dqb->dqb_btime);
8164                 else if (bover)
8165                         diff2str(dqb->dqb_btime, timebuf, now);
8166
8167                 kbytes2str(lustre_stoqb(dqb->dqb_curspace),
8168                            strbuf, sizeof(strbuf), h);
8169                 if (rc == -EREMOTEIO)
8170                         sprintf(numbuf[0], "%s*", strbuf);
8171                 else
8172                         sprintf(numbuf[0], (dqb->dqb_valid & QIF_SPACE) ?
8173                                 "%s" : "[%s]", strbuf);
8174
8175                 kbytes2str(dqb->dqb_bsoftlimit, strbuf, sizeof(strbuf), h);
8176                 if (type == QC_GENERAL)
8177                         sprintf(numbuf[1], (dqb->dqb_valid & QIF_BLIMITS) ?
8178                                 "%s" : "[%s]", strbuf);
8179                 else
8180                         sprintf(numbuf[1], "%s", "-");
8181
8182                 kbytes2str(dqb->dqb_bhardlimit, strbuf, sizeof(strbuf), h);
8183                 sprintf(numbuf[2], (dqb->dqb_valid & QIF_BLIMITS) ?
8184                         "%s" : "[%s]", strbuf);
8185
8186                 if (show_default)
8187                         printf(" %6s %7s %7s", numbuf[1], numbuf[2], timebuf);
8188                 else
8189                         printf(" %7s%c %6s %7s %7s",
8190                                numbuf[0], bover ? '*' : ' ', numbuf[1],
8191                                numbuf[2], bover > 1 ? timebuf : "-");
8192
8193                 if (show_default)
8194                         snprintf(timebuf, sizeof(timebuf), "%llu",
8195                                  (unsigned long long)dqb->dqb_itime);
8196                 else if (iover)
8197                         diff2str(dqb->dqb_itime, timebuf, now);
8198
8199                 snprintf(numbuf[0], sizeof(numbuf),
8200                          (dqb->dqb_valid & QIF_INODES) ? "%ju" : "[%ju]",
8201                          (uintmax_t)dqb->dqb_curinodes);
8202
8203                 if (type == QC_GENERAL)
8204                         sprintf(numbuf[1], (dqb->dqb_valid & QIF_ILIMITS) ?
8205                                 "%ju" : "[%ju]",
8206                                 (uintmax_t)dqb->dqb_isoftlimit);
8207                 else
8208                         sprintf(numbuf[1], "%s", "-");
8209
8210                 sprintf(numbuf[2], (dqb->dqb_valid & QIF_ILIMITS) ?
8211                         "%ju" : "[%ju]", (uintmax_t)dqb->dqb_ihardlimit);
8212
8213                 if (show_default)
8214                         printf(" %6s %7s %7s", numbuf[1], numbuf[2], timebuf);
8215                 else if (type != QC_OSTIDX)
8216                         printf(" %7s%c %6s %7s %7s",
8217                                numbuf[0], iover ? '*' : ' ', numbuf[1],
8218                                numbuf[2], iover > 1 ? timebuf : "-");
8219                 else
8220                         printf(" %7s %7s %7s %7s", "-", "-", "-", "-");
8221                 printf("\n");
8222         } else if (qctl->qc_cmd == LUSTRE_Q_GETINFO || LUSTRE_Q_GETINFOPOOL ||
8223                    qctl->qc_cmd == Q_GETOINFO) {
8224                 char bgtimebuf[40];
8225                 char igtimebuf[40];
8226
8227                 if (qctl->qc_dqinfo.dqi_bgrace == NOTIFY_GRACE_TIME)
8228                         strncpy(bgtimebuf, NOTIFY_GRACE, 40);
8229                 else
8230                         sec2str(qctl->qc_dqinfo.dqi_bgrace, bgtimebuf, rc);
8231                 if (qctl->qc_dqinfo.dqi_igrace == NOTIFY_GRACE_TIME)
8232                         strncpy(igtimebuf, NOTIFY_GRACE, 40);
8233                 else
8234                         sec2str(qctl->qc_dqinfo.dqi_igrace, igtimebuf, rc);
8235
8236                 printf("Block grace time: %s; Inode grace time: %s\n",
8237                        bgtimebuf, igtimebuf);
8238         }
8239 }
8240
8241 static int tgt_name2index(const char *tgtname, unsigned int *idx)
8242 {
8243         char *dash, *endp;
8244
8245         /* format is "lustre-OST0001" */
8246         dash = memchr(tgtname, '-', LUSTRE_MAXFSNAME + 1);
8247         if (!dash) {
8248                 fprintf(stderr, "wrong tgtname format '%s'\n", tgtname);
8249                 return -EINVAL;
8250         }
8251         dash += 4;
8252
8253         *idx = strtoul(dash, &endp, 16);
8254         if (*idx > 0xffff) {
8255                 fprintf(stderr, "wrong index %s\n", tgtname);
8256                 return -ERANGE;
8257         }
8258
8259         return 0;
8260 }
8261
8262 static int print_obd_quota(char *mnt, struct if_quotactl *qctl, int is_mdt,
8263                            bool h, __u64 *total)
8264 {
8265         int rc = 0, rc1 = 0, count = 0, i = 0;
8266         char **list = NULL, *buffer = NULL;
8267         __u32 valid = qctl->qc_valid;
8268
8269         if (qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL && is_mdt)
8270                 return 0;
8271
8272         /* Is it correct for the case OST0000, OST0002, OST0003 -
8273          * we will ask OST0001 that is absent and won't ask OST0003? */
8274         rc = llapi_get_obd_count(mnt, &count, is_mdt);
8275         if (rc) {
8276                 fprintf(stderr, "can not get %s count: %s\n",
8277                         is_mdt ? "mdt" : "ost", strerror(-rc));
8278                 return rc;
8279         }
8280
8281         if (qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL) {
8282                 char fname[PATH_MAX];
8283                 char fsname[LUSTRE_MAXFSNAME + 1];
8284                 int bufsize = sizeof(struct obd_uuid) * count;
8285
8286                 rc = llapi_search_fsname(mnt, fsname);
8287                 if (rc) {
8288                         fprintf(stderr, "cannot get fsname for mountpoint %s\n",
8289                                 mnt);
8290                         goto out;
8291                 }
8292                 buffer = malloc(bufsize + sizeof(*list) * count);
8293                 if (!buffer)
8294                         return -ENOMEM;
8295                 list = (char **)(buffer + bufsize);
8296                 snprintf(fname, PATH_MAX, "%s.%s", fsname, qctl->qc_poolname);
8297                 count = llapi_get_poolmembers(fname, list, count,
8298                                               buffer, bufsize);
8299                 if (count <= 0)
8300                         goto out;
8301         }
8302
8303         for (i = 0; i < count; i++) {
8304                 if (qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL) {
8305                         unsigned int index;
8306
8307                         if (tgt_name2index(list[i], &index))
8308                                 continue;
8309                         qctl->qc_idx = index;
8310                 } else {
8311                         qctl->qc_idx = i;
8312                 }
8313
8314                 qctl->qc_valid = is_mdt ? QC_MDTIDX : QC_OSTIDX;
8315                 rc = llapi_quotactl(mnt, qctl);
8316                 if (rc) {
8317                         /* It is remote client case. */
8318                         if (rc == -EOPNOTSUPP) {
8319                                 rc = 0;
8320                                 goto out;
8321                         }
8322
8323                         /* no target for this index yet */
8324                         if (rc == -ENODEV) {
8325                                 rc = 0;
8326                                 continue;
8327                         }
8328
8329                         /* inactive target */
8330                         if (rc == -ENODATA) {
8331                                 char name[UUID_MAX+8];
8332
8333                                 snprintf(name, sizeof(name), "%s[inact]",
8334                                         obd_uuid2str(&qctl->obd_uuid));
8335                                 memset(&qctl->qc_dqinfo, 0,
8336                                        sizeof(qctl->qc_dqinfo));
8337                                 memset(&qctl->qc_dqblk, 0,
8338                                        sizeof(qctl->qc_dqblk));
8339                                 print_quota(name, qctl, qctl->qc_valid, 0, h,
8340                                             false);
8341                                 rc = 0;
8342                                 continue;
8343                         }
8344
8345                         if (!rc1)
8346                                 rc1 = rc;
8347                         fprintf(stderr, "quotactl %s%d failed.\n",
8348                                 is_mdt ? "mdt" : "ost", qctl->qc_idx);
8349                         continue;
8350                 }
8351
8352                 print_quota(obd_uuid2str(&qctl->obd_uuid), qctl,
8353                             qctl->qc_valid, 0, h, false);
8354                 *total += is_mdt ? qctl->qc_dqblk.dqb_ihardlimit :
8355                                    qctl->qc_dqblk.dqb_bhardlimit;
8356         }
8357 out:
8358         if (buffer)
8359                 free(buffer);
8360         qctl->qc_valid = valid;
8361         return rc ? : rc1;
8362 }
8363
8364 static int get_print_quota(char *mnt, char *name, struct if_quotactl *qctl,
8365                            int verbose, int quiet, bool human_readable,
8366                            bool show_default)
8367 {
8368         int rc1 = 0, rc2 = 0, rc3 = 0;
8369         char *obd_type = (char *)qctl->obd_type;
8370         char *obd_uuid = (char *)qctl->obd_uuid.uuid;
8371         __u64 total_ialloc = 0, total_balloc = 0;
8372         bool use_default_for_blk = false;
8373         bool use_default_for_file = false;
8374         int inacc;
8375
8376         rc1 = llapi_quotactl(mnt, qctl);
8377         if (rc1 < 0) {
8378                 switch (rc1) {
8379                 case -ESRCH:
8380                         fprintf(stderr, "%s quotas are not enabled.\n",
8381                                 qtype_name(qctl->qc_type));
8382                         goto out;
8383                 case -EPERM:
8384                         fprintf(stderr, "Permission denied.\n");
8385                 case -ENODEV:
8386                 case -ENOENT:
8387                         /* We already got error message. */
8388                         goto out;
8389                 default:
8390                         fprintf(stderr, "Unexpected quotactl error: %s\n",
8391                                 strerror(-rc1));
8392                 }
8393         }
8394
8395         if (!show_default && qctl->qc_id == 0) {
8396                 qctl->qc_dqblk.dqb_bhardlimit = 0;
8397                 qctl->qc_dqblk.dqb_bsoftlimit = 0;
8398                 qctl->qc_dqblk.dqb_ihardlimit = 0;
8399                 qctl->qc_dqblk.dqb_isoftlimit = 0;
8400                 qctl->qc_dqblk.dqb_btime = 0;
8401                 qctl->qc_dqblk.dqb_itime = 0;
8402                 qctl->qc_dqblk.dqb_valid |= QIF_LIMITS | QIF_TIMES;
8403         }
8404
8405         if (qctl->qc_dqblk.dqb_valid & QIF_BTIME &&
8406             LQUOTA_FLAG(qctl->qc_dqblk.dqb_btime) & LQUOTA_FLAG_DEFAULT) {
8407                 use_default_for_blk = true;
8408                 qctl->qc_dqblk.dqb_btime &= LQUOTA_GRACE_MASK;
8409         }
8410
8411         if (qctl->qc_dqblk.dqb_valid & QIF_ITIME &&
8412             LQUOTA_FLAG(qctl->qc_dqblk.dqb_itime) & LQUOTA_FLAG_DEFAULT) {
8413                 use_default_for_file = true;
8414                 qctl->qc_dqblk.dqb_itime &= LQUOTA_GRACE_MASK;
8415         }
8416
8417         if ((qctl->qc_cmd == LUSTRE_Q_GETQUOTA ||
8418              qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL ||
8419              qctl->qc_cmd == LUSTRE_Q_GETDEFAULT_POOL ||
8420              qctl->qc_cmd == LUSTRE_Q_GETDEFAULT) && !quiet)
8421                 print_quota_title(name, qctl, human_readable, show_default);
8422
8423         if (rc1 && *obd_type)
8424                 fprintf(stderr, "%s %s ", obd_type, obd_uuid);
8425
8426         if (qctl->qc_valid != QC_GENERAL)
8427                 mnt = "";
8428
8429         inacc = (qctl->qc_cmd == LUSTRE_Q_GETQUOTA ||
8430                  qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL) &&
8431                 ((qctl->qc_dqblk.dqb_valid & (QIF_LIMITS|QIF_USAGE)) !=
8432                  (QIF_LIMITS|QIF_USAGE));
8433
8434         print_quota(mnt, qctl, QC_GENERAL, rc1, human_readable, show_default);
8435
8436         if (!show_default && verbose &&
8437             qctl->qc_valid == QC_GENERAL && qctl->qc_cmd != LUSTRE_Q_GETINFO &&
8438             qctl->qc_cmd != LUSTRE_Q_GETINFOPOOL) {
8439                 char strbuf[STRBUF_LEN];
8440
8441                 rc2 = print_obd_quota(mnt, qctl, 1, human_readable,
8442                                       &total_ialloc);
8443                 rc3 = print_obd_quota(mnt, qctl, 0, human_readable,
8444                                       &total_balloc);
8445                 kbytes2str(total_balloc, strbuf, sizeof(strbuf),
8446                            human_readable);
8447                 printf("Total allocated inode limit: %ju, total allocated block limit: %s\n",
8448                        (uintmax_t)total_ialloc, strbuf);
8449         }
8450
8451         if (use_default_for_blk)
8452                 printf("%cid %u is using default block quota setting\n",
8453                        *qtype_name(qctl->qc_type), qctl->qc_id);
8454
8455         if (use_default_for_file)
8456                 printf("%cid %u is using default file quota setting\n",
8457                        *qtype_name(qctl->qc_type), qctl->qc_id);
8458
8459         if (rc1 || rc2 || rc3 || inacc)
8460                 printf("Some errors happened when getting quota info. Some devices may be not working or deactivated. The data in \"[]\" is inaccurate.\n");
8461 out:
8462         if (rc1)
8463                 return rc1;
8464         if (rc2)
8465                 return rc2;
8466         if (rc3)
8467                 return rc3;
8468         if (inacc)
8469                 return -EIO;
8470
8471         return 0;
8472 }
8473
8474 static int lfs_project(int argc, char **argv)
8475 {
8476         int ret = 0, err = 0, c, i;
8477         struct project_handle_control phc = { 0 };
8478         enum lfs_project_ops_t op;
8479
8480         phc.newline = true;
8481         phc.assign_projid = false;
8482         /* default action */
8483         op = LFS_PROJECT_LIST;
8484
8485         while ((c = getopt(argc, argv, "p:cCsdkr0")) != -1) {
8486                 switch (c) {
8487                 case 'c':
8488                         if (op != LFS_PROJECT_LIST) {
8489                                 fprintf(stderr,
8490                                         "%s: cannot specify '-c' '-C' '-s' together\n",
8491                                         progname);
8492                                 return CMD_HELP;
8493                         }
8494
8495                         op = LFS_PROJECT_CHECK;
8496                         break;
8497                 case 'C':
8498                         if (op != LFS_PROJECT_LIST) {
8499                                 fprintf(stderr,
8500                                         "%s: cannot specify '-c' '-C' '-s' together\n",
8501                                         progname);
8502                                 return CMD_HELP;
8503                         }
8504
8505                         op = LFS_PROJECT_CLEAR;
8506                         break;
8507                 case 's':
8508                         if (op != LFS_PROJECT_LIST) {
8509                                 fprintf(stderr,
8510                                         "%s: cannot specify '-c' '-C' '-s' together\n",
8511                                         progname);
8512                                 return CMD_HELP;
8513                         }
8514
8515                         phc.set_inherit = true;
8516                         op = LFS_PROJECT_SET;
8517                         break;
8518                 case 'd':
8519                         phc.dironly = true;
8520                         break;
8521                 case 'k':
8522                         phc.keep_projid = true;
8523                         break;
8524                 case 'r':
8525                         phc.recursive = true;
8526                         break;
8527                 case 'p':
8528                         if (str2quotaid(&phc.projid, optarg)) {
8529                                 fprintf(stderr,
8530                                         "Invalid project ID: %s\n",
8531                                         optarg);
8532                                 return CMD_HELP;
8533                         }
8534
8535                         phc.assign_projid = true;
8536
8537                         break;
8538                 case '0':
8539                         phc.newline = false;
8540                         break;
8541                 default:
8542                         fprintf(stderr, "%s: invalid option '%c'\n",
8543                                 progname, optopt);
8544                         return CMD_HELP;
8545                 }
8546         }
8547
8548         if (phc.assign_projid && op == LFS_PROJECT_LIST) {
8549                 op = LFS_PROJECT_SET;
8550                 phc.set_projid = true;
8551         } else if (phc.assign_projid && op == LFS_PROJECT_SET) {
8552                 phc.set_projid = true;
8553         }
8554
8555         switch (op) {
8556         case LFS_PROJECT_CHECK:
8557                 if (phc.keep_projid) {
8558                         fprintf(stderr,
8559                                 "%s: '-k' is useless together with '-c'\n",
8560                                 progname);
8561                         return CMD_HELP;
8562                 }
8563                 break;
8564         case LFS_PROJECT_CLEAR:
8565                 if (!phc.newline) {
8566                         fprintf(stderr,
8567                                 "%s: '-0' is useless together with '-C'\n",
8568                                 progname);
8569                         return CMD_HELP;
8570                 }
8571                 if (phc.assign_projid) {
8572                         fprintf(stderr,
8573                                 "%s: '-p' is useless together with '-C'\n",
8574                                 progname);
8575                         return CMD_HELP;
8576                 }
8577                 break;
8578         case LFS_PROJECT_SET:
8579                 if (!phc.newline) {
8580                         fprintf(stderr,
8581                                 "%s: '-0' is useless together with '-s'\n",
8582                                 progname);
8583                         return CMD_HELP;
8584                 }
8585                 if (phc.keep_projid) {
8586                         fprintf(stderr,
8587                                 "%s: '-k' is useless together with '-s'\n",
8588                                 progname);
8589                         return CMD_HELP;
8590                 }
8591                 break;
8592         default:
8593                 if (!phc.newline) {
8594                         fprintf(stderr,
8595                                 "%s: '-0' is useless for list operations\n",
8596                                 progname);
8597                         return CMD_HELP;
8598                 }
8599                 break;
8600         }
8601
8602         argv += optind;
8603         argc -= optind;
8604         if (argc == 0) {
8605                 fprintf(stderr, "%s: missing file or directory target(s)\n",
8606                         progname);
8607                 return CMD_HELP;
8608         }
8609
8610         for (i = 0; i < argc; i++) {
8611                 switch (op) {
8612                 case LFS_PROJECT_CHECK:
8613                         err = lfs_project_check(argv[i], &phc);
8614                         break;
8615                 case LFS_PROJECT_LIST:
8616                         err = lfs_project_list(argv[i], &phc);
8617                         break;
8618                 case LFS_PROJECT_CLEAR:
8619                         err = lfs_project_clear(argv[i], &phc);
8620                         break;
8621                 case LFS_PROJECT_SET:
8622                         err = lfs_project_set(argv[i], &phc);
8623                         break;
8624                 default:
8625                         break;
8626                 }
8627                 if (err && !ret)
8628                         ret = err;
8629         }
8630
8631         return ret;
8632 }
8633
8634 static int lfs_quota(int argc, char **argv)
8635 {
8636         int c;
8637         char *mnt, *name = NULL;
8638         struct if_quotactl *qctl;
8639         char *obd_uuid;
8640         int rc = 0, rc1 = 0, verbose = 0, quiet = 0;
8641         __u32 valid = QC_GENERAL, idx = 0;
8642         bool human_readable = false;
8643         bool show_default = false;
8644         int qtype;
8645         bool show_pools = false;
8646         struct option long_opts[] = {
8647         { .val = LFS_POOL_OPT, .name = "pool", .has_arg = optional_argument },
8648         { .name = NULL } };
8649         char **poollist = NULL;
8650         char *buf = NULL;
8651         int poolcount, i;
8652
8653         qctl = calloc(1, sizeof(*qctl) + LOV_MAXPOOLNAME + 1);
8654         if (!qctl)
8655                 return -ENOMEM;
8656
8657         qctl->qc_cmd = LUSTRE_Q_GETQUOTA;
8658         qctl->qc_type = ALLQUOTA;
8659         obd_uuid = (char *)qctl->obd_uuid.uuid;
8660
8661         while ((c = getopt_long(argc, argv, "gGi:I:o:pPqtuUvh",
8662                 long_opts, NULL)) != -1) {
8663                 switch (c) {
8664                 case 'U':
8665                         show_default = true;
8666                 case 'u':
8667                         qtype = USRQUOTA;
8668                         goto quota_type;
8669                 case 'G':
8670                         show_default = true;
8671                 case 'g':
8672                         qtype = GRPQUOTA;
8673                         goto quota_type;
8674                 case 'P':
8675                         show_default = true;
8676                 case 'p':
8677                         qtype = PRJQUOTA;
8678 quota_type:
8679                         if (qctl->qc_type != ALLQUOTA) {
8680                                 fprintf(stderr,
8681                                         "%s quota: only one of -u, -g, or -p may be specified\n",
8682                                         progname);
8683                                 rc = CMD_HELP;
8684                                 goto out;
8685                         }
8686                         qctl->qc_type = qtype;
8687                         break;
8688                 case 't':
8689                         qctl->qc_cmd = LUSTRE_Q_GETINFO;
8690                         break;
8691                 case 'o':
8692                         valid = qctl->qc_valid = QC_UUID;
8693                         snprintf(obd_uuid, sizeof(*obd_uuid), "%s", optarg);
8694                         break;
8695                 case 'i':
8696                         valid = qctl->qc_valid = QC_MDTIDX;
8697                         idx = qctl->qc_idx = atoi(optarg);
8698                         if (idx == 0 && *optarg != '0') {
8699                                 fprintf(stderr,
8700                                         "%s quota: invalid MDT index '%s'\n",
8701                                         progname, optarg);
8702                                 rc = CMD_HELP;
8703                                 goto out;
8704                         }
8705                         break;
8706                 case 'I':
8707                         valid = qctl->qc_valid = QC_OSTIDX;
8708                         idx = qctl->qc_idx = atoi(optarg);
8709                         if (idx == 0 && *optarg != '0') {
8710                                 fprintf(stderr,
8711                                         "%s quota: invalid OST index '%s'\n",
8712                                         progname, optarg);
8713                                 rc = CMD_HELP;
8714                                 goto out;
8715                         }
8716                         break;
8717                 case 'v':
8718                         verbose = 1;
8719                         break;
8720                 case 'q':
8721                         quiet = 1;
8722                         break;
8723                 case 'h':
8724                         human_readable = true;
8725                         break;
8726                 case LFS_POOL_OPT:
8727                         if ((!optarg) && (argv[optind] != NULL) &&
8728                                 (argv[optind][0] != '-') &&
8729                                 (argv[optind][0] != '/')) {
8730                                 optarg = argv[optind++];
8731                                 if (lfs_verify_poolarg(optarg)) {
8732                                         rc = -EINVAL;
8733                                         goto out;
8734                                 }
8735                                 strncpy(qctl->qc_poolname, optarg,
8736                                         LOV_MAXPOOLNAME);
8737                                 if (qctl->qc_cmd == LUSTRE_Q_GETINFO)
8738                                         qctl->qc_cmd = LUSTRE_Q_GETINFOPOOL;
8739                                 else
8740                                         qctl->qc_cmd = LUSTRE_Q_GETQUOTAPOOL;
8741                                 break;
8742                         }
8743
8744                         /* optarg is NULL */
8745                         show_pools = true;
8746                         qctl->qc_cmd = LUSTRE_Q_GETQUOTAPOOL;
8747                         break;
8748                 default:
8749                         fprintf(stderr, "%s quota: unrecognized option '%s'\n",
8750                                 progname, argv[optind - 1]);
8751                         rc = CMD_HELP;
8752                         goto out;
8753                 }
8754         }
8755
8756         /* current uid/gid info for "lfs quota /path/to/lustre/mount" */
8757         if ((qctl->qc_cmd == LUSTRE_Q_GETQUOTA ||
8758              qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL) &&
8759              qctl->qc_type == ALLQUOTA &&
8760              optind == argc - 1 && !show_default) {
8761                 qctl->qc_idx = idx;
8762
8763                 for (qtype = USRQUOTA; qtype <= GRPQUOTA; qtype++) {
8764                         qctl->qc_type = qtype;
8765                         qctl->qc_valid = valid;
8766                         if (qtype == USRQUOTA) {
8767                                 qctl->qc_id = geteuid();
8768                                 rc = uid2name(&name, qctl->qc_id);
8769                         } else {
8770                                 qctl->qc_id = getegid();
8771                                 rc = gid2name(&name, qctl->qc_id);
8772                                 memset(&qctl->qc_dqblk, 0,
8773                                        sizeof(qctl->qc_dqblk));
8774                         }
8775                         if (rc)
8776                                 name = "<unknown>";
8777                         mnt = argv[optind];
8778                         rc1 = get_print_quota(mnt, name, qctl, verbose, quiet,
8779                                               human_readable, show_default);
8780                         if (rc1 && !rc)
8781                                 rc = rc1;
8782                 }
8783                 goto out;
8784         /* lfs quota -u username /path/to/lustre/mount */
8785         } else if (qctl->qc_cmd == LUSTRE_Q_GETQUOTA ||
8786                    qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL) {
8787                 /* options should be followed by u/g-name and mntpoint */
8788                 if ((!show_default && optind + 2 != argc) ||
8789                     (show_default && optind + 1 != argc) ||
8790                     qctl->qc_type == ALLQUOTA) {
8791                         fprintf(stderr,
8792                                 "%s quota: name and mount point must be specified\n",
8793                                 progname);
8794                         rc = CMD_HELP;
8795                         goto out;
8796                 }
8797
8798                 if (!show_default) {
8799                         name = argv[optind++];
8800                         switch (qctl->qc_type) {
8801                         case USRQUOTA:
8802                                 rc = name2uid(&qctl->qc_id, name);
8803                                 break;
8804                         case GRPQUOTA:
8805                                 rc = name2gid(&qctl->qc_id, name);
8806                                 break;
8807                         case PRJQUOTA:
8808                                 rc = name2projid(&qctl->qc_id, name);
8809                                 break;
8810                         default:
8811                                 rc = -ENOTSUP;
8812                                 break;
8813                         }
8814                 } else {
8815                         qctl->qc_valid = QC_GENERAL;
8816                         qctl->qc_cmd = qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL ?
8817                                         LUSTRE_Q_GETDEFAULT_POOL :
8818                                         LUSTRE_Q_GETDEFAULT;
8819                         qctl->qc_id = 0;
8820                 }
8821
8822                 if (rc) {
8823                         if (str2quotaid(&qctl->qc_id, name)) {
8824                                 fprintf(stderr, "%s quota: invalid id '%s'\n",
8825                                         progname, name);
8826                                 rc = CMD_HELP;
8827                                 goto out;
8828                         }
8829                 }
8830         } else if (optind + 1 != argc || qctl->qc_type == ALLQUOTA) {
8831                 fprintf(stderr, "%s quota: missing quota info argument(s)\n",
8832                         progname);
8833                 rc = CMD_HELP;
8834                 goto out;
8835         }
8836
8837         mnt = argv[optind];
8838         if (show_pools) {
8839                 char *p;
8840
8841                 i = 0;
8842                 rc = llapi_get_poolbuf(mnt, &buf, &poollist, &poolcount);
8843                 if (rc)
8844                         goto out;
8845
8846                 for (i = 0; i < poolcount; i++) {
8847                         p = memchr(poollist[i], '.', MAXNAMLEN);
8848                         if (!p) {
8849                                 fprintf(stderr, "bad string format %.*s\n",
8850                                         MAXNAMLEN, poollist[i]);
8851                                 rc = -EINVAL;
8852                                 goto out;
8853                         }
8854                         p++;
8855                         printf("Quotas for pool: %s\n", p);
8856                         strncpy(qctl->qc_poolname, p, LOV_MAXPOOLNAME);
8857                         rc = get_print_quota(mnt, name, qctl, verbose, quiet,
8858                                              human_readable, show_default);
8859                         if (rc)
8860                                 break;
8861                 }
8862                 goto out;
8863         }
8864
8865         rc = get_print_quota(mnt, name, qctl, verbose, quiet,
8866                              human_readable, show_default);
8867 out:
8868         free(buf);
8869         free(qctl);
8870         return rc;
8871 }
8872 #endif /* HAVE_SYS_QUOTA_H! */
8873
8874 static int flushctx_ioctl(char *mp)
8875 {
8876         int fd, rc;
8877
8878         fd = open(mp, O_RDONLY);
8879         if (fd == -1) {
8880                 fprintf(stderr, "flushctx: error open %s: %s\n",
8881                         mp, strerror(errno));
8882                 return -1;
8883         }
8884
8885         rc = ioctl(fd, LL_IOC_FLUSHCTX);
8886         if (rc == -1)
8887                 fprintf(stderr, "flushctx: error ioctl %s: %s\n",
8888                         mp, strerror(errno));
8889
8890         close(fd);
8891         return rc;
8892 }
8893
8894 static int lfs_flushctx(int argc, char **argv)
8895 {
8896         int     kdestroy = 0, reap = 0, c;
8897         char    mntdir[PATH_MAX] = {'\0'};
8898         int     index = 0;
8899         int     rc = 0;
8900
8901         while ((c = getopt(argc, argv, "kr")) != -1) {
8902                 switch (c) {
8903                 case 'k':
8904                         kdestroy = 1;
8905                         break;
8906                 case 'r':
8907                         reap = 1;
8908                         break;
8909                 default:
8910                         fprintf(stderr,
8911                                 "error: %s: option '-%c' unrecognized\n",
8912                                 argv[0], c);
8913                         return CMD_HELP;
8914                 }
8915         }
8916
8917         if (kdestroy) {
8918                 rc = system("kdestroy > /dev/null");
8919                 if (rc) {
8920                         rc = WEXITSTATUS(rc);
8921                         fprintf(stderr,
8922                                 "error destroying tickets: %d, continuing\n",
8923                                 rc);
8924                 }
8925         }
8926
8927         if (optind >= argc) {
8928                 /* flush for all mounted lustre fs. */
8929                 while (!llapi_search_mounts(NULL, index++, mntdir, NULL)) {
8930                         /* Check if we have a mount point */
8931                         if (mntdir[0] == '\0')
8932                                 continue;
8933
8934                         if (flushctx_ioctl(mntdir))
8935                                 rc = -1;
8936
8937                         mntdir[0] = '\0'; /* avoid matching in next loop */
8938                 }
8939         } else {
8940                 /* flush fs as specified */
8941                 while (optind < argc) {
8942                         if (flushctx_ioctl(argv[optind++]))
8943                                 rc = -1;
8944                 }
8945         }
8946
8947         if (reap) {
8948                 rc = system("keyctl reap > /dev/null");
8949                 if (rc != 0) {
8950                         rc = WEXITSTATUS(rc);
8951                         fprintf(stderr, "error reaping keyring: %d\n", rc);
8952                 }
8953         }
8954
8955         return rc;
8956 }
8957
8958 static int lfs_changelog(int argc, char **argv)
8959 {
8960         void *changelog_priv;
8961         struct changelog_rec *rec;
8962         long long startrec = 0, endrec = 0;
8963         char *mdd;
8964         struct option long_opts[] = {
8965                 { .val = 'f', .name = "follow", .has_arg = no_argument },
8966                 { .name = NULL } };
8967         char short_opts[] = "f";
8968         int rc, follow = 0;
8969
8970         while ((rc = getopt_long(argc, argv, short_opts,
8971                 long_opts, NULL)) != -1) {
8972                 switch (rc) {
8973                 case 'f':
8974                         follow++;
8975                         break;
8976                 default:
8977                         fprintf(stderr,
8978                                 "%s changelog: unrecognized option '%s'\n",
8979                                 progname, argv[optind - 1]);
8980                         return CMD_HELP;
8981                 }
8982         }
8983         if (optind >= argc) {
8984                 fprintf(stderr, "%s changelog: mdtname must be specified\n",
8985                         progname);
8986                 return CMD_HELP;
8987         }
8988
8989         mdd = argv[optind++];
8990         if (argc > optind) {
8991                 errno = 0;
8992                 startrec = strtoll(argv[optind++], NULL, 10);
8993                 if (errno != 0 || startrec < 0) {
8994                         fprintf(stderr,
8995                                 "%s changelog: bad startrec\n",
8996                                 progname);
8997                         return CMD_HELP;
8998                 }
8999         }
9000
9001         if (argc > optind) {
9002                 errno = 0;
9003                 endrec = strtoll(argv[optind++], NULL, 10);
9004                 if (errno != 0 || endrec < 0) {
9005                         fprintf(stderr,
9006                                 "%s changelog: bad endrec\n",
9007                                 progname);
9008                         return CMD_HELP;
9009                 }
9010         }
9011
9012         rc = llapi_changelog_start(&changelog_priv,
9013                                    CHANGELOG_FLAG_BLOCK |
9014                                    CHANGELOG_FLAG_JOBID |
9015                                    CHANGELOG_FLAG_EXTRA_FLAGS |
9016                                    (follow ? CHANGELOG_FLAG_FOLLOW : 0),
9017                                    mdd, startrec);
9018         if (rc < 0) {
9019                 fprintf(stderr, "%s changelog: cannot start changelog: %s\n",
9020                         progname, strerror(errno = -rc));
9021                 return rc;
9022         }
9023
9024         rc = llapi_changelog_set_xflags(changelog_priv,
9025                                         CHANGELOG_EXTRA_FLAG_UIDGID |
9026                                         CHANGELOG_EXTRA_FLAG_NID |
9027                                         CHANGELOG_EXTRA_FLAG_OMODE |
9028                                         CHANGELOG_EXTRA_FLAG_XATTR);
9029         if (rc < 0) {
9030                 fprintf(stderr,
9031                         "%s changelog: cannot set xflags for changelog: %s\n",
9032                         progname, strerror(errno = -rc));
9033                 return rc;
9034         }
9035
9036         while ((rc = llapi_changelog_recv(changelog_priv, &rec)) == 0) {
9037                 time_t secs;
9038                 struct tm ts;
9039
9040                 if (endrec && rec->cr_index > endrec) {
9041                         llapi_changelog_free(&rec);
9042                         break;
9043                 }
9044                 if (rec->cr_index < startrec) {
9045                         llapi_changelog_free(&rec);
9046                         continue;
9047                 }
9048
9049                 secs = rec->cr_time >> 30;
9050                 gmtime_r(&secs, &ts);
9051                 printf("%ju %02d%-5s %02d:%02d:%02d.%09d %04d.%02d.%02d "
9052                        "0x%x t="DFID, (uintmax_t)rec->cr_index, rec->cr_type,
9053                        changelog_type2str(rec->cr_type),
9054                        ts.tm_hour, ts.tm_min, ts.tm_sec,
9055                        (int)(rec->cr_time & ((1 << 30) - 1)),
9056                        ts.tm_year + 1900, ts.tm_mon + 1, ts.tm_mday,
9057                        rec->cr_flags & CLF_FLAGMASK, PFID(&rec->cr_tfid));
9058
9059                 if (rec->cr_flags & CLF_JOBID) {
9060                         struct changelog_ext_jobid *jid =
9061                                 changelog_rec_jobid(rec);
9062
9063                         if (jid->cr_jobid[0] != '\0')
9064                                 printf(" j=%s", jid->cr_jobid);
9065                 }
9066
9067                 if (rec->cr_flags & CLF_EXTRA_FLAGS) {
9068                         struct changelog_ext_extra_flags *ef =
9069                                 changelog_rec_extra_flags(rec);
9070
9071                         printf(" ef=0x%llx",
9072                                (unsigned long long)ef->cr_extra_flags);
9073
9074                         if (ef->cr_extra_flags & CLFE_UIDGID) {
9075                                 struct changelog_ext_uidgid *uidgid =
9076                                         changelog_rec_uidgid(rec);
9077
9078                                 printf(" u=%llu:%llu",
9079                                        (unsigned long long)uidgid->cr_uid,
9080                                        (unsigned long long)uidgid->cr_gid);
9081                         }
9082                         if (ef->cr_extra_flags & CLFE_NID) {
9083                                 struct changelog_ext_nid *nid =
9084                                         changelog_rec_nid(rec);
9085
9086                                 printf(" nid=%s",
9087                                        libcfs_nid2str(nid->cr_nid));
9088                         }
9089
9090                         if (ef->cr_extra_flags & CLFE_OPEN) {
9091                                 struct changelog_ext_openmode *omd =
9092                                         changelog_rec_openmode(rec);
9093                                 char mode[] = "---";
9094
9095                                 /* exec mode must be exclusive */
9096                                 if (omd->cr_openflags & MDS_FMODE_EXEC) {
9097                                         mode[2] = 'x';
9098                                 } else {
9099                                         if (omd->cr_openflags & MDS_FMODE_READ)
9100                                                 mode[0] = 'r';
9101                                         if (omd->cr_openflags &
9102                                             (MDS_FMODE_WRITE |
9103                                              MDS_OPEN_TRUNC |
9104                                              MDS_OPEN_APPEND))
9105                                                 mode[1] = 'w';
9106                                 }
9107
9108                                 if (strcmp(mode, "---") != 0)
9109                                         printf(" m=%s", mode);
9110                         }
9111
9112                         if (ef->cr_extra_flags & CLFE_XATTR) {
9113                                 struct changelog_ext_xattr *xattr =
9114                                         changelog_rec_xattr(rec);
9115
9116                                 if (xattr->cr_xattr[0] != '\0')
9117                                         printf(" x=%s", xattr->cr_xattr);
9118                         }
9119                 }
9120
9121                 if (!fid_is_zero(&rec->cr_pfid))
9122                         printf(" p="DFID, PFID(&rec->cr_pfid));
9123                 if (rec->cr_namelen)
9124                         printf(" %.*s", rec->cr_namelen,
9125                                changelog_rec_name(rec));
9126
9127                 if (rec->cr_flags & CLF_RENAME) {
9128                         struct changelog_ext_rename *rnm =
9129                                 changelog_rec_rename(rec);
9130
9131                         if (!fid_is_zero(&rnm->cr_sfid))
9132                                 printf(" s="DFID" sp="DFID" %.*s",
9133                                        PFID(&rnm->cr_sfid),
9134                                        PFID(&rnm->cr_spfid),
9135                                        (int)changelog_rec_snamelen(rec),
9136                                        changelog_rec_sname(rec));
9137                 }
9138                 printf("\n");
9139
9140                 llapi_changelog_free(&rec);
9141         }
9142
9143         llapi_changelog_fini(&changelog_priv);
9144
9145         if (rc < 0)
9146                 fprintf(stderr, "%s changelog: cannot access changelog: %s\n",
9147                         progname, strerror(errno = -rc));
9148
9149         return (rc == 1 ? 0 : rc);
9150 }
9151
9152 static int lfs_changelog_clear(int argc, char **argv)
9153 {
9154         long long endrec;
9155         int rc;
9156
9157         if (argc != 4)
9158                 return CMD_HELP;
9159
9160         errno = 0;
9161         endrec = strtoll(argv[3], NULL, 10);
9162         if (errno != 0 || endrec < 0) {
9163                 fprintf(stderr,
9164                         "%s: bad endrec '%s'\n",
9165                         argv[0], argv[3]);
9166                 return CMD_HELP;
9167         }
9168
9169         rc = llapi_changelog_clear(argv[1], argv[2], endrec);
9170
9171         if (rc == -EINVAL)
9172                 fprintf(stderr, "%s: record out of range: %llu\n",
9173                         argv[0], endrec);
9174         else if (rc == -ENOENT)
9175                 fprintf(stderr, "%s: no changelog user: %s\n",
9176                         argv[0], argv[2]);
9177         else if (rc)
9178                 fprintf(stderr, "%s error: %s\n", argv[0],
9179                         strerror(-rc));
9180
9181         if (rc)
9182                 errno = -rc;
9183
9184         return rc;
9185 }
9186
9187 static void rstripc(char *str, int c)
9188 {
9189         char *end = str + strlen(str);
9190
9191         for (; str < end && end[-1] == c; --end)
9192                 end[-1] = '\0';
9193 }
9194
9195 static int lfs_fid2path(int argc, char **argv)
9196 {
9197         struct option long_opts[] = {
9198                 { .val = 'c',   .name = "cur",  .has_arg = no_argument },
9199                 { .val = 'c',   .name = "current",      .has_arg = no_argument },
9200                 { .val = 'c',   .name = "print-link",   .has_arg = no_argument },
9201                 { .val = 'f',   .name = "print-fid",    .has_arg = no_argument },
9202                 { .val = 'l',   .name = "link", .has_arg = required_argument },
9203                 { .name = NULL } };
9204         char short_opts[] = "cfl:pr:";
9205         bool print_link = false;
9206         bool print_fid = false;
9207         bool print_mnt_dir;
9208         char mnt_dir[PATH_MAX] = "";
9209         int mnt_fd = -1;
9210         char *path_or_fsname;
9211         long long recno = -1;
9212         int linkno = -1;
9213         char *endptr = NULL;
9214         int rc = 0;
9215         int c;
9216         int i;
9217
9218         while ((c = getopt_long(argc, argv, short_opts, long_opts, NULL)) != -1) {
9219                 switch (c) {
9220                 case 'c':
9221                         print_link = true;
9222                         break;
9223                 case 'f':
9224                         print_fid = true;
9225                         break;
9226                 case 'l':
9227                         errno = 0;
9228                         linkno = strtol(optarg, &endptr, 10);
9229                         if (errno != 0 || *endptr != '\0' || linkno < 0) {
9230                                 fprintf(stderr,
9231                                         "%s fid2path: invalid linkno '%s'\n",
9232                                         progname, optarg);
9233                                 return CMD_HELP;
9234                         }
9235                         break;
9236                 case 'r':
9237                         /* recno is something to do with changelogs
9238                          * that was never implemented. We just pass it
9239                          * through for the MDT to ignore.
9240                          */
9241                         errno = 0;
9242                         recno = strtoll(optarg, &endptr, 10);
9243                         if (errno != 0 || *endptr != '\0' || recno < 0) {
9244                                 fprintf(stderr,
9245                                         "%s fid2path: invalid recno '%s'\n",
9246                                         progname, optarg);
9247                                 return CMD_HELP;
9248                         }
9249                         break;
9250                 default:
9251                         fprintf(stderr,
9252                                 "%s fid2path: unrecognized option '%s'\n",
9253                                 progname, argv[optind - 1]);
9254                         return CMD_HELP;
9255                 }
9256         }
9257
9258         if (argc - optind < 2) {
9259                 fprintf(stderr,
9260                         "Usage: %s fid2path FSNAME|ROOT FID...\n",
9261                         progname);
9262                 return CMD_HELP;
9263         }
9264
9265         path_or_fsname = argv[optind];
9266
9267         if (*path_or_fsname == '/') {
9268                 print_mnt_dir = true;
9269                 rc = llapi_search_mounts(path_or_fsname, 0, mnt_dir, NULL);
9270         } else {
9271                 print_mnt_dir = false;
9272                 rc = llapi_search_rootpath(mnt_dir, path_or_fsname);
9273         }
9274
9275         if (rc < 0) {
9276                 fprintf(stderr,
9277                         "%s fid2path: cannot resolve mount point for '%s': %s\n",
9278                         progname, path_or_fsname, strerror(-rc));
9279                 goto out;
9280         }
9281
9282         mnt_fd = open(mnt_dir, O_RDONLY | O_DIRECTORY);
9283         if (mnt_fd < 0) {
9284                 fprintf(stderr,
9285                         "%s fid2path: cannot open mount point for '%s': %s\n",
9286                         progname, path_or_fsname, strerror(-rc));
9287                 goto out;
9288         }
9289
9290         /* Strip trailing slashes from mnt_dir. */
9291         rstripc(mnt_dir + 1, '/');
9292
9293         for (i = optind + 1; i < argc; i++) {
9294                 const char *fid_str = argv[i];
9295                 struct lu_fid fid;
9296                 int rc2;
9297
9298                 rc2 = llapi_fid_parse(fid_str, &fid, NULL);
9299                 if (rc2 < 0) {
9300                         fprintf(stderr,
9301                                 "%s fid2path: invalid FID '%s'\n",
9302                                 progname, fid_str);
9303                         if (rc == 0)
9304                                 rc = rc2;
9305
9306                         continue;
9307                 }
9308
9309                 int linktmp = (linkno >= 0) ? linkno : 0;
9310                 while (1) {
9311                         int oldtmp = linktmp;
9312                         long long rectmp = recno;
9313                         char path_buf[PATH_MAX];
9314
9315                         rc2 = llapi_fid2path_at(mnt_fd, &fid,
9316                                 path_buf, sizeof(path_buf), &rectmp, &linktmp);
9317                         if (rc2 < 0) {
9318                                 fprintf(stderr,
9319                                         "%s fid2path: cannot find %s %s: %s\n",
9320                                         progname, path_or_fsname, fid_str,
9321                                         strerror(-rc2));
9322                                 if (rc == 0)
9323                                         rc = rc2;
9324                                 break;
9325                         }
9326
9327                         if (print_fid)
9328                                 printf("%s ", fid_str);
9329
9330                         if (print_link)
9331                                 printf("%d ", linktmp);
9332
9333                         /* You may think this looks wrong or weird (and it is!)
9334                          * but we are actually trying to preserve the old quirky
9335                          * behaviors (enforced by our old quirky tests!) that
9336                          * make lfs so much fun to work on:
9337                          *
9338                          *   lustre 0x200000007:0x1:0x0 => "/"
9339                          *   /mnt/lustre 0x200000007:0x1:0x0 => "/mnt/lustre//"
9340                          *
9341                          * Note that llapi_fid2path() returns "" for the root
9342                          * FID. */
9343
9344                         printf("%s%s%s\n",
9345                                print_mnt_dir ? mnt_dir : "",
9346                                (print_mnt_dir || *path_buf == '\0') ? "/" : "",
9347                                path_buf);
9348
9349                         if (linkno >= 0)
9350                                 /* specified linkno */
9351                                 break;
9352
9353                         if (oldtmp == linktmp)
9354                                 /* no more links */
9355                                 break;
9356                 }
9357         }
9358 out:
9359         if (!(mnt_fd < 0))
9360                 close(mnt_fd);
9361
9362         return rc;
9363 }
9364
9365 static int lfs_path2fid(int argc, char **argv)
9366 {
9367         struct option long_opts[] = {
9368                 { .val = 'p', .name = "parents", .has_arg = no_argument },
9369                 { .name = NULL } };
9370         char            **path;
9371         const char        short_opts[] = "p";
9372         const char       *sep = "";
9373         struct lu_fid     fid;
9374         int               rc = 0;
9375         bool              show_parents = false;
9376
9377         while ((rc = getopt_long(argc, argv, short_opts,
9378                                  long_opts, NULL)) != -1) {
9379                 switch (rc) {
9380                 case 'p':
9381                         show_parents = true;
9382                         break;
9383                 default:
9384                         fprintf(stderr,
9385                                 "%s path2fid: unrecognized option '%s'\n",
9386                                 progname, argv[optind - 1]);
9387                         return CMD_HELP;
9388                 }
9389         }
9390
9391         if (optind > argc - 1) {
9392                 fprintf(stderr, "%s path2fid: FILE... must be specified\n",
9393                         progname);
9394                 return CMD_HELP;
9395         } else if (optind < argc - 1) {
9396                 sep = ": ";
9397         }
9398
9399         rc = 0;
9400         for (path = argv + optind; *path != NULL; path++) {
9401                 int err = 0;
9402
9403                 if (!show_parents) {
9404                         err = llapi_path2fid(*path, &fid);
9405                         if (!err)
9406                                 printf("%s%s"DFID"\n",
9407                                        *sep != '\0' ? *path : "", sep,
9408                                        PFID(&fid));
9409                 } else {
9410                         char            name[NAME_MAX + 1];
9411                         unsigned int    linkno = 0;
9412
9413                         while ((err = llapi_path2parent(*path, linkno, &fid,
9414                                                 name, sizeof(name))) == 0) {
9415                                 if (*sep != '\0' && linkno == 0)
9416                                         printf("%s%s", *path, sep);
9417
9418                                 printf("%s"DFID"/%s", linkno != 0 ? "\t" : "",
9419                                        PFID(&fid), name);
9420                                 linkno++;
9421                         }
9422
9423                         /* err == -ENODATA is end-of-loop */
9424                         if (linkno > 0 && err == -ENODATA) {
9425                                 printf("\n");
9426                                 err = 0;
9427                         }
9428                 }
9429
9430                 if (err) {
9431                         fprintf(stderr,
9432                                 "%s path2fid: cannot get %sfid for '%s': %s\n",
9433                                 progname, show_parents ? "parent " : "", *path,
9434                                 strerror(-err));
9435                         if (rc == 0) {
9436                                 rc = err;
9437                                 errno = -err;
9438                         }
9439                 }
9440         }
9441
9442         return rc;
9443 }
9444
9445 #define MAX_ERRNO       4095
9446 #define IS_ERR_VALUE(x) ((unsigned long)(x) >= (unsigned long)-MAX_ERRNO)
9447
9448 static int lfs_rmfid_and_show_errors(const char *device, struct fid_array *fa)
9449 {
9450         int rc, rc2, k;
9451
9452         rc = llapi_rmfid(device, fa);
9453         if (rc < 0) {
9454                 fprintf(stderr, "%s rmfid: cannot remove FIDs: %s\n",
9455                         progname, strerror(-rc));
9456                 return rc;
9457         }
9458
9459         for (k = 0; k < fa->fa_nr; k++) {
9460                 rc2 = (__s32)fa->fa_fids[k].f_ver;
9461                 if (!IS_ERR_VALUE(rc2))
9462                         continue;
9463
9464                 if (rc == 0)
9465                         rc = rc2;
9466
9467                 fa->fa_fids[k].f_ver = 0;
9468                 fprintf(stderr, "%s rmfid: cannot remove "DFID": %s\n",
9469                         progname, PFID(&fa->fa_fids[k]), strerror(-rc2));
9470         }
9471
9472         return rc;
9473 }
9474
9475 static int lfs_rmfid(int argc, char **argv)
9476 {
9477         char *fidstr, *device;
9478         int rc = 0, rc2, nr;
9479         struct fid_array *fa;
9480
9481         if (optind > argc - 1) {
9482                 fprintf(stderr, "%s rmfid: missing dirname\n", progname);
9483                 return CMD_HELP;
9484         }
9485
9486         device = argv[optind++];
9487
9488         nr = argc - optind;
9489         fa = malloc(offsetof(struct fid_array, fa_fids[nr + 1]));
9490         if (!fa)
9491                 return -ENOMEM;
9492
9493         fa->fa_nr = 0;
9494         rc = 0;
9495         while (optind < argc) {
9496                 int found;
9497
9498                 fidstr = argv[optind++];
9499                 while (*fidstr == '[')
9500                         fidstr++;
9501                 found = sscanf(fidstr, SFID, RFID(&fa->fa_fids[fa->fa_nr]));
9502                 if (found != 3) {
9503                         fprintf(stderr, "unrecognized FID: %s\n",
9504                                 argv[optind - 1]);
9505                         exit(1);
9506                 }
9507                 fa->fa_nr++;
9508                 if (fa->fa_nr == OBD_MAX_FIDS_IN_ARRAY) {
9509                         /* start another batch */
9510                         rc2 = lfs_rmfid_and_show_errors(device, fa);
9511                         if (rc2 && !rc)
9512                                 rc = rc2;
9513                         fa->fa_nr = 0;
9514                 }
9515         }
9516         if (fa->fa_nr) {
9517                 rc2 = lfs_rmfid_and_show_errors(device, fa);
9518                 if (rc2 && !rc)
9519                         rc = rc2;
9520         }
9521
9522         return rc;
9523 }
9524
9525 static int lfs_data_version(int argc, char **argv)
9526 {
9527         int data_version_flags = LL_DV_RD_FLUSH; /* Read by default */
9528         __u64 data_version;
9529         char *path;
9530         int fd;
9531         int rc;
9532         int c;
9533
9534         if (argc < 2) {
9535                 fprintf(stderr, "%s: FILE must be specified\n",
9536                         progname);
9537                 return CMD_HELP;
9538         }
9539
9540         while ((c = getopt(argc, argv, "hnrw")) != -1) {
9541                 switch (c) {
9542                 case 'n':
9543                         data_version_flags = 0;
9544                         break;
9545                 case 'r':
9546                         data_version_flags |= LL_DV_RD_FLUSH;
9547                         break;
9548                 case 'w':
9549                         data_version_flags |= LL_DV_WR_FLUSH;
9550                         break;
9551                 default:
9552                         fprintf(stderr,
9553                                 "%s data_version: unrecognized option '%s'\n",
9554                                 progname, argv[optind - 1]);
9555                         fallthrough;
9556                 case 'h':
9557                         return CMD_HELP;
9558                 }
9559         }
9560         if (optind == argc) {
9561                 fprintf(stderr, "%s data_version: FILE must be specified\n",
9562                         progname);
9563                 return CMD_HELP;
9564         }
9565
9566         path = argv[optind];
9567         fd = open(path, O_RDONLY);
9568         if (fd < 0) {
9569                 rc = -errno;
9570                 fprintf(stderr, "%s data_version: cannot open file '%s': %s\n",
9571                         progname, path, strerror(-rc));
9572                 return rc;
9573         }
9574
9575         rc = llapi_get_data_version(fd, &data_version, data_version_flags);
9576         if (rc < 0)
9577                 fprintf(stderr,
9578                         "%s data_version: cannot get version for '%s': %s\n",
9579                         progname, path, strerror(-rc));
9580         else
9581                 printf("%ju" "\n", (uintmax_t)data_version);
9582
9583         close(fd);
9584         return rc;
9585 }
9586
9587 static int lfs_hsm_state(int argc, char **argv)
9588 {
9589         int rc;
9590         int i = 1;
9591         char *path;
9592         struct hsm_user_state hus;
9593
9594         if (argc < 2)
9595                 return CMD_HELP;
9596
9597         do {
9598                 path = argv[i];
9599
9600                 rc = llapi_hsm_state_get(path, &hus);
9601                 if (rc) {
9602                         fprintf(stderr, "can't get hsm state for %s: %s\n",
9603                                 path, strerror(errno = -rc));
9604                         return rc;
9605                 }
9606
9607                 /* Display path name and status flags */
9608                 printf("%s: (0x%08x)", path, hus.hus_states);
9609
9610                 if (hus.hus_states & HS_RELEASED)
9611                         printf(" released");
9612                 if (hus.hus_states & HS_EXISTS)
9613                         printf(" exists");
9614                 if (hus.hus_states & HS_DIRTY)
9615                         printf(" dirty");
9616                 if (hus.hus_states & HS_ARCHIVED)
9617                         printf(" archived");
9618                 /* Display user-settable flags */
9619                 if (hus.hus_states & HS_NORELEASE)
9620                         printf(" never_release");
9621                 if (hus.hus_states & HS_NOARCHIVE)
9622                         printf(" never_archive");
9623                 if (hus.hus_states & HS_LOST)
9624                         printf(" lost_from_hsm");
9625
9626                 if (hus.hus_archive_id != 0)
9627                         printf(", archive_id:%d", hus.hus_archive_id);
9628                 printf("\n");
9629
9630         } while (++i < argc);
9631
9632         return 0;
9633 }
9634
9635 #define LFS_HSM_SET   0
9636 #define LFS_HSM_CLEAR 1
9637
9638 /**
9639  * Generic function to set or clear HSM flags.
9640  * Used by hsm_set and hsm_clear.
9641  *
9642  * @mode  if LFS_HSM_SET, set the flags, if LFS_HSM_CLEAR, clear the flags.
9643  */
9644 static int lfs_hsm_change_flags(int argc, char **argv, int mode)
9645 {
9646         struct option long_opts[] = {
9647         { .val = 'A',   .name = "archived",     .has_arg = no_argument },
9648         { .val = 'a',   .name = "noarchive",    .has_arg = no_argument },
9649         { .val = 'd',   .name = "dirty",        .has_arg = no_argument },
9650         { .val = 'e',   .name = "exists",       .has_arg = no_argument },
9651         { .val = 'h',   .name = "help",         .has_arg = no_argument },
9652         { .val = 'i',   .name = "archive-id",   .has_arg = required_argument },
9653         { .val = 'l',   .name = "lost",         .has_arg = no_argument },
9654         { .val = 'r',   .name = "norelease",    .has_arg = no_argument },
9655         { .name = NULL } };
9656         __u64 mask = 0;
9657         int c, rc;
9658         char *path;
9659         __u32 archive_id = 0;
9660         char *end = NULL;
9661
9662         if (argc < 3)
9663                 return CMD_HELP;
9664
9665         while ((c = getopt_long(argc, argv, "aAdehi:lr",
9666                                 long_opts, NULL)) != -1) {
9667                 switch (c) {
9668                 case 'l':
9669                         mask |= HS_LOST;
9670                         break;
9671                 case 'a':
9672                         mask |= HS_NOARCHIVE;
9673                         break;
9674                 case 'A':
9675                         mask |= HS_ARCHIVED;
9676                         break;
9677                 case 'r':
9678                         mask |= HS_NORELEASE;
9679                         break;
9680                 case 'd':
9681                         mask |= HS_DIRTY;
9682                         break;
9683                 case 'e':
9684                         mask |= HS_EXISTS;
9685                         break;
9686                 case 'i':
9687                         errno = 0;
9688                         archive_id = strtol(optarg, &end, 10);
9689                         if (errno != 0 || *end != '\0' || archive_id < 0) {
9690                                 fprintf(stderr,
9691                                         "%s: invalid archive_id: '%s'\n",
9692                                         progname, end);
9693                                 return CMD_HELP;
9694                         }
9695                         break;
9696                 default:
9697                         fprintf(stderr, "%s: unrecognized option '%s'\n",
9698                                 progname, argv[optind - 1]);
9699                         fallthrough;
9700                 case 'h':
9701                         return CMD_HELP;
9702                 }
9703         }
9704
9705         /* User should have specified a flag */
9706         if (mask == 0)
9707                 return CMD_HELP;
9708
9709         while (optind < argc) {
9710                 path = argv[optind];
9711
9712                 /* If mode == 0, this means we apply the mask. */
9713                 if (mode == LFS_HSM_SET)
9714                         rc = llapi_hsm_state_set(path, mask, 0, archive_id);
9715                 else
9716                         rc = llapi_hsm_state_set(path, 0, mask, 0);
9717
9718                 if (rc != 0) {
9719                         fprintf(stderr, "Can't change hsm flags for %s: %s\n",
9720                                 path, strerror(errno = -rc));
9721                         return rc;
9722                 }
9723                 optind++;
9724         }
9725
9726         return 0;
9727 }
9728
9729 static int lfs_hsm_action(int argc, char **argv)
9730 {
9731         int                              rc;
9732         int                              i = 1;
9733         char                            *path;
9734         struct hsm_current_action        hca;
9735         struct hsm_extent                he;
9736         enum hsm_user_action             hua;
9737         enum hsm_progress_states         hps;
9738
9739         if (argc < 2)
9740                 return CMD_HELP;
9741
9742         do {
9743                 path = argv[i];
9744
9745                 rc = llapi_hsm_current_action(path, &hca);
9746                 if (rc) {
9747                         fprintf(stderr, "can't get hsm action for %s: %s\n",
9748                                 path, strerror(errno = -rc));
9749                         return rc;
9750                 }
9751                 he = hca.hca_location;
9752                 hua = hca.hca_action;
9753                 hps = hca.hca_state;
9754
9755                 printf("%s: %s", path, hsm_user_action2name(hua));
9756
9757                 /* Skip file without action */
9758                 if (hca.hca_action == HUA_NONE) {
9759                         printf("\n");
9760                         continue;
9761                 }
9762
9763                 printf(" %s ", hsm_progress_state2name(hps));
9764
9765                 if ((hps == HPS_RUNNING) &&
9766                     (hua == HUA_ARCHIVE || hua == HUA_RESTORE))
9767                         printf("(%llu bytes moved)\n",
9768                                (unsigned long long)he.length);
9769                 else if ((he.offset + he.length) == LUSTRE_EOF)
9770                         printf("(from %llu to EOF)\n",
9771                                (unsigned long long)he.offset);
9772                 else
9773                         printf("(from %llu to %llu)\n",
9774                                (unsigned long long)he.offset,
9775                                (unsigned long long)(he.offset + he.length));
9776
9777         } while (++i < argc);
9778
9779         return 0;
9780 }
9781
9782 static int lfs_hsm_set(int argc, char **argv)
9783 {
9784         return lfs_hsm_change_flags(argc, argv, LFS_HSM_SET);
9785 }
9786
9787 static int lfs_hsm_clear(int argc, char **argv)
9788 {
9789         return lfs_hsm_change_flags(argc, argv, LFS_HSM_CLEAR);
9790 }
9791
9792 /**
9793  * Check file state and return its fid, to be used by lfs_hsm_request().
9794  *
9795  * \param[in]     file      Path to file to check
9796  * \param[in,out] fid       Pointer to allocated lu_fid struct.
9797  * \param[in,out] last_dev  Pointer to last device id used.
9798  *
9799  * \return 0 on success.
9800  */
9801 static int lfs_hsm_prepare_file(const char *file, struct lu_fid *fid,
9802                                 dev_t *last_dev)
9803 {
9804         struct stat     st;
9805         int             rc;
9806
9807         rc = lstat(file, &st);
9808         if (rc) {
9809                 fprintf(stderr, "Cannot stat %s: %s\n", file, strerror(errno));
9810                 return -errno;
9811         }
9812         /*
9813          * Checking for regular file as archiving as posix copytool
9814          * rejects archiving files other than regular files
9815          */
9816         if (!S_ISREG(st.st_mode)) {
9817                 fprintf(stderr, "error: \"%s\" is not a regular file\n", file);
9818                 return CMD_HELP;
9819         }
9820         /* A request should be ... */
9821         if (*last_dev != st.st_dev && *last_dev != 0) {
9822                 fprintf(stderr,
9823                         "All files should be on the same filesystem: %s\n",
9824                         file);
9825                 return -EINVAL;
9826         }
9827         *last_dev = st.st_dev;
9828
9829         rc = llapi_path2fid(file, fid);
9830         if (rc) {
9831                 fprintf(stderr, "Cannot read FID of %s: %s\n",
9832                         file, strerror(-rc));
9833                 return rc;
9834         }
9835         return 0;
9836 }
9837
9838 /* Fill an HSM HUR item with a given file name.
9839  *
9840  * If mntpath is set, then the filename is actually a FID, and no
9841  * lookup on the filesystem will be performed.
9842  *
9843  * \param[in]  hur         the user request to fill
9844  * \param[in]  idx         index of the item inside the HUR to fill
9845  * \param[in]  mntpath     mountpoint of Lustre
9846  * \param[in]  fname       filename (if mtnpath is NULL)
9847  *                         or FID (if mntpath is set)
9848  * \param[in]  last_dev    pointer to last device id used
9849  *
9850  * \retval 0 on success
9851  * \retval CMD_HELP or a negative errno on error
9852  */
9853 static int fill_hur_item(struct hsm_user_request *hur, unsigned int idx,
9854                          const char *mntpath, const char *fname,
9855                          dev_t *last_dev)
9856 {
9857         struct hsm_user_item *hui = &hur->hur_user_item[idx];
9858         int rc;
9859
9860         hui->hui_extent.length = -1;
9861
9862         if (mntpath) {
9863                 rc = llapi_fid_parse(fname, &hui->hui_fid, NULL);
9864                 if (rc)
9865                         fprintf(stderr, "hsm: '%s' is not a valid FID\n",
9866                                 fname);
9867         } else {
9868                 rc = lfs_hsm_prepare_file(fname, &hui->hui_fid, last_dev);
9869         }
9870
9871         if (rc == 0)
9872                 hur->hur_request.hr_itemcount++;
9873
9874         return rc;
9875 }
9876
9877 static int lfs_hsm_request(int argc, char **argv, int action)
9878 {
9879         struct option long_opts[] = {
9880         { .val = 'a',   .name = "archive",      .has_arg = required_argument },
9881         { .val = 'D',   .name = "data",         .has_arg = required_argument },
9882         { .val = 'h',   .name = "help",         .has_arg = no_argument },
9883         { .val = 'l',   .name = "filelist",     .has_arg = required_argument },
9884         { .val = 'm',   .name = "mntpath",      .has_arg = required_argument },
9885         { .name = NULL } };
9886         dev_t last_dev = 0;
9887         struct hsm_user_request *hur, *oldhur;
9888         int c, i;
9889         size_t len;
9890         int nbfile;
9891         char *line = NULL;
9892         char *filelist = NULL;
9893         char fullpath[PATH_MAX];
9894         char *opaque = NULL;
9895         int opaque_len = 0;
9896         int archive_id = 0;
9897         FILE *fp;
9898         int nbfile_alloc = 0;
9899         char *some_file = NULL;
9900         char *mntpath = NULL;
9901         int rc;
9902
9903         if (argc < 2)
9904                 return CMD_HELP;
9905
9906         while ((c = getopt_long(argc, argv, "a:D:hl:m:",
9907                                 long_opts, NULL)) != -1) {
9908                 switch (c) {
9909                 case 'l':
9910                         filelist = optarg;
9911                         break;
9912                 case 'D':
9913                         opaque = optarg;
9914                         break;
9915                 case 'a':
9916                         if (action != HUA_ARCHIVE &&
9917                             action != HUA_REMOVE) {
9918                                 fprintf(stderr,
9919                                         "error: -a is supported only when archiving or removing\n");
9920                                 return CMD_HELP;
9921                         }
9922                         archive_id = atoi(optarg);
9923                         break;
9924                 case 'm':
9925                         if (!some_file) {
9926                                 mntpath = optarg;
9927                                 some_file = strdup(optarg);
9928                         }
9929                         break;
9930                 default:
9931                         fprintf(stderr, "%s: unrecognized option '%s'\n",
9932                                 progname, argv[optind - 1]);
9933                         fallthrough;
9934                 case 'h':
9935                         return CMD_HELP;
9936                 }
9937         }
9938
9939         /* All remaining args are files, so we have at least nbfile */
9940         nbfile = argc - optind;
9941
9942         if ((nbfile == 0) && (!filelist))
9943                 return CMD_HELP;
9944
9945         if (opaque)
9946                 opaque_len = strlen(opaque);
9947
9948         /*
9949          * Alloc the request structure with enough place to store all files
9950          * from command line.
9951          */
9952         hur = llapi_hsm_user_request_alloc(nbfile, opaque_len);
9953         if (!hur) {
9954                 fprintf(stderr, "Cannot create the request: %s\n",
9955                         strerror(errno));
9956                 return errno;
9957         }
9958         nbfile_alloc = nbfile;
9959
9960         hur->hur_request.hr_action = action;
9961         hur->hur_request.hr_archive_id = archive_id;
9962         hur->hur_request.hr_flags = 0;
9963
9964         /* All remaining args are files, add them */
9965         if (nbfile != 0 && some_file == NULL)
9966                 some_file = strdup(argv[optind]);
9967
9968         for (i = 0; i < nbfile; i++) {
9969                 rc = fill_hur_item(hur, i, mntpath, argv[optind + i],
9970                                    &last_dev);
9971                 if (rc)
9972                         goto out_free;
9973         }
9974
9975         /* from here stop using nb_file, use hur->hur_request.hr_itemcount */
9976
9977         /* If a filelist was specified, read the filelist from it. */
9978         if (filelist) {
9979                 fp = fopen(filelist, "r");
9980                 if (!fp) {
9981                         fprintf(stderr, "Cannot read the file list %s: %s\n",
9982                                 filelist, strerror(errno));
9983                         rc = -errno;
9984                         goto out_free;
9985                 }
9986
9987                 while ((rc = getline(&line, &len, fp)) != -1) {
9988                         /*
9989                          * If allocated buffer was too small, get something
9990                          * larger
9991                          */
9992                         if (nbfile_alloc <= hur->hur_request.hr_itemcount) {
9993                                 ssize_t size;
9994
9995                                 nbfile_alloc = nbfile_alloc * 2 + 1;
9996                                 oldhur = hur;
9997                                 hur = llapi_hsm_user_request_alloc(nbfile_alloc,
9998                                                                    opaque_len);
9999                                 if (!hur) {
10000                                         fprintf(stderr,
10001                                                 "hsm: cannot allocate the request: %s\n",
10002                                                 strerror(errno));
10003                                         hur = oldhur;
10004                                         rc = -errno;
10005                                         fclose(fp);
10006                                         goto out_free;
10007                                 }
10008                                 size = hur_len(oldhur);
10009                                 if (size < 0) {
10010                                         fprintf(stderr,
10011                                                 "hsm: cannot allocate %u files + %u bytes data\n",
10012                                                 oldhur->hur_request.hr_itemcount,
10013                                                 oldhur->hur_request.hr_data_len);
10014                                         free(hur);
10015                                         hur = oldhur;
10016                                         rc = -E2BIG;
10017                                         fclose(fp);
10018                                         goto out_free;
10019                                 }
10020                                 memcpy(hur, oldhur, size);
10021                                 free(oldhur);
10022                         }
10023
10024                         /* Chop CR */
10025                         if (line[strlen(line) - 1] == '\n')
10026                                 line[strlen(line) - 1] = '\0';
10027
10028                         rc = fill_hur_item(hur, hur->hur_request.hr_itemcount,
10029                                            mntpath, line, &last_dev);
10030                         if (rc) {
10031                                 fclose(fp);
10032                                 goto out_free;
10033                         }
10034
10035                         if (!some_file) {
10036                                 some_file = line;
10037                                 line = NULL;
10038                         }
10039                 }
10040
10041                 rc = fclose(fp);
10042                 free(line);
10043         }
10044
10045         /* If a --data was used, add it to the request */
10046         hur->hur_request.hr_data_len = opaque_len;
10047         if (opaque)
10048                 memcpy(hur_data(hur), opaque, opaque_len);
10049
10050         /* Send the HSM request */
10051         if (realpath(some_file, fullpath) == NULL) {
10052                 fprintf(stderr, "Could not find path '%s': %s\n",
10053                         some_file, strerror(errno));
10054         }
10055         rc = llapi_hsm_request(fullpath, hur);
10056         if (rc) {
10057                 fprintf(stderr, "Cannot send HSM request (use of %s): %s\n",
10058                         some_file, strerror(-rc));
10059                 goto out_free;
10060         }
10061
10062 out_free:
10063         free(some_file);
10064         free(hur);
10065         return rc;
10066 }
10067
10068 static int lfs_hsm_archive(int argc, char **argv)
10069 {
10070         return lfs_hsm_request(argc, argv, HUA_ARCHIVE);
10071 }
10072
10073 static int lfs_hsm_restore(int argc, char **argv)
10074 {
10075         return lfs_hsm_request(argc, argv, HUA_RESTORE);
10076 }
10077
10078 static int lfs_hsm_release(int argc, char **argv)
10079 {
10080         return lfs_hsm_request(argc, argv, HUA_RELEASE);
10081 }
10082
10083 static int lfs_hsm_remove(int argc, char **argv)
10084 {
10085         return lfs_hsm_request(argc, argv, HUA_REMOVE);
10086 }
10087
10088 static int lfs_hsm_cancel(int argc, char **argv)
10089 {
10090         return lfs_hsm_request(argc, argv, HUA_CANCEL);
10091 }
10092
10093 static int lfs_swap_layouts(int argc, char **argv)
10094 {
10095         if (argc != 3)
10096                 return CMD_HELP;
10097
10098         return llapi_swap_layouts(argv[1], argv[2], 0, 0,
10099                                   SWAP_LAYOUTS_KEEP_MTIME |
10100                                   SWAP_LAYOUTS_KEEP_ATIME);
10101 }
10102
10103 static const char *const ladvise_names[] = LU_LADVISE_NAMES;
10104
10105 static const char *const lock_mode_names[] = LOCK_MODE_NAMES;
10106
10107 int lfs_get_mode(const char *string)
10108 {
10109         enum lock_mode_user mode;
10110
10111         for (mode = 0; mode < ARRAY_SIZE(lock_mode_names); mode++) {
10112                 if (lock_mode_names[mode] == NULL)
10113                         continue;
10114                 if (strcasecmp(string, lock_mode_names[mode]) == 0)
10115                         return mode;
10116         }
10117
10118         return -EINVAL;
10119 }
10120
10121 static enum lu_ladvise_type lfs_get_ladvice(const char *string)
10122 {
10123         enum lu_ladvise_type advice;
10124
10125         for (advice = 0;
10126              advice < ARRAY_SIZE(ladvise_names); advice++) {
10127                 if (ladvise_names[advice] == NULL)
10128                         continue;
10129                 if (strcmp(string, ladvise_names[advice]) == 0)
10130                         return advice;
10131         }
10132
10133         return LU_LADVISE_INVALID;
10134 }
10135
10136 static int lfs_ladvise(int argc, char **argv)
10137 {
10138         struct option long_opts[] = {
10139         { .val = 'a',   .name = "advice",       .has_arg = required_argument },
10140         { .val = 'b',   .name = "background",   .has_arg = no_argument },
10141         { .val = 'e',   .name = "end",          .has_arg = required_argument },
10142         { .val = 'h',   .name = "help",         .has_arg = no_argument },
10143         { .val = 'l',   .name = "length",       .has_arg = required_argument },
10144         { .val = 'm',   .name = "mode",         .has_arg = required_argument },
10145         { .val = 's',   .name = "start",        .has_arg = required_argument },
10146         { .val = 'u',   .name = "unset",        .has_arg = no_argument },
10147         { .name = NULL } };
10148         struct llapi_lu_ladvise advice;
10149         enum lu_ladvise_type advice_type = LU_LADVISE_INVALID;
10150         unsigned long long start = 0;
10151         unsigned long long end = LUSTRE_EOF;
10152         unsigned long long length = 0;
10153         unsigned long long size_units;
10154         unsigned long long flags = 0;
10155         int c, fd, rc = 0;
10156         const char *path;
10157         int mode = 0;
10158
10159         optind = 0;
10160         while ((c = getopt_long(argc, argv, "a:be:hl:m:s:u",
10161                                 long_opts, NULL)) != -1) {
10162                 switch (c) {
10163                 case 'a':
10164                         advice_type = lfs_get_ladvice(optarg);
10165                         if (advice_type == LU_LADVISE_INVALID) {
10166                                 fprintf(stderr,
10167                                         "%s: invalid advice type '%s'\n",
10168                                         progname, optarg);
10169                                 fprintf(stderr, "Valid types:");
10170
10171                                 for (advice_type = 0;
10172                                      advice_type < ARRAY_SIZE(ladvise_names);
10173                                      advice_type++) {
10174                                         if (ladvise_names[advice_type] == NULL)
10175                                                 continue;
10176                                         fprintf(stderr, " %s",
10177                                                 ladvise_names[advice_type]);
10178                                 }
10179                                 fprintf(stderr, "\n");
10180
10181                                 return CMD_HELP;
10182                         }
10183                         break;
10184                 case 'b':
10185                         flags |= LF_ASYNC;
10186                         break;
10187                 case 'u':
10188                         flags |= LF_UNSET;
10189                         break;
10190                 case 'e':
10191                         size_units = 1;
10192                         rc = llapi_parse_size(optarg, &end,
10193                                               &size_units, 0);
10194                         if (rc) {
10195                                 fprintf(stderr, "%s: bad end offset '%s'\n",
10196                                         argv[0], optarg);
10197                                 return CMD_HELP;
10198                         }
10199                         break;
10200                 case 's':
10201                         size_units = 1;
10202                         rc = llapi_parse_size(optarg, &start,
10203                                               &size_units, 0);
10204                         if (rc) {
10205                                 fprintf(stderr,
10206                                         "%s: bad start offset '%s'\n",
10207                                         argv[0], optarg);
10208                                 return CMD_HELP;
10209                         }
10210                         break;
10211                 case 'l':
10212                         size_units = 1;
10213                         rc = llapi_parse_size(optarg, &length,
10214                                               &size_units, 0);
10215                         if (rc) {
10216                                 fprintf(stderr, "%s: bad length '%s'\n",
10217                                         argv[0], optarg);
10218                                 return CMD_HELP;
10219                         }
10220                         break;
10221                 case 'm':
10222                         mode = lfs_get_mode(optarg);
10223                         if (mode < 0) {
10224                                 fprintf(stderr,
10225                                         "%s: bad mode '%s', valid modes are READ or WRITE\n",
10226                                         argv[0], optarg);
10227                                 return CMD_HELP;
10228                         }
10229                         break;
10230                 default:
10231                         fprintf(stderr, "%s: unrecognized option '%s'\n",
10232                                 progname, argv[optind - 1]);
10233                         fallthrough;
10234                 case 'h':
10235                         return CMD_HELP;
10236                 }
10237         }
10238
10239         if (advice_type == LU_LADVISE_INVALID) {
10240                 fprintf(stderr, "%s: please give an advice type\n", argv[0]);
10241                 fprintf(stderr, "Valid types:");
10242                 for (advice_type = 0; advice_type < ARRAY_SIZE(ladvise_names);
10243                      advice_type++) {
10244                         if (ladvise_names[advice_type] == NULL)
10245                                 continue;
10246                         fprintf(stderr, " %s", ladvise_names[advice_type]);
10247                 }
10248                 fprintf(stderr, "\n");
10249                 return CMD_HELP;
10250         }
10251
10252         if (advice_type == LU_LADVISE_LOCKNOEXPAND) {
10253                 fprintf(stderr,
10254                         "%s: Lock no expand advice is a per file descriptor advice, so when called from lfs, it does nothing.\n",
10255                         argv[0]);
10256                 return CMD_HELP;
10257         }
10258
10259         if (argc <= optind) {
10260                 fprintf(stderr, "%s: please give one or more file names\n",
10261                         argv[0]);
10262                 return CMD_HELP;
10263         }
10264
10265         if (end != LUSTRE_EOF && length != 0 && end != start + length) {
10266                 fprintf(stderr, "%s: conflicting arguments of -l and -e\n",
10267                         argv[0]);
10268                 return CMD_HELP;
10269         }
10270
10271         if (end == LUSTRE_EOF && length != 0)
10272                 end = start + length;
10273
10274         if (end <= start) {
10275                 fprintf(stderr, "%s: range [%llu, %llu] is invalid\n",
10276                         argv[0], start, end);
10277                 return CMD_HELP;
10278         }
10279
10280         if (advice_type != LU_LADVISE_LOCKAHEAD && mode != 0) {
10281                 fprintf(stderr, "%s: mode is only valid with lockahead\n",
10282                         argv[0]);
10283                 return CMD_HELP;
10284         }
10285
10286         if (advice_type == LU_LADVISE_LOCKAHEAD && mode == 0) {
10287                 fprintf(stderr, "%s: mode is required with lockahead\n",
10288                         argv[0]);
10289                 return CMD_HELP;
10290         }
10291
10292         while (optind < argc) {
10293                 int rc2;
10294
10295                 path = argv[optind++];
10296
10297                 fd = open(path, O_RDONLY);
10298                 if (fd < 0) {
10299                         fprintf(stderr, "%s: cannot open file '%s': %s\n",
10300                                 argv[0], path, strerror(errno));
10301                         rc2 = -errno;
10302                         goto next;
10303                 }
10304
10305                 advice.lla_start = start;
10306                 advice.lla_end = end;
10307                 advice.lla_advice = advice_type;
10308                 advice.lla_value1 = 0;
10309                 advice.lla_value2 = 0;
10310                 advice.lla_value3 = 0;
10311                 advice.lla_value4 = 0;
10312                 if (advice_type == LU_LADVISE_LOCKAHEAD) {
10313                         advice.lla_lockahead_mode = mode;
10314                         advice.lla_peradvice_flags = flags;
10315                 }
10316
10317                 rc2 = llapi_ladvise(fd, flags, 1, &advice);
10318                 close(fd);
10319                 if (rc2 < 0) {
10320                         fprintf(stderr,
10321                                 "%s: cannot give advice '%s' to file '%s': %s\n",
10322                                 argv[0], ladvise_names[advice_type],
10323                                 path, strerror(errno));
10324
10325                         goto next;
10326                 }
10327
10328 next:
10329                 if (rc == 0 && rc2 < 0)
10330                         rc = rc2;
10331         }
10332         return rc;
10333 }
10334
10335 static const char *const heat_names[] = LU_HEAT_NAMES;
10336
10337 static int lfs_heat_get(int argc, char **argv)
10338 {
10339         struct lu_heat *heat;
10340         int rc = 0, rc2;
10341         char *path;
10342         int fd;
10343         int i;
10344
10345         if (argc <= 1)
10346                 return CMD_HELP;
10347
10348         heat = calloc(sizeof(*heat) + sizeof(__u64) * OBD_HEAT_COUNT, 1);
10349         if (!heat) {
10350                 fprintf(stderr, "%s: memory allocation failed\n", argv[0]);
10351                 return -ENOMEM;
10352         }
10353
10354         optind = 1;
10355         while (optind < argc) {
10356                 path = argv[optind++];
10357
10358                 fd = open(path, O_RDONLY);
10359                 if (fd < 0) {
10360                         fprintf(stderr, "%s: cannot open file '%s': %s\n",
10361                                 argv[0], path, strerror(errno));
10362                         rc2 = -errno;
10363                         goto next;
10364                 }
10365
10366                 heat->lh_count = OBD_HEAT_COUNT;
10367                 rc2 = llapi_heat_get(fd, heat);
10368                 close(fd);
10369                 if (rc2 < 0) {
10370                         fprintf(stderr,
10371                                 "%s: cannot get heat of file '%s': %s\n",
10372                                 argv[0], path, strerror(errno));
10373                         goto next;
10374                 }
10375
10376                 printf("flags: %x\n", heat->lh_flags);
10377                 for (i = 0; i < heat->lh_count; i++)
10378                         printf("%s: %llu\n", heat_names[i],
10379                                (unsigned long long)heat->lh_heat[i]);
10380 next:
10381                 if (rc == 0 && rc2 < 0)
10382                         rc = rc2;
10383         }
10384
10385         free(heat);
10386         return rc;
10387 }
10388
10389 static int lfs_heat_set(int argc, char **argv)
10390 {
10391         struct option long_opts[] = {
10392         { .val = 'c',   .name = "clear",        .has_arg = no_argument },
10393         { .val = 'h',   .name = "help",         .has_arg = no_argument },
10394         { .val = 'o',   .name = "off",          .has_arg = no_argument },
10395         { .val = 'O',   .name = "on",           .has_arg = no_argument },
10396         { .name = NULL } };
10397         enum lu_heat_flag flags = 0;
10398         int rc = 0, rc2;
10399         char *path;
10400         int fd;
10401         int c;
10402
10403         if (argc <= 1)
10404                 return CMD_HELP;
10405
10406         optind = 0;
10407         while ((c = getopt_long(argc, argv, "choO", long_opts, NULL)) != -1) {
10408                 switch (c) {
10409                 case 'c':
10410                         flags |= LU_HEAT_FLAG_CLEAR;
10411                         break;
10412                 case 'o':
10413                         flags |= LU_HEAT_FLAG_CLEAR;
10414                         flags |= LU_HEAT_FLAG_OFF;
10415                         break;
10416                 case 'O':
10417                         flags &= ~LU_HEAT_FLAG_OFF;
10418                         break;
10419                 default:
10420                         fprintf(stderr, "%s: unrecognized option '%s'\n",
10421                                 progname, argv[optind - 1]);
10422                         fallthrough;
10423                 case 'h':
10424                         return CMD_HELP;
10425                 }
10426         }
10427
10428         if (argc <= optind) {
10429                 fprintf(stderr, "%s: please give one or more file names\n",
10430                         argv[0]);
10431                 return CMD_HELP;
10432         }
10433
10434         while (optind < argc) {
10435                 path = argv[optind++];
10436
10437                 fd = open(path, O_RDONLY);
10438                 if (fd < 0) {
10439                         fprintf(stderr, "%s: cannot open file '%s': %s\n",
10440                                 argv[0], path, strerror(errno));
10441                         rc2 = -errno;
10442                         goto next;
10443                 }
10444
10445                 rc2 = llapi_heat_set(fd, flags);
10446                 close(fd);
10447                 if (rc2 < 0) {
10448                         fprintf(stderr,
10449                                 "%s: cannot setflags heat of file '%s': %s\n",
10450                                 argv[0], path, strerror(errno));
10451                         goto next;
10452                 }
10453 next:
10454                 if (rc == 0 && rc2 < 0)
10455                         rc = rc2;
10456         }
10457         return rc;
10458 }
10459
10460 /**
10461  * The input string contains a comma delimited list of component ids and
10462  * ranges, for example "1,2-4,7".
10463  */
10464 static int parse_mirror_ids(__u16 *ids, int size, char *arg)
10465 {
10466         bool end_of_loop = false;
10467         char *ptr = NULL;
10468         int nr = 0;
10469         int rc;
10470
10471         if (!arg)
10472                 return -EINVAL;
10473
10474         while (!end_of_loop) {
10475                 int start_index;
10476                 int end_index;
10477                 int i;
10478                 char *endptr = NULL;
10479
10480                 rc = -EINVAL;
10481                 ptr = strchrnul(arg, ',');
10482                 end_of_loop = *ptr == '\0';
10483                 *ptr = '\0';
10484
10485                 start_index = strtol(arg, &endptr, 0);
10486                 if (endptr == arg) /* no data at all */
10487                         break;
10488                 if (*endptr != '-' && *endptr != '\0') /* has invalid data */
10489                         break;
10490                 if (start_index < 0)
10491                         break;
10492
10493                 end_index = start_index;
10494                 if (*endptr == '-') {
10495                         end_index = strtol(endptr + 1, &endptr, 0);
10496                         if (*endptr != '\0')
10497                                 break;
10498                         if (end_index < start_index)
10499                                 break;
10500                 }
10501
10502                 for (i = start_index; i <= end_index && size > 0; i++) {
10503                         int j;
10504
10505                         /* remove duplicate */
10506                         for (j = 0; j < nr; j++) {
10507                                 if (ids[j] == i)
10508                                         break;
10509                         }
10510                         if (j == nr) { /* no duplicate */
10511                                 ids[nr++] = i;
10512                                 --size;
10513                         }
10514                 }
10515
10516                 if (size == 0 && i < end_index)
10517                         break;
10518
10519                 *ptr = ',';
10520                 arg = ++ptr;
10521                 rc = 0;
10522         }
10523         if (!end_of_loop && ptr)
10524                 *ptr = ',';
10525
10526         return rc < 0 ? rc : nr;
10527 }
10528
10529 /**
10530  * struct verify_mirror_id - Mirror id to be verified.
10531  * @mirror_id:   A specified mirror id.
10532  * @is_valid_id: @mirror_id is valid or not in the mirrored file.
10533  */
10534 struct verify_mirror_id {
10535         __u16 mirror_id;
10536         bool is_valid_id;
10537 };
10538
10539 /**
10540  * compare_mirror_ids() - Compare mirror ids.
10541  * @layout: Mirror component list.
10542  * @cbdata: Callback data in verify_mirror_id structure.
10543  *
10544  * This is a callback function called by llapi_layout_comp_iterate()
10545  * to compare the specified mirror id with the one in the current
10546  * component of @layout. If they are the same, then the specified
10547  * mirror id is valid.
10548  *
10549  * Return: a negative error code on failure or
10550  *         LLAPI_LAYOUT_ITER_CONT: Proceed iteration
10551  *         LLAPI_LAYOUT_ITER_STOP: Stop iteration
10552  */
10553 static inline
10554 int compare_mirror_ids(struct llapi_layout *layout, void *cbdata)
10555 {
10556         struct verify_mirror_id *mirror_id_cbdata =
10557                                  (struct verify_mirror_id *)cbdata;
10558         uint32_t mirror_id;
10559         int rc = 0;
10560
10561         rc = llapi_layout_mirror_id_get(layout, &mirror_id);
10562         if (rc < 0) {
10563                 rc = -errno;
10564                 fprintf(stderr,
10565                         "%s: llapi_layout_mirror_id_get failed: %s.\n",
10566                         progname, strerror(errno));
10567                 return rc;
10568         }
10569
10570         if (mirror_id_cbdata->mirror_id == mirror_id) {
10571                 mirror_id_cbdata->is_valid_id = true;
10572                 return LLAPI_LAYOUT_ITER_STOP;
10573         }
10574
10575         return LLAPI_LAYOUT_ITER_CONT;
10576 }
10577
10578 /**
10579  * verify_mirror_ids() - Verify specified mirror ids.
10580  * @fname:      Mirrored file name.
10581  * @mirror_ids: Specified mirror ids to be verified.
10582  * @ids_nr:     Number of specified mirror ids.
10583  *
10584  * This function verifies that specified @mirror_ids are valid
10585  * in the mirrored file @fname.
10586  *
10587  * Return: 0 on success or a negative error code on failure.
10588  */
10589 static inline
10590 int verify_mirror_ids(const char *fname, __u16 *mirror_ids, int ids_nr)
10591 {
10592         struct llapi_layout *layout = NULL;
10593         struct verify_mirror_id mirror_id_cbdata = { 0 };
10594         struct stat stbuf;
10595         uint32_t flr_state;
10596         int i;
10597         int fd;
10598         int rc = 0;
10599         int rc2 = 0;
10600
10601         if (ids_nr <= 0)
10602                 return -EINVAL;
10603
10604         if (stat(fname, &stbuf) < 0) {
10605                 fprintf(stderr, "%s: cannot stat file '%s': %s.\n",
10606                         progname, fname, strerror(errno));
10607                 rc = -errno;
10608                 goto error;
10609         }
10610
10611         if (!S_ISREG(stbuf.st_mode)) {
10612                 fprintf(stderr, "%s: '%s' is not a regular file.\n",
10613                         progname, fname);
10614                 rc = -EINVAL;
10615                 goto error;
10616         }
10617
10618         fd = open(fname, O_DIRECT | O_RDONLY);
10619         if (fd < 0) {
10620                 fprintf(stderr, "%s: cannot open '%s': %s.\n",
10621                         progname, fname, strerror(errno));
10622                 rc = -errno;
10623                 goto error;
10624         }
10625
10626         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
10627         if (rc < 0) {
10628                 fprintf(stderr, "%s: '%s' llapi_lease_acquire failed: %s.\n",
10629                         progname, fname, strerror(errno));
10630                 goto close_fd;
10631         }
10632
10633         layout = llapi_layout_get_by_fd(fd, 0);
10634         if (!layout) {
10635                 fprintf(stderr, "%s: '%s' llapi_layout_get_by_fd failed: %s.\n",
10636                         progname, fname, strerror(errno));
10637                 rc = -errno;
10638                 llapi_lease_release(fd);
10639                 goto close_fd;
10640         }
10641
10642         rc = llapi_layout_flags_get(layout, &flr_state);
10643         if (rc < 0) {
10644                 fprintf(stderr, "%s: '%s' llapi_layout_flags_get failed: %s.\n",
10645                         progname, fname, strerror(errno));
10646                 rc = -errno;
10647                 goto free_layout;
10648         }
10649
10650         flr_state &= LCM_FL_FLR_MASK;
10651         switch (flr_state) {
10652         case LCM_FL_NONE:
10653                 rc = -EINVAL;
10654                 fprintf(stderr, "%s: '%s' file state error: %s.\n",
10655                         progname, fname, llapi_layout_flags_string(flr_state));
10656                 goto free_layout;
10657         default:
10658                 break;
10659         }
10660
10661         rc2 = 0;
10662         for (i = 0; i < ids_nr; i++) {
10663                 mirror_id_cbdata.mirror_id = mirror_ids[i];
10664                 mirror_id_cbdata.is_valid_id = false;
10665
10666                 rc = llapi_layout_comp_iterate(layout, compare_mirror_ids,
10667                                                &mirror_id_cbdata);
10668                 if (rc < 0) {
10669                         rc = -errno;
10670                         fprintf(stderr,
10671                                 "%s: '%s' failed to verify mirror id: %u.\n",
10672                                 progname, fname, mirror_ids[i]);
10673                         goto free_layout;
10674                 }
10675
10676                 if (!mirror_id_cbdata.is_valid_id) {
10677                         rc2 = -EINVAL;
10678                         fprintf(stderr,
10679                                 "%s: '%s' invalid specified mirror id: %u.\n",
10680                                 progname, fname, mirror_ids[i]);
10681                 }
10682         }
10683         rc = rc2;
10684
10685 free_layout:
10686         llapi_layout_free(layout);
10687         llapi_lease_release(fd);
10688 close_fd:
10689         close(fd);
10690 error:
10691         return rc;
10692 }
10693
10694 static inline
10695 int lfs_mirror_resync_file(const char *fname, struct ll_ioc_lease *ioc,
10696                            __u16 *mirror_ids, int ids_nr)
10697 {
10698         struct llapi_resync_comp comp_array[1024] = { { 0 } };
10699         struct llapi_layout *layout;
10700         struct stat stbuf;
10701         uint32_t flr_state;
10702         uint64_t start;
10703         uint64_t end;
10704         int comp_size = 0;
10705         int idx;
10706         int fd;
10707         int rc;
10708         int rc2;
10709
10710         if (stat(fname, &stbuf) < 0) {
10711                 fprintf(stderr, "%s: cannot stat file '%s': %s.\n",
10712                         progname, fname, strerror(errno));
10713                 rc = -errno;
10714                 goto error;
10715         }
10716         if (!S_ISREG(stbuf.st_mode)) {
10717                 fprintf(stderr, "%s: '%s' is not a regular file.\n",
10718                         progname, fname);
10719                 rc = -EINVAL;
10720                 goto error;
10721         }
10722
10723         /* Allow mirror resync even without the key on encrypted files */
10724         fd = open(fname, O_DIRECT | O_RDWR | O_FILE_ENC);
10725         if (fd < 0) {
10726                 fprintf(stderr, "%s: cannot open '%s': %s.\n",
10727                         progname, fname, strerror(errno));
10728                 rc = -errno;
10729                 goto error;
10730         }
10731
10732         layout = llapi_layout_get_by_fd(fd, 0);
10733         if (!layout) {
10734                 fprintf(stderr, "%s: '%s' llapi_layout_get_by_fd failed: %s.\n",
10735                         progname, fname, strerror(errno));
10736                 rc = -errno;
10737                 goto close_fd;
10738         }
10739
10740         rc = llapi_layout_flags_get(layout, &flr_state);
10741         if (rc) {
10742                 fprintf(stderr, "%s: '%s' llapi_layout_flags_get failed: %s.\n",
10743                         progname, fname, strerror(errno));
10744                 rc = -errno;
10745                 goto free_layout;
10746         }
10747
10748         flr_state &= LCM_FL_FLR_MASK;
10749         if (flr_state == LCM_FL_NONE) {
10750                 rc = -EINVAL;
10751                 fprintf(stderr, "%s: '%s' is not a FLR file.\n",
10752                         progname, fname);
10753                 goto free_layout;
10754         }
10755
10756         /* get stale component info */
10757         comp_size = llapi_mirror_find_stale(layout, comp_array,
10758                                             ARRAY_SIZE(comp_array),
10759                                             mirror_ids, ids_nr);
10760         if (comp_size <= 0) {
10761                 rc = comp_size;
10762                 goto free_layout;
10763         }
10764
10765         ioc->lil_mode = LL_LEASE_WRLCK;
10766         ioc->lil_flags = LL_LEASE_RESYNC;
10767         rc = llapi_lease_set(fd, ioc);
10768         if (rc < 0) {
10769                 if (rc == -EALREADY)
10770                         rc = 0;
10771                 else
10772                         fprintf(stderr,
10773                             "%s: '%s' llapi_lease_get_ext resync failed: %s.\n",
10774                                 progname, fname, strerror(-rc));
10775                 goto free_layout;
10776         }
10777
10778         /* get the read range [start, end) */
10779         start = comp_array[0].lrc_start;
10780         end = comp_array[0].lrc_end;
10781         for (idx = 1; idx < comp_size; idx++) {
10782                 if (comp_array[idx].lrc_start < start)
10783                         start = comp_array[idx].lrc_start;
10784                 if (end < comp_array[idx].lrc_end)
10785                         end = comp_array[idx].lrc_end;
10786         }
10787
10788         rc = llapi_lease_check(fd);
10789         if (rc != LL_LEASE_WRLCK) {
10790                 fprintf(stderr, "%s: '%s' lost lease lock.\n",
10791                         progname, fname);
10792                 goto free_layout;
10793         }
10794
10795         rc = llapi_mirror_resync_many(fd, layout, comp_array, comp_size,
10796                                       start, end);
10797         if (rc < 0)
10798                 fprintf(stderr, "%s: '%s' llapi_mirror_resync_many: %s.\n",
10799                         progname, fname, strerror(-rc));
10800
10801         rc = migrate_set_timestamps(fd, &stbuf);
10802         if (rc < 0) {
10803                 fprintf(stderr, "%s: '%s' cannot set timestamps: %s\n",
10804                         progname, fname, strerror(-rc));
10805                 goto free_layout;
10806         }
10807
10808         /* need to do the lease unlock even resync fails */
10809         ioc->lil_mode = LL_LEASE_UNLCK;
10810         ioc->lil_flags = LL_LEASE_RESYNC_DONE;
10811         ioc->lil_count = 0;
10812         for (idx = 0; idx < comp_size; idx++) {
10813                 if (comp_array[idx].lrc_synced) {
10814                         ioc->lil_ids[ioc->lil_count] = comp_array[idx].lrc_id;
10815                         ioc->lil_count++;
10816                 }
10817         }
10818
10819         rc2 = llapi_lease_set(fd, ioc);
10820         /**
10821          * llapi_lease_set returns lease mode when it request to unlock
10822          * the lease lock.
10823          */
10824         if (rc2 <= 0) {
10825                 /* rc2 == 0 means lost lease lock */
10826                 if (rc2 == 0 && rc == 0)
10827                         rc = -EBUSY;
10828                 else
10829                         rc = rc2;
10830                 fprintf(stderr, "%s: resync file '%s' failed: %s.\n",
10831                         progname, fname,
10832                         rc2 == 0 ? "lost lease lock" : strerror(-rc2));
10833
10834                 llapi_lease_release(fd);
10835                 goto free_layout;
10836         }
10837
10838 free_layout:
10839         llapi_layout_free(layout);
10840 close_fd:
10841         close(fd);
10842 error:
10843         return rc;
10844 }
10845
10846 static inline int lfs_mirror_resync(int argc, char **argv)
10847 {
10848         struct option long_opts[] = {
10849         { .val = 'h',   .name = "help",         .has_arg = no_argument },
10850         { .val = 'o',   .name = "only",         .has_arg = required_argument },
10851         { .name = NULL } };
10852         struct ll_ioc_lease *ioc = NULL;
10853         __u16 mirror_ids[128] = { 0 };
10854         int ids_nr = 0;
10855         int c;
10856         int rc = 0;
10857
10858         while ((c = getopt_long(argc, argv, "ho:", long_opts, NULL)) >= 0) {
10859                 switch (c) {
10860                 case 'o':
10861                         rc = parse_mirror_ids(mirror_ids,
10862                                         sizeof(mirror_ids) / sizeof(__u16),
10863                                         optarg);
10864                         if (rc < 0) {
10865                                 fprintf(stderr,
10866                                         "%s: bad mirror ids '%s'.\n",
10867                                         argv[0], optarg);
10868                                 goto error;
10869                         }
10870                         ids_nr = rc;
10871                         break;
10872                 default:
10873                         fprintf(stderr, "%s: unrecognized option '%s'\n",
10874                                 progname, argv[optind - 1]);
10875                         fallthrough;
10876                 case 'h':
10877                         rc = CMD_HELP;
10878                         goto error;
10879                 }
10880         }
10881
10882         if (argc == optind) {
10883                 fprintf(stderr, "%s: no file name given.\n", argv[0]);
10884                 rc = CMD_HELP;
10885                 goto error;
10886         }
10887
10888         if (ids_nr > 0 && argc > optind + 1) {
10889                 fprintf(stderr,
10890                     "%s: option '--only' cannot be used upon multiple files.\n",
10891                         argv[0]);
10892                 rc = CMD_HELP;
10893                 goto error;
10894         }
10895
10896         if (ids_nr > 0) {
10897                 rc = verify_mirror_ids(argv[optind], mirror_ids, ids_nr);
10898                 if (rc < 0)
10899                         goto error;
10900         }
10901
10902         /* set the lease on the file */
10903         ioc = calloc(sizeof(*ioc) + sizeof(__u32) * 4096, 1);
10904         if (!ioc) {
10905                 fprintf(stderr, "%s: cannot alloc id array for ioc: %s.\n",
10906                         argv[0], strerror(errno));
10907                 rc = -errno;
10908                 goto error;
10909         }
10910
10911         for (; optind < argc; optind++) {
10912                 rc = lfs_mirror_resync_file(argv[optind], ioc,
10913                                             mirror_ids, ids_nr);
10914                 /* ignore previous file's error, continue with next file */
10915
10916                 /* reset ioc */
10917                 memset(ioc, 0, sizeof(*ioc) + sizeof(__u32) * 4096);
10918         }
10919
10920         free(ioc);
10921 error:
10922         return rc;
10923 }
10924
10925 static inline int verify_mirror_id_by_fd(int fd, __u16 mirror_id)
10926 {
10927         struct llapi_layout *layout;
10928         int rc;
10929
10930         layout = llapi_layout_get_by_fd(fd, 0);
10931         if (!layout) {
10932                 fprintf(stderr, "could not get layout.\n");
10933                 return  -EINVAL;
10934         }
10935
10936         rc = llapi_layout_comp_iterate(layout, find_mirror_id, &mirror_id);
10937         if (rc < 0) {
10938                 fprintf(stderr, "failed to iterate layout\n");
10939                 llapi_layout_free(layout);
10940
10941                 return rc;
10942         } else if (rc == LLAPI_LAYOUT_ITER_CONT) {
10943                 fprintf(stderr, "does not find mirror with ID %u\n", mirror_id);
10944                 llapi_layout_free(layout);
10945
10946                 return -EINVAL;
10947         }
10948         llapi_layout_free(layout);
10949
10950         return 0;
10951 }
10952
10953 /**
10954  * Check whether two files are the same file
10955  * \retval      0  same file
10956  * \retval      1  not the same file
10957  * \retval      <0 error code
10958  */
10959 static inline int check_same_file(int fd, const char *f2)
10960 {
10961         struct stat stbuf1;
10962         struct stat stbuf2;
10963
10964         if (fstat(fd, &stbuf1) < 0)
10965                 return -errno;
10966
10967         if (stat(f2, &stbuf2) < 0)
10968                 return 1;
10969
10970         if (stbuf1.st_rdev == stbuf2.st_rdev &&
10971             stbuf1.st_ino == stbuf2.st_ino)
10972                 return 0;
10973
10974         return 1;
10975 }
10976
10977 static inline int lfs_mirror_read(int argc, char **argv)
10978 {
10979         int rc = CMD_HELP;
10980         __u16 mirror_id = 0;
10981         const char *outfile = NULL;
10982         char *fname;
10983         int fd = 0;
10984         int outfd;
10985         int c;
10986         void *buf;
10987         const size_t buflen = 4 << 20;
10988         off_t pos;
10989         struct option long_opts[] = {
10990         { .val = 'h',   .name = "help",         .has_arg = no_argument },
10991         { .val = 'N',   .name = "mirror-id",    .has_arg = required_argument },
10992         { .val = 'o',   .name = "outfile",      .has_arg = required_argument },
10993         { .name = NULL } };
10994
10995         while ((c = getopt_long(argc, argv, "hN:o:", long_opts, NULL)) >= 0) {
10996                 char *end;
10997
10998                 switch (c) {
10999                 case 'N': {
11000                         unsigned long int id;
11001
11002                         errno = 0;
11003                         id = strtoul(optarg, &end, 0);
11004                         if (errno != 0 || *end != '\0' || id == 0 ||
11005                             id > UINT16_MAX) {
11006                                 fprintf(stderr,
11007                                         "%s %s: invalid mirror ID '%s'\n",
11008                                         progname, argv[0], optarg);
11009                                 return rc;
11010                         }
11011
11012                         mirror_id = (__u16)id;
11013                         break;
11014                 }
11015                 case 'o':
11016                         outfile = optarg;
11017                         break;
11018                 default:
11019                         fprintf(stderr, "%s: unrecognized option '%s'\n",
11020                                 progname, argv[optind - 1]);
11021                         fallthrough;
11022                 case 'h':
11023                         return CMD_HELP;
11024                 }
11025         }
11026
11027         if (argc == optind) {
11028                 fprintf(stderr, "%s %s: no mirrored file provided\n",
11029                         progname, argv[0]);
11030                 return rc;
11031         } else if (argc > optind + 1) {
11032                 fprintf(stderr, "%s %s: too many files\n", progname, argv[0]);
11033                 return rc;
11034         }
11035
11036         if (mirror_id == 0) {
11037                 fprintf(stderr, "%s %s: no valid mirror ID is provided\n",
11038                         progname, argv[0]);
11039                 return rc;
11040         }
11041
11042         /* open mirror file */
11043         fname = argv[optind];
11044         fd = open(fname, O_DIRECT | O_RDONLY);
11045         if (fd < 0) {
11046                 fprintf(stderr, "%s %s: cannot open '%s': %s\n",
11047                         progname, argv[0], fname, strerror(errno));
11048                 return rc;
11049         }
11050
11051         /* verify mirror id */
11052         rc = verify_mirror_id_by_fd(fd, mirror_id);
11053         if (rc) {
11054                 fprintf(stderr,
11055                         "%s %s: cannot find mirror with ID %u in '%s'\n",
11056                         progname, argv[0], mirror_id, fname);
11057                 goto close_fd;
11058         }
11059
11060         /* open output file - O_EXCL ensures output is not the same as input */
11061         if (outfile) {
11062                 outfd = open(outfile, O_EXCL | O_WRONLY | O_CREAT, 0644);
11063                 if (outfd < 0) {
11064                         fprintf(stderr, "%s %s: cannot create file '%s': %s\n",
11065                                 progname, argv[0], outfile, strerror(errno));
11066                         rc = -errno;
11067                         goto close_fd;
11068                 }
11069         } else {
11070                 outfd = STDOUT_FILENO;
11071         }
11072
11073         /* allocate buffer */
11074         rc = posix_memalign(&buf, sysconf(_SC_PAGESIZE), buflen);
11075         if (rc) {
11076                 fprintf(stderr, "%s %s: posix_memalign returns %d\n",
11077                                 progname, argv[0], rc);
11078                 goto close_outfd;
11079         }
11080
11081         pos = 0;
11082         while (1) {
11083                 ssize_t bytes_read;
11084                 ssize_t written = 0;
11085
11086                 bytes_read = llapi_mirror_read(fd, mirror_id, buf, buflen, pos);
11087                 if (bytes_read < 0) {
11088                         rc = bytes_read;
11089                         fprintf(stderr,
11090                                 "%s %s: fail to read data from mirror %u: %s\n",
11091                                 progname, argv[0], mirror_id, strerror(-rc));
11092                         goto free_buf;
11093                 }
11094
11095                 /* EOF reached */
11096                 if (bytes_read == 0)
11097                         break;
11098
11099                 while (written < bytes_read) {
11100                         ssize_t written2;
11101
11102                         written2 = write(outfd, buf + written,
11103                                          bytes_read - written);
11104                         if (written2 < 0) {
11105                                 fprintf(stderr,
11106                                         "%s %s: fail to write %s: %s\n",
11107                                         progname, argv[0], outfile ? : "STDOUT",
11108                                         strerror(errno));
11109                                 rc = -errno;
11110                                 goto free_buf;
11111                         }
11112                         written += written2;
11113                 }
11114
11115                 if (written != bytes_read) {
11116                         fprintf(stderr,
11117                 "%s %s: written %ld bytes does not match with %ld read.\n",
11118                                 progname, argv[0], written, bytes_read);
11119                         rc = -EIO;
11120                         goto free_buf;
11121                 }
11122
11123                 pos += bytes_read;
11124         }
11125
11126         fsync(outfd);
11127         rc = 0;
11128
11129 free_buf:
11130         free(buf);
11131 close_outfd:
11132         if (outfile)
11133                 close(outfd);
11134 close_fd:
11135         close(fd);
11136
11137         return rc;
11138 }
11139
11140 static inline int lfs_mirror_write(int argc, char **argv)
11141 {
11142         int rc = CMD_HELP;
11143         __u16 mirror_id = 0;
11144         const char *inputfile = NULL;
11145         char *fname;
11146         int fd = 0;
11147         int inputfd;
11148         int c;
11149         void *buf;
11150         const size_t buflen = 4 << 20;
11151         off_t pos;
11152         size_t page_size = sysconf(_SC_PAGESIZE);
11153         struct ll_ioc_lease_id ioc;
11154         struct option long_opts[] = {
11155         { .val = 'h',   .name = "help",         .has_arg = no_argument },
11156         { .val = 'i',   .name = "inputfile",    .has_arg = required_argument },
11157         { .val = 'N',   .name = "mirror-id",    .has_arg = required_argument },
11158         { .name = NULL } };
11159
11160         while ((c = getopt_long(argc, argv, "hi:N:", long_opts, NULL)) >= 0) {
11161                 char *end;
11162
11163                 switch (c) {
11164                 case 'N': {
11165                         unsigned long int id;
11166
11167                         errno = 0;
11168                         id = strtoul(optarg, &end, 0);
11169                         if (errno != 0 || *end != '\0' || id == 0 ||
11170                             id > UINT16_MAX) {
11171                                 fprintf(stderr,
11172                                         "%s %s: invalid mirror ID '%s'\n",
11173                                         progname, argv[0], optarg);
11174                                 return rc;
11175                         }
11176
11177                         mirror_id = (__u16)id;
11178                         break;
11179                 }
11180                 case 'i':
11181                         inputfile = optarg;
11182                         break;
11183                 default:
11184                         fprintf(stderr, "%s: unrecognized option '%s'\n",
11185                                 progname, argv[optind - 1]);
11186                         fallthrough;
11187                 case 'h':
11188                         return CMD_HELP;
11189                 }
11190         }
11191
11192         if (argc == optind) {
11193                 fprintf(stderr, "%s %s: no mirrored file provided\n",
11194                         progname, argv[0]);
11195                 return rc;
11196         } else if (argc > optind + 1) {
11197                 fprintf(stderr, "%s %s: too many files\n", progname, argv[0]);
11198                 return rc;
11199         }
11200
11201         if (mirror_id == 0) {
11202                 fprintf(stderr, "%s %s: no valid mirror ID is provided\n",
11203                         progname, argv[0]);
11204                 return rc;
11205         }
11206
11207         /* open mirror file */
11208         fname = argv[optind];
11209         fd = open(fname, O_DIRECT | O_WRONLY);
11210         if (fd < 0) {
11211                 fprintf(stderr, "%s %s: cannot open '%s': %s\n",
11212                         progname, argv[0], fname, strerror(errno));
11213                 return rc;
11214         }
11215
11216         /* verify mirror id */
11217         rc = verify_mirror_id_by_fd(fd, mirror_id);
11218         if (rc) {
11219                 fprintf(stderr,
11220                         "%s %s: cannot find mirror with ID %u in '%s'\n",
11221                         progname, argv[0], mirror_id, fname);
11222                 goto close_fd;
11223         }
11224
11225         /* open input file */
11226         if (inputfile) {
11227                 rc = check_same_file(fd, inputfile);
11228                 if (rc == 0) {
11229                         fprintf(stderr,
11230                         "%s %s: input file cannot be the mirrored file\n",
11231                                 progname, argv[0]);
11232                         goto close_fd;
11233                 }
11234                 if (rc < 0)
11235                         goto close_fd;
11236
11237                 inputfd = open(inputfile, O_RDONLY, 0644);
11238                 if (inputfd < 0) {
11239                         fprintf(stderr, "%s %s: cannot open file '%s': %s\n",
11240                                 progname, argv[0], inputfile, strerror(errno));
11241                         rc = -errno;
11242                         goto close_fd;
11243                 }
11244         } else {
11245                 inputfd = STDIN_FILENO;
11246         }
11247
11248         /* allocate buffer */
11249         rc = posix_memalign(&buf, page_size, buflen);
11250         if (rc) {
11251                 fprintf(stderr, "%s %s: posix_memalign returns %d\n",
11252                         progname, argv[0], rc);
11253                 goto close_inputfd;
11254         }
11255
11256         /* prepare target mirror components instantiation */
11257         ioc.lil_mode = LL_LEASE_WRLCK;
11258         ioc.lil_flags = LL_LEASE_RESYNC;
11259         ioc.lil_mirror_id = mirror_id;
11260         rc = llapi_lease_set(fd, (struct ll_ioc_lease *)&ioc);
11261         if (rc < 0) {
11262                 fprintf(stderr,
11263                         "%s %s: '%s' llapi_lease_get_ext failed: %s\n",
11264                         progname, argv[0], fname, strerror(errno));
11265                 goto free_buf;
11266         }
11267
11268         pos = 0;
11269         while (1) {
11270                 ssize_t bytes_read;
11271                 ssize_t written;
11272                 size_t to_write;
11273
11274                 rc = llapi_lease_check(fd);
11275                 if (rc != LL_LEASE_WRLCK) {
11276                         fprintf(stderr, "%s %s: '%s' lost lease lock\n",
11277                                 progname, argv[0], fname);
11278                         goto free_buf;
11279                 }
11280
11281                 bytes_read = read(inputfd, buf, buflen);
11282                 if (bytes_read < 0) {
11283                         rc = bytes_read;
11284                         fprintf(stderr,
11285                                 "%s %s: fail to read data from '%s': %s\n",
11286                                 progname, argv[0], inputfile ? : "STDIN",
11287                                 strerror(errno));
11288                         rc = -errno;
11289                         goto free_buf;
11290                 }
11291
11292                 /* EOF reached */
11293                 if (bytes_read == 0)
11294                         break;
11295
11296                 /* round up to page align to make direct IO happy. */
11297                 to_write = (bytes_read + page_size - 1) & ~(page_size - 1);
11298
11299                 written = llapi_mirror_write(fd, mirror_id, buf, to_write,
11300                                              pos);
11301                 if (written < 0) {
11302                         rc = written;
11303                         fprintf(stderr,
11304                               "%s %s: fail to write to mirror %u: %s\n",
11305                                 progname, argv[0], mirror_id,
11306                                 strerror(-rc));
11307                         goto free_buf;
11308                 }
11309
11310                 pos += bytes_read;
11311         }
11312
11313         if (pos & (page_size - 1)) {
11314                 rc = llapi_mirror_truncate(fd, mirror_id, pos);
11315                 if (rc < 0)
11316                         goto free_buf;
11317         }
11318
11319         ioc.lil_mode = LL_LEASE_UNLCK;
11320         ioc.lil_flags = LL_LEASE_RESYNC_DONE;
11321         ioc.lil_count = 0;
11322         rc = llapi_lease_set(fd, (struct ll_ioc_lease *)&ioc);
11323         if (rc <= 0) {
11324                 if (rc == 0)
11325                         rc = -EBUSY;
11326                 fprintf(stderr,
11327                         "%s %s: release lease lock of '%s' failed: %s\n",
11328                         progname, argv[0], fname, strerror(errno));
11329                 goto free_buf;
11330         }
11331
11332         rc = 0;
11333
11334 free_buf:
11335         free(buf);
11336 close_inputfd:
11337         if (inputfile)
11338                 close(inputfd);
11339 close_fd:
11340         close(fd);
11341
11342         return rc;
11343 }
11344
11345 static inline int get_other_mirror_ids(int fd, __u16 *ids, __u16 exclude_id)
11346 {
11347         struct llapi_layout *layout;
11348         struct collect_ids_data cid = { .cid_ids = ids,
11349                                         .cid_count = 0,
11350                                         .cid_exclude = exclude_id, };
11351         int rc;
11352
11353         layout = llapi_layout_get_by_fd(fd, 0);
11354         if (!layout) {
11355                 fprintf(stderr, "could not get layout\n");
11356                 return -EINVAL;
11357         }
11358
11359         rc = llapi_layout_comp_iterate(layout, collect_mirror_id, &cid);
11360         if (rc < 0) {
11361                 fprintf(stderr, "failed to iterate layout\n");
11362                 llapi_layout_free(layout);
11363
11364                 return rc;
11365         }
11366         llapi_layout_free(layout);
11367
11368         return cid.cid_count;
11369 }
11370
11371 #ifndef MIRROR_ID_NEG
11372 #define MIRROR_ID_NEG         0x8000
11373 #endif
11374
11375 static inline int lfs_mirror_copy(int argc, char **argv)
11376 {
11377         int rc = CMD_HELP;
11378         __u16 read_mirror_id = 0;
11379         __u16 ids[128] = { 0 };
11380         int count = 0;
11381         struct llapi_layout *layout = NULL;
11382         struct llapi_resync_comp comp_array[1024] = { { 0 } };
11383         int comp_size = 0;
11384         char *fname;
11385         int fd = 0;
11386         int c;
11387         int i;
11388         ssize_t copied;
11389         struct ll_ioc_lease *ioc = NULL;
11390         struct ll_ioc_lease_id *resync_ioc;
11391         struct option long_opts[] = {
11392         { .val = 'h',   .name = "help",         .has_arg = no_argument },
11393         { .val = 'i',   .name = "read-mirror",  .has_arg = required_argument },
11394         { .val = 'o',   .name = "write-mirror", .has_arg = required_argument },
11395         { .name = NULL } };
11396         char cmd[PATH_MAX];
11397
11398         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
11399         progname = cmd;
11400         while ((c = getopt_long(argc, argv, "hi:o:", long_opts, NULL)) >= 0) {
11401                 char *end;
11402
11403                 switch (c) {
11404                 case 'i': {
11405                         unsigned long int id;
11406
11407                         errno = 0;
11408                         id = strtoul(optarg, &end, 0);
11409                         if (errno != 0 || *end != '\0' || id == 0 ||
11410                             id > UINT16_MAX) {
11411                                 fprintf(stderr,
11412                                         "%s: invalid read mirror ID '%s'\n",
11413                                         progname, optarg);
11414                                 return rc;
11415                         }
11416
11417                         read_mirror_id = (__u16)id;
11418                         break;
11419                 }
11420                 case 'o':
11421                         if (!strcmp(optarg, "-1")) {
11422                                 /* specify all other mirrors */
11423                                 ids[0] = (__u16)-1;
11424                                 count = 1;
11425                         } else {
11426                                 count = parse_mirror_ids((__u16 *)ids,
11427                                                          ARRAY_SIZE(ids),
11428                                                          optarg);
11429                                 if (count < 0)
11430                                         return rc;
11431                         }
11432                         break;
11433                 default:
11434                         fprintf(stderr, "%s: unrecognized option '%s'\n",
11435                                 progname, argv[optind - 1]);
11436                         fallthrough;
11437                 case 'h':
11438                         return CMD_HELP;
11439                 }
11440         }
11441
11442         if (argc == optind) {
11443                 fprintf(stderr, "%s %s: no mirrored file provided\n",
11444                         progname, argv[0]);
11445                 return rc;
11446         } else if (argc > optind + 1) {
11447                 fprintf(stderr, "%s %s: too many files\n", progname, argv[0]);
11448                 return rc;
11449         }
11450
11451         if (read_mirror_id == 0) {
11452                 fprintf(stderr,
11453                         "%s %s: no valid read mirror ID %d is provided\n",
11454                         progname, argv[0], read_mirror_id);
11455                 return rc;
11456         }
11457
11458         if (count == 0) {
11459                 fprintf(stderr,
11460                         "%s %s: no write mirror ID is provided\n",
11461                         progname, argv[0]);
11462                 return rc;
11463         }
11464
11465         for (i = 0; i < count; i++) {
11466                 if (read_mirror_id == ids[i]) {
11467                         fprintf(stderr,
11468                         "%s %s: read and write mirror ID cannot be the same\n",
11469                                 progname, argv[0]);
11470                         return rc;
11471                 }
11472         }
11473
11474         /* open mirror file */
11475         fname = argv[optind];
11476
11477         fd = open(fname, O_DIRECT | O_RDWR);
11478         if (fd < 0) {
11479                 fprintf(stderr, "%s %s: cannot open '%s': %s\n",
11480                         progname, argv[0], fname, strerror(errno));
11481                 return rc;
11482         }
11483
11484         /* write to all other mirrors */
11485         if (ids[0] == (__u16)-1) {
11486                 count = get_other_mirror_ids(fd, ids, read_mirror_id);
11487                 if (count <= 0) {
11488                         rc = count;
11489                         fprintf(stderr,
11490                         "%s %s: failed to get other mirror ids in '%s': %d\n",
11491                                 progname, argv[0], fname, rc);
11492                         goto close_fd;
11493                 }
11494         }
11495
11496         /* verify mirror id */
11497         rc = verify_mirror_id_by_fd(fd, read_mirror_id);
11498         if (rc) {
11499                 fprintf(stderr,
11500                         "%s %s: cannot find mirror with ID %u in '%s'\n",
11501                         progname, argv[0], read_mirror_id, fname);
11502                 goto close_fd;
11503         }
11504
11505         for (i = 0; i < count; i++) {
11506                 rc = verify_mirror_id_by_fd(fd, ids[i]);
11507                 if (rc) {
11508                         fprintf(stderr,
11509                         "%s %s: cannot find mirror with ID %u in '%s'\n",
11510                                 progname, argv[0], ids[i], fname);
11511                         goto close_fd;
11512                 }
11513         }
11514
11515         ioc = calloc(sizeof(*ioc) + sizeof(__u32) * 4096, 1);
11516         if (!ioc) {
11517                 fprintf(stderr,
11518                         "%s %s: cannot alloc comp id array for ioc: %s\n",
11519                         progname, argv[0], strerror(errno));
11520                 rc = -errno;
11521                 goto close_fd;
11522         }
11523
11524         /* get stale component info */
11525         layout = llapi_layout_get_by_fd(fd, 0);
11526         if (!layout) {
11527                 fprintf(stderr, "%s %s: failed to get layout of '%s': %s\n",
11528                         progname, argv[0], fname, strerror(errno));
11529                 rc = -errno;
11530                 goto free_ioc;
11531         }
11532         comp_size = llapi_mirror_find_stale(layout, comp_array,
11533                                             ARRAY_SIZE(comp_array),
11534                                             ids, count);
11535         llapi_layout_free(layout);
11536         if (comp_size < 0) {
11537                 rc = comp_size;
11538                 goto free_ioc;
11539         }
11540
11541         /* prepare target mirror components instantiation */
11542         resync_ioc = (struct ll_ioc_lease_id *)ioc;
11543         resync_ioc->lil_mode = LL_LEASE_WRLCK;
11544         resync_ioc->lil_flags = LL_LEASE_RESYNC;
11545         if (count == 1)
11546                 resync_ioc->lil_mirror_id = ids[0];
11547         else
11548                 resync_ioc->lil_mirror_id = read_mirror_id | MIRROR_ID_NEG;
11549         rc = llapi_lease_set(fd, ioc);
11550         if (rc < 0) {
11551                 fprintf(stderr,
11552                         "%s %s: '%s' llapi_lease_get_ext failed: %s\n",
11553                         progname, argv[0], fname, strerror(errno));
11554                 goto free_ioc;
11555         }
11556
11557         copied = llapi_mirror_copy_many(fd, read_mirror_id, ids, count);
11558         if (copied < 0) {
11559                 rc = copied;
11560                 fprintf(stderr, "%s %s: copy error: %d\n",
11561                         progname, argv[0], rc);
11562                 goto free_ioc;
11563         }
11564
11565         fprintf(stdout, "mirror copied successfully: ");
11566         for (i = 0; i < copied; i++)
11567                 fprintf(stdout, "%d ", ids[i]);
11568         fprintf(stdout, "\n");
11569
11570         ioc->lil_mode = LL_LEASE_UNLCK;
11571         ioc->lil_flags = LL_LEASE_RESYNC_DONE;
11572         ioc->lil_count = 0;
11573         for (i = 0; i < comp_size; i++) {
11574                 int j;
11575
11576                 for (j = 0; j < copied; j++) {
11577                         if (comp_array[i].lrc_mirror_id != ids[j])
11578                                 continue;
11579
11580                         ioc->lil_ids[ioc->lil_count] = comp_array[i].lrc_id;
11581                         ioc->lil_count++;
11582                 }
11583         }
11584         rc = llapi_lease_set(fd, ioc);
11585         if (rc <= 0) {
11586                 if (rc == 0)
11587                         rc = -EBUSY;
11588                 fprintf(stderr,
11589                         "%s %s: release lease lock of '%s' failed: %s\n",
11590                         progname, argv[0], fname, strerror(errno));
11591                 goto free_ioc;
11592         }
11593
11594         rc = 0;
11595
11596 free_ioc:
11597         free(ioc);
11598 close_fd:
11599         close(fd);
11600
11601         return rc;
11602 }
11603
11604 /**
11605  * struct verify_chunk - Mirror chunk to be verified.
11606  * @chunk:        [start, end) of the chunk.
11607  * @mirror_count: Number of mirror ids in @mirror_id array.
11608  * @mirror_id:    Array of valid mirror ids that cover the chunk.
11609  */
11610 struct verify_chunk {
11611         struct lu_extent chunk;
11612         unsigned int mirror_count;
11613         __u16 mirror_id[LUSTRE_MIRROR_COUNT_MAX];
11614 };
11615
11616 /**
11617  * print_chunks() - Print chunk information.
11618  * @fname:       Mirrored file name.
11619  * @chunks:      Array of chunks.
11620  * @chunk_count: Number of chunks in @chunks array.
11621  *
11622  * This function prints [start, end) of each chunk in @chunks
11623  * for mirrored file @fname, and also prints the valid mirror ids
11624  * that cover the chunk.
11625  *
11626  * Return: void.
11627  */
11628 static inline
11629 void print_chunks(const char *fname, struct verify_chunk *chunks,
11630                   int chunk_count)
11631 {
11632         int i;
11633         int j;
11634
11635         fprintf(stdout, "Chunks to be verified in %s:\n", fname);
11636         for (i = 0; i < chunk_count; i++) {
11637                 fprintf(stdout, DEXT, PEXT(&chunks[i].chunk));
11638
11639                 if (chunks[i].mirror_count == 0)
11640                         fprintf(stdout, "\t[");
11641                 else {
11642                         fprintf(stdout, "\t[%u", chunks[i].mirror_id[0]);
11643                         for (j = 1; j < chunks[i].mirror_count; j++)
11644                                 fprintf(stdout, ", %u", chunks[i].mirror_id[j]);
11645                 }
11646                 fprintf(stdout, "]\t%u\n", chunks[i].mirror_count);
11647         }
11648         fprintf(stdout, "\n");
11649 }
11650
11651 /**
11652  * print_checksums() - Print CRC-32 checksum values.
11653  * @chunk: A chunk and its corresponding valid mirror ids.
11654  * @crc:   CRC-32 checksum values on the chunk for each valid mirror.
11655  *
11656  * This function prints CRC-32 checksum values on @chunk for
11657  * each valid mirror that covers it.
11658  *
11659  * Return: void.
11660  */
11661 static inline
11662 void print_checksums(struct verify_chunk *chunk, unsigned long *crc,
11663                      unsigned long long pos, unsigned long long len)
11664 {
11665         int i;
11666
11667         fprintf(stdout,
11668                 "CRC-32 checksum value for chunk "DEXT":\n", pos, pos + len);
11669         for (i = 0; i < chunk->mirror_count; i++)
11670                 fprintf(stdout, "Mirror %u:\t%#lx\n",
11671                         chunk->mirror_id[i], crc[i]);
11672         fprintf(stdout, "\n");
11673 }
11674
11675 /**
11676  * filter_mirror_id() - Filter specified mirror ids.
11677  * @chunks:      Array of chunks.
11678  * @chunk_count: Number of chunks in @chunks array.
11679  * @mirror_ids:  Specified mirror ids to be verified.
11680  * @ids_nr:      Number of specified mirror ids.
11681  *
11682  * This function scans valid mirror ids that cover each chunk in @chunks
11683  * and filters specified mirror ids.
11684  *
11685  * Return: void.
11686  */
11687 static inline
11688 void filter_mirror_id(struct verify_chunk *chunks, int chunk_count,
11689                       __u16 *mirror_ids, int ids_nr)
11690 {
11691         int i;
11692         int j;
11693         int k;
11694         __u16 valid_id[LUSTRE_MIRROR_COUNT_MAX] = { 0 };
11695         unsigned int valid_count = 0;
11696
11697         for (i = 0; i < chunk_count; i++) {
11698                 if (chunks[i].mirror_count == 0)
11699                         continue;
11700
11701                 valid_count = 0;
11702                 for (j = 0; j < ids_nr; j++) {
11703                         for (k = 0; k < chunks[i].mirror_count; k++) {
11704                                 if (chunks[i].mirror_id[k] == mirror_ids[j]) {
11705                                         valid_id[valid_count] = mirror_ids[j];
11706                                         valid_count++;
11707                                         break;
11708                                 }
11709                         }
11710                 }
11711
11712                 memcpy(chunks[i].mirror_id, valid_id,
11713                        sizeof(__u16) * valid_count);
11714                 chunks[i].mirror_count = valid_count;
11715         }
11716 }
11717
11718 /**
11719  * lfs_mirror_prepare_chunk() - Find mirror chunks to be verified.
11720  * @layout:      Mirror component list.
11721  * @chunks:      Array of chunks.
11722  * @chunks_size: Array size of @chunks.
11723  *
11724  * This function scans the components in @layout from offset 0 to LUSTRE_EOF
11725  * to find out chunk segments and store them in @chunks array.
11726  *
11727  * The @mirror_id array in each element of @chunks will store the valid
11728  * mirror ids that cover the chunk. If a mirror component covering the
11729  * chunk has LCME_FL_STALE or LCME_FL_OFFLINE flag, then the mirror id
11730  * will not be stored into the @mirror_id array, and the chunk for that
11731  * mirror will not be verified.
11732  *
11733  * The @mirror_count in each element of @chunks will store the number of
11734  * mirror ids in @mirror_id array. If @mirror_count is 0, it indicates the
11735  * chunk is invalid in all of the mirrors. And if @mirror_count is 1, it
11736  * indicates the chunk is valid in only one mirror. In both cases, the
11737  * chunk will not be verified.
11738  *
11739  * Here is an example:
11740  *
11741  *  0      1M     2M     3M     4M           EOF
11742  *  +------+-------------+--------------------+
11743  *  |      |             |      S             |       mirror1
11744  *  +------+------+------+------+-------------+
11745  *  |             |   S  |   S  |             |       mirror2
11746  *  +-------------+------+------+-------------+
11747  *
11748  * prepared @chunks array will contain 5 elements:
11749  * (([0, 1M), [1, 2], 2),
11750  *  ([1M, 2M), [1, 2], 2),
11751  *  ([2M, 3M), [1], 1),
11752  *  ([3M, 4M], [], 0),
11753  *  ([4M, EOF), [2], 1))
11754  *
11755  * Return: the actual array size of @chunks on success
11756  *         or a negative error code on failure.
11757  */
11758 static inline
11759 int lfs_mirror_prepare_chunk(struct llapi_layout *layout,
11760                              struct verify_chunk *chunks,
11761                              size_t chunks_size)
11762 {
11763         uint64_t start;
11764         uint64_t end;
11765         uint32_t mirror_id;
11766         uint32_t flags;
11767         int idx = 0;
11768         int i = 0;
11769         int rc = 0;
11770
11771         memset(chunks, 0, sizeof(*chunks) * chunks_size);
11772
11773         while (1) {
11774                 rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_FIRST);
11775                 if (rc < 0) {
11776                         fprintf(stderr,
11777                                 "%s: move to the first layout component: %s.\n",
11778                                 progname, strerror(errno));
11779                         goto error;
11780                 }
11781
11782                 i = 0;
11783                 rc = 0;
11784                 chunks[idx].chunk.e_end = LUSTRE_EOF;
11785                 while (rc == 0) {
11786                         rc = llapi_layout_comp_extent_get(layout, &start, &end);
11787                         if (rc < 0) {
11788                                 fprintf(stderr,
11789                                         "%s: llapi_layout_comp_extent_get failed: %s.\n",
11790                                         progname, strerror(errno));
11791                                 goto error;
11792                         }
11793
11794                         if (start > chunks[idx].chunk.e_start ||
11795                             end <= chunks[idx].chunk.e_start)
11796                                 goto next;
11797
11798                         if (end < chunks[idx].chunk.e_end)
11799                                 chunks[idx].chunk.e_end = end;
11800
11801                         rc = llapi_layout_comp_flags_get(layout, &flags);
11802                         if (rc < 0) {
11803                                 fprintf(stderr,
11804                                         "%s: llapi_layout_comp_flags_get failed: %s.\n",
11805                                         progname, strerror(errno));
11806                                 goto error;
11807                         }
11808
11809                         if (flags & LCME_FL_STALE || flags & LCME_FL_OFFLINE)
11810                                 goto next;
11811
11812                         rc = llapi_layout_mirror_id_get(layout, &mirror_id);
11813                         if (rc < 0) {
11814                                 fprintf(stderr,
11815                                         "%s: llapi_layout_mirror_id_get failed: %s.\n",
11816                                         progname, strerror(errno));
11817                                 goto error;
11818                         }
11819
11820                         if (i >= ARRAY_SIZE(chunks[idx].mirror_id)) {
11821                                 fprintf(stderr,
11822                                         "%s: mirror_id array is too small.\n",
11823                                         progname);
11824                                 rc = -EINVAL;
11825                                 goto error;
11826                         }
11827                         chunks[idx].mirror_id[i] = mirror_id;
11828                         i++;
11829
11830 next:
11831                         rc = llapi_layout_comp_use(layout,
11832                                                    LLAPI_LAYOUT_COMP_USE_NEXT);
11833                         if (rc < 0) {
11834                                 fprintf(stderr,
11835                                         "%s: move to the next layout component: %s.\n",
11836                                         progname, strerror(errno));
11837                                 goto error;
11838                         }
11839                 } /* loop through all components */
11840
11841                 chunks[idx].mirror_count = i;
11842
11843                 if (chunks[idx].chunk.e_end == LUSTRE_EOF)
11844                         break;
11845
11846                 idx++;
11847                 if (idx >= chunks_size) {
11848                         fprintf(stderr, "%s: chunks array is too small.\n",
11849                                 progname);
11850                         rc = -EINVAL;
11851                         goto error;
11852                 }
11853
11854                 chunks[idx].chunk.e_start = chunks[idx - 1].chunk.e_end;
11855         }
11856
11857 error:
11858         return rc < 0 ? rc : idx + 1;
11859 }
11860
11861 /**
11862  * lfs_mirror_verify_chunk() - Verify a chunk.
11863  * @fd:        File descriptor of the mirrored file.
11864  * @file_size: Size of the mirrored file.
11865  * @chunk:     A chunk and its corresponding valid mirror ids.
11866  * @verbose:   Verbose mode.
11867  *
11868  * This function verifies a @chunk contains exactly the same data
11869  * ammong the mirrors that cover it.
11870  *
11871  * If @verbose is specified, then the function will print where the
11872  * differences are if the data do not match. Otherwise, it will
11873  * just return an error in that case.
11874  *
11875  * Return: 0 on success or a negative error code on failure.
11876  */
11877 static inline
11878 int lfs_mirror_verify_chunk(int fd, size_t file_size,
11879                             struct verify_chunk *chunk, int verbose)
11880 {
11881         const size_t buflen = 4 * 1024 * 1024; /* 4M */
11882         void *buf;
11883         size_t page_size = sysconf(_SC_PAGESIZE);
11884         ssize_t bytes_read;
11885         ssize_t bytes_done;
11886         size_t count;
11887         off_t pos;
11888         unsigned long crc;
11889         unsigned long crc_array[LUSTRE_MIRROR_COUNT_MAX] = { 0 };
11890         int i;
11891         int rc = 0;
11892
11893         if (file_size == 0)
11894                 return 0;
11895
11896         rc = posix_memalign(&buf, page_size, buflen);
11897         if (rc) /* error code is returned directly */
11898                 return -rc;
11899
11900         if (verbose > 1) {
11901                 fprintf(stdout, "Verifying chunk "DEXT" on mirror:",
11902                         PEXT(&chunk->chunk));
11903                 for (i = 0; i < chunk->mirror_count; i++)
11904                         fprintf(stdout, " %u", chunk->mirror_id[i]);
11905                 fprintf(stdout, "\n");
11906         }
11907
11908         bytes_done = 0;
11909         count = MIN(chunk->chunk.e_end, file_size) - chunk->chunk.e_start;
11910         pos = chunk->chunk.e_start;
11911         while (bytes_done < count) {
11912                 /* compute initial CRC-32 checksum */
11913                 crc = crc32(0L, Z_NULL, 0);
11914                 memset(crc_array, 0, sizeof(crc_array));
11915
11916                 bytes_read = 0;
11917                 for (i = 0; i < chunk->mirror_count; i++) {
11918                         bytes_read = llapi_mirror_read(fd, chunk->mirror_id[i],
11919                                                        buf, buflen, pos);
11920                         if (bytes_read < 0) {
11921                                 rc = bytes_read;
11922                                 fprintf(stderr,
11923                                         "%s: failed to read data from mirror %u: %s.\n",
11924                                         progname, chunk->mirror_id[i],
11925                                         strerror(-rc));
11926                                 goto error;
11927                         }
11928
11929                         /* compute new CRC-32 checksum */
11930                         crc_array[i] = crc32(crc, buf, bytes_read);
11931                 }
11932
11933                 if (verbose)
11934                         print_checksums(chunk, crc_array, pos, buflen);
11935
11936                 /* compare CRC-32 checksum values */
11937                 for (i = 1; i < chunk->mirror_count; i++) {
11938                         if (crc_array[i] != crc_array[0]) {
11939                                 rc = -EINVAL;
11940
11941                                 fprintf(stderr,
11942                                         "%s: chunk "DEXT" has different checksum value on mirror %u and mirror %u.\n",
11943                                         progname, PEXT(&chunk->chunk),
11944                                         chunk->mirror_id[0],
11945                                         chunk->mirror_id[i]);
11946                         }
11947                 }
11948
11949                 pos += bytes_read;
11950                 bytes_done += bytes_read;
11951         }
11952
11953         if (verbose > 1 && rc == 0) {
11954                 fprintf(stdout, "Verifying chunk "DEXT" on mirror:",
11955                         PEXT(&chunk->chunk));
11956                 for (i = 0; i < chunk->mirror_count; i++)
11957                         fprintf(stdout, " %u", chunk->mirror_id[i]);
11958                 fprintf(stdout, " PASS\n\n");
11959         }
11960
11961 error:
11962         free(buf);
11963         return rc;
11964 }
11965
11966 /**
11967  * lfs_mirror_verify_file() - Verify a mirrored file.
11968  * @fname:      Mirrored file name.
11969  * @mirror_ids: Specified mirror ids to be verified.
11970  * @ids_nr:     Number of specified mirror ids.
11971  * @verbose:    Verbose mode.
11972  *
11973  * This function verifies that each SYNC mirror of a mirrored file
11974  * specified by @fname contains exactly the same data.
11975  *
11976  * If @mirror_ids is specified, then the function will verify the
11977  * mirrors specified by @mirror_ids contain exactly the same data.
11978  *
11979  * If @verbose is specified, then the function will print where the
11980  * differences are if the data do not match. Otherwise, it will
11981  * just return an error in that case.
11982  *
11983  * Return: 0 on success or a negative error code on failure.
11984  */
11985 static inline
11986 int lfs_mirror_verify_file(const char *fname, __u16 *mirror_ids, int ids_nr,
11987                            int verbose)
11988 {
11989         struct verify_chunk chunks_array[1024] = { };
11990         struct llapi_layout *layout = NULL;
11991         struct stat stbuf;
11992         uint32_t flr_state;
11993         int fd;
11994         int chunk_count = 0;
11995         int idx = 0;
11996         int rc = 0;
11997         int rc1 = 0;
11998         int rc2 = 0;
11999
12000         if (stat(fname, &stbuf) < 0) {
12001                 fprintf(stderr, "%s: cannot stat file '%s': %s.\n",
12002                         progname, fname, strerror(errno));
12003                 rc = -errno;
12004                 goto error;
12005         }
12006
12007         if (!S_ISREG(stbuf.st_mode)) {
12008                 fprintf(stderr, "%s: '%s' is not a regular file.\n",
12009                         progname, fname);
12010                 rc = -EINVAL;
12011                 goto error;
12012         }
12013
12014         if (stbuf.st_size == 0) {
12015                 if (verbose)
12016                         fprintf(stdout, "%s: '%s' file size is 0.\n",
12017                                 progname, fname);
12018                 rc = 0;
12019                 goto error;
12020         }
12021
12022         /* Allow mirror verify even without the key on encrypted files */
12023         fd = open(fname, O_DIRECT | O_RDONLY | O_FILE_ENC);
12024         if (fd < 0) {
12025                 fprintf(stderr, "%s: cannot open '%s': %s.\n",
12026                         progname, fname, strerror(errno));
12027                 rc = -errno;
12028                 goto error;
12029         }
12030
12031         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
12032         if (rc < 0) {
12033                 fprintf(stderr, "%s: '%s' llapi_lease_acquire failed: %s.\n",
12034                         progname, fname, strerror(errno));
12035                 goto close_fd;
12036         }
12037
12038         layout = llapi_layout_get_by_fd(fd, 0);
12039         if (!layout) {
12040                 fprintf(stderr, "%s: '%s' llapi_layout_get_by_fd failed: %s.\n",
12041                         progname, fname, strerror(errno));
12042                 rc = -errno;
12043                 llapi_lease_release(fd);
12044                 goto close_fd;
12045         }
12046
12047         rc = llapi_layout_flags_get(layout, &flr_state);
12048         if (rc < 0) {
12049                 fprintf(stderr, "%s: '%s' llapi_layout_flags_get failed: %s.\n",
12050                         progname, fname, strerror(errno));
12051                 rc = -errno;
12052                 goto free_layout;
12053         }
12054
12055         flr_state &= LCM_FL_FLR_MASK;
12056         switch (flr_state) {
12057         case LCM_FL_NONE:
12058                 rc = -EINVAL;
12059                 fprintf(stderr, "%s: '%s' file state error: %s.\n",
12060                         progname, fname, llapi_layout_flags_string(flr_state));
12061                 goto free_layout;
12062         default:
12063                 break;
12064         }
12065
12066         /* find out mirror chunks to be verified */
12067         chunk_count = lfs_mirror_prepare_chunk(layout, chunks_array,
12068                                                ARRAY_SIZE(chunks_array));
12069         if (chunk_count < 0) {
12070                 rc = chunk_count;
12071                 goto free_layout;
12072         }
12073
12074         if (ids_nr > 0)
12075                 /* filter specified mirror ids */
12076                 filter_mirror_id(chunks_array, chunk_count, mirror_ids, ids_nr);
12077
12078         if (verbose > 2)
12079                 print_chunks(fname, chunks_array, chunk_count);
12080
12081         for (idx = 0; idx < chunk_count; idx++) {
12082                 if (chunks_array[idx].chunk.e_start >= stbuf.st_size) {
12083                         if (verbose)
12084                                 fprintf(stdout,
12085                                         "%s: '%s' chunk "DEXT" exceeds file size %#llx: skipped\n",
12086                                         progname, fname,
12087                                         PEXT(&chunks_array[idx].chunk),
12088                                         (unsigned long long)stbuf.st_size);
12089                         break;
12090                 }
12091
12092                 if (chunks_array[idx].mirror_count == 0) {
12093                         fprintf(stderr,
12094                                 "%s: '%s' chunk "DEXT" is invalid in all of the mirrors: ",
12095                                 progname, fname,
12096                                 PEXT(&chunks_array[idx].chunk));
12097                         if (verbose) {
12098                                 fprintf(stderr, "skipped\n");
12099                                 continue;
12100                         }
12101                         rc = -EINVAL;
12102                         fprintf(stderr, "failed\n");
12103                         goto free_layout;
12104                 }
12105
12106                 if (chunks_array[idx].mirror_count == 1) {
12107                         if (verbose)
12108                                 fprintf(stdout,
12109                                         "%s: '%s' chunk "DEXT" is only valid in mirror %u: skipped\n",
12110                                         progname, fname,
12111                                         PEXT(&chunks_array[idx].chunk),
12112                                         chunks_array[idx].mirror_id[0]);
12113                         continue;
12114                 }
12115
12116                 rc = llapi_lease_check(fd);
12117                 if (rc != LL_LEASE_RDLCK) {
12118                         fprintf(stderr, "%s: '%s' lost lease lock.\n",
12119                                 progname, fname);
12120                         goto free_layout;
12121                 }
12122
12123                 /* verify one chunk */
12124                 rc1 = lfs_mirror_verify_chunk(fd, stbuf.st_size,
12125                                               &chunks_array[idx], verbose);
12126                 if (rc1 < 0) {
12127                         rc2 = rc1;
12128                         if (!verbose) {
12129                                 rc = rc1;
12130                                 goto free_layout;
12131                         }
12132                 }
12133         }
12134
12135         if (rc2 < 0)
12136                 rc = rc2;
12137
12138 free_layout:
12139         llapi_layout_free(layout);
12140         llapi_lease_release(fd);
12141 close_fd:
12142         close(fd);
12143 error:
12144         return rc;
12145 }
12146
12147 /**
12148  * lfs_mirror_verify() - Parse and execute lfs mirror verify command.
12149  * @argc: The count of lfs mirror verify command line arguments.
12150  * @argv: Array of strings for lfs mirror verify command line arguments.
12151  *
12152  * This function parses lfs mirror verify command and verifies the
12153  * specified mirrored file(s).
12154  *
12155  * Return: 0 on success or a negative error code on failure.
12156  */
12157 static inline int lfs_mirror_verify(int argc, char **argv)
12158 {
12159         __u16 mirror_ids[LUSTRE_MIRROR_COUNT_MAX] = { 0 };
12160         int ids_nr = 0;
12161         int c;
12162         int verbose = 0;
12163         int rc = 0;
12164         int rc1 = 0;
12165         char cmd[PATH_MAX];
12166
12167         struct option long_opts[] = {
12168         { .val = 'h',   .name = "help",         .has_arg = no_argument },
12169         { .val = 'o',   .name = "only",         .has_arg = required_argument },
12170         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
12171         { .name = NULL } };
12172
12173         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
12174         progname = cmd;
12175         while ((c = getopt_long(argc, argv, "ho:v", long_opts, NULL)) >= 0) {
12176                 switch (c) {
12177                 case 'o':
12178                         rc = parse_mirror_ids(mirror_ids,
12179                                               ARRAY_SIZE(mirror_ids),
12180                                               optarg);
12181                         if (rc < 0) {
12182                                 fprintf(stderr,
12183                                         "%s: bad mirror ids '%s'.\n",
12184                                         progname, optarg);
12185                                 goto error;
12186                         }
12187                         ids_nr = rc;
12188                         if (ids_nr < 2) {
12189                                 fprintf(stderr,
12190                                         "%s: at least 2 mirror ids needed with '--only' option.\n",
12191                                         progname);
12192                                 rc = CMD_HELP;
12193                                 goto error;
12194                         }
12195                         break;
12196                 case 'v':
12197                         verbose++;
12198                         break;
12199                 default:
12200                         fprintf(stderr, "%s: unrecognized option '%s'\n",
12201                                 progname, argv[optind - 1]);
12202                         fallthrough;
12203                 case 'h':
12204                         rc = CMD_HELP;
12205                         goto error;
12206                 }
12207         }
12208
12209         if (argc == optind) {
12210                 fprintf(stderr, "%s: no file name given.\n", progname);
12211                 rc = CMD_HELP;
12212                 goto error;
12213         }
12214
12215         if (ids_nr > 0 && argc > optind + 1) {
12216                 fprintf(stderr,
12217                         "%s: '--only' cannot be used upon multiple files.\n",
12218                         progname);
12219                 rc = CMD_HELP;
12220                 goto error;
12221         }
12222
12223         if (ids_nr > 0) {
12224                 rc = verify_mirror_ids(argv[optind], mirror_ids, ids_nr);
12225                 if (rc < 0)
12226                         goto error;
12227         }
12228
12229         rc = 0;
12230         for (; optind < argc; optind++) {
12231                 rc1 = lfs_mirror_verify_file(argv[optind], mirror_ids, ids_nr,
12232                                              verbose);
12233                 if (rc1 < 0)
12234                         rc = rc1;
12235         }
12236 error:
12237         return rc;
12238 }
12239
12240 /**
12241  * lfs_mirror() - Parse and execute lfs mirror commands.
12242  * @argc: The count of lfs mirror command line arguments.
12243  * @argv: Array of strings for lfs mirror command line arguments.
12244  *
12245  * This function parses lfs mirror commands and performs the
12246  * corresponding functions specified in mirror_cmdlist[].
12247  *
12248  * Return: 0 on success or an error code on failure.
12249  */
12250 static int lfs_mirror(int argc, char **argv)
12251 {
12252         char cmd[PATH_MAX];
12253         int rc = 0;
12254
12255         setlinebuf(stdout);
12256
12257         Parser_init("lfs-mirror > ", mirror_cmdlist);
12258
12259         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
12260         progname = cmd;
12261         program_invocation_short_name = cmd;
12262         if (argc > 1)
12263                 rc = Parser_execarg(argc - 1, argv + 1, mirror_cmdlist);
12264         else
12265                 rc = Parser_commands();
12266
12267         return rc < 0 ? -rc : rc;
12268 }
12269
12270 static void lustre_som_swab(struct lustre_som_attrs *attrs)
12271 {
12272 #if __BYTE_ORDER == __BIG_ENDIAN
12273         __swab16s(&attrs->lsa_valid);
12274         __swab64s(&attrs->lsa_size);
12275         __swab64s(&attrs->lsa_blocks);
12276 #endif
12277 }
12278
12279 enum lfs_som_type {
12280         LFS_SOM_SIZE = 0x1,
12281         LFS_SOM_BLOCKS = 0x2,
12282         LFS_SOM_FLAGS = 0x4,
12283         LFS_SOM_ATTR_ALL = LFS_SOM_SIZE | LFS_SOM_BLOCKS |
12284                            LFS_SOM_FLAGS,
12285 };
12286
12287 static int lfs_getsom(int argc, char **argv)
12288 {
12289         const char *path;
12290         struct lustre_som_attrs *attrs;
12291         char buf[sizeof(*attrs) + 64];
12292         enum lfs_som_type type = LFS_SOM_ATTR_ALL;
12293         int rc = 0, c;
12294
12295         while ((c = getopt(argc, argv, "bfhs")) != -1) {
12296                 switch (c) {
12297                 case 'b':
12298                         type = LFS_SOM_BLOCKS;
12299                         break;
12300                 case 'f':
12301                         type = LFS_SOM_FLAGS;
12302                         break;
12303                 case 's':
12304                         type = LFS_SOM_SIZE;
12305                         break;
12306                 default:
12307                         fprintf(stderr, "%s: unrecognized option '%s'\n",
12308                                 progname, argv[optind - 1]);
12309                         fallthrough;
12310                 case 'h':
12311                         return CMD_HELP;
12312                 }
12313         }
12314
12315         argc -= optind;
12316         argv += optind;
12317
12318         if (argc != 1) {
12319                 fprintf(stderr, "%s: %s\n",
12320                         progname, argc == 0 ? "miss file target" :
12321                         "input more than 2 files");
12322                 return CMD_HELP;
12323         }
12324
12325         path = argv[0];
12326         attrs = (void *)buf;
12327         rc = lgetxattr(path, "trusted.som", attrs, sizeof(buf));
12328         if (rc < 0) {
12329                 rc = -errno;
12330                 fprintf(stderr, "%s failed to get som xattr: %s (%d)\n",
12331                         argv[0], strerror(errno), errno);
12332                 return rc;
12333         }
12334
12335         lustre_som_swab(attrs);
12336
12337         switch (type) {
12338         case LFS_SOM_ATTR_ALL:
12339                 printf("file: %s size: %llu blocks: %llu flags: %x\n",
12340                        path, (unsigned long long)attrs->lsa_size,
12341                        (unsigned long long)attrs->lsa_blocks,
12342                        attrs->lsa_valid);
12343                 break;
12344         case LFS_SOM_SIZE:
12345                 printf("%llu\n", (unsigned long long)attrs->lsa_size);
12346                 break;
12347         case LFS_SOM_BLOCKS:
12348                 printf("%llu\n", (unsigned long long)attrs->lsa_blocks);
12349                 break;
12350         case LFS_SOM_FLAGS:
12351                 printf("%x\n", attrs->lsa_valid);
12352                 break;
12353         default:
12354                 fprintf(stderr, "%s: unknown option\n", progname);
12355                 return CMD_HELP;
12356         }
12357
12358         return 0;
12359 }
12360
12361 /**
12362  * lfs_mirror_list_commands() - List lfs mirror commands.
12363  * @argc: The count of command line arguments.
12364  * @argv: Array of strings for command line arguments.
12365  *
12366  * This function lists lfs mirror commands defined in mirror_cmdlist[].
12367  *
12368  * Return: 0 on success.
12369  */
12370 static int lfs_mirror_list_commands(int argc, char **argv)
12371 {
12372         char buffer[81] = "";
12373
12374         Parser_list_commands(mirror_cmdlist, buffer, sizeof(buffer),
12375                              NULL, 0, 4);
12376
12377         return 0;
12378 }
12379
12380 static int lfs_pcc_attach(int argc, char **argv)
12381 {
12382         struct option long_opts[] = {
12383         { .val = 'h',   .name = "help", .has_arg = no_argument },
12384         { .val = 'i',   .name = "id",   .has_arg = required_argument },
12385         { .name = NULL } };
12386         int c;
12387         int rc = 0;
12388         __u32 archive_id = 0;
12389         const char *path;
12390         char *end;
12391         char fullpath[PATH_MAX];
12392         enum lu_pcc_type type = LU_PCC_READWRITE;
12393
12394         optind = 0;
12395         while ((c = getopt_long(argc, argv, "hi:",
12396                                 long_opts, NULL)) != -1) {
12397                 switch (c) {
12398                 case 'i':
12399                         errno = 0;
12400                         archive_id = strtoul(optarg, &end, 0);
12401                         if (errno != 0 || *end != '\0' ||
12402                             archive_id == 0 || archive_id > UINT32_MAX) {
12403                                 fprintf(stderr,
12404                                         "error: %s: bad archive ID '%s'\n",
12405                                         progname, optarg);
12406                                 return CMD_HELP;
12407                         }
12408                         break;
12409                 default:
12410                         fprintf(stderr, "%s: unrecognized option '%s'\n",
12411                                 progname, argv[optind - 1]);
12412                         fallthrough;
12413                 case 'h':
12414                         return CMD_HELP;
12415                 }
12416         }
12417
12418         if (archive_id == 0) {
12419                 fprintf(stderr, "%s: must specify attach ID\n", argv[0]);
12420                 return CMD_HELP;
12421         }
12422
12423         if (argc <= optind) {
12424                 fprintf(stderr, "%s: must specify one or more file names\n",
12425                         argv[0]);
12426                 return CMD_HELP;
12427         }
12428
12429         while (optind < argc) {
12430                 int rc2;
12431
12432                 path = argv[optind++];
12433                 if (!realpath(path, fullpath)) {
12434                         fprintf(stderr, "%s: could not find path '%s': %s\n",
12435                                 argv[0], path, strerror(errno));
12436                         if (rc == 0)
12437                                 rc = -EINVAL;
12438                         continue;
12439                 }
12440
12441                 rc2 = llapi_pcc_attach(fullpath, archive_id, type);
12442                 if (rc2 < 0) {
12443                         fprintf(stderr,
12444                                 "%s: cannot attach '%s' to PCC with archive ID '%u': %s\n",
12445                                 argv[0], path, archive_id, strerror(-rc2));
12446                         if (rc == 0)
12447                                 rc = rc2;
12448                 }
12449         }
12450         return rc;
12451 }
12452
12453 static int lfs_pcc_attach_fid(int argc, char **argv)
12454 {
12455         struct option long_opts[] = {
12456         { .val = 'h',   .name = "help", .has_arg = no_argument },
12457         { .val = 'i',   .name = "id",   .has_arg = required_argument },
12458         { .val = 'm',   .name = "mnt",  .has_arg = required_argument },
12459         { .name = NULL } };
12460         int c;
12461         int rc = 0;
12462         __u32 archive_id = 0;
12463         char *end;
12464         const char *mntpath = NULL;
12465         const char *fidstr;
12466         enum lu_pcc_type type = LU_PCC_READWRITE;
12467
12468         optind = 0;
12469         while ((c = getopt_long(argc, argv, "hi:m:",
12470                                 long_opts, NULL)) != -1) {
12471                 switch (c) {
12472                 case 'i':
12473                         errno = 0;
12474                         archive_id = strtoul(optarg, &end, 0);
12475                         if (errno != 0 || *end != '\0' ||
12476                             archive_id > UINT32_MAX) {
12477                                 fprintf(stderr,
12478                                         "error: %s: bad archive ID '%s'\n",
12479                                         argv[0], optarg);
12480                                 return CMD_HELP;
12481                         }
12482                         break;
12483                 case 'm':
12484                         mntpath = optarg;
12485                         break;
12486                 default:
12487                         fprintf(stderr, "%s: unrecognized option '%s'\n",
12488                                 progname, argv[optind - 1]);
12489                         fallthrough;
12490                 case 'h':
12491                         return CMD_HELP;
12492                 }
12493         }
12494
12495         if (archive_id == 0) {
12496                 fprintf(stderr, "%s: must specify an archive ID\n", argv[0]);
12497                 return CMD_HELP;
12498         }
12499
12500         if (!mntpath) {
12501                 fprintf(stderr, "%s: must specify Lustre mount point\n",
12502                         argv[0]);
12503                 return CMD_HELP;
12504         }
12505
12506         if (argc <= optind) {
12507                 fprintf(stderr, "%s: must specify one or more fids\n", argv[0]);
12508                 return CMD_HELP;
12509         }
12510
12511         while (optind < argc) {
12512                 int rc2;
12513
12514                 fidstr = argv[optind++];
12515
12516                 rc2 = llapi_pcc_attach_fid_str(mntpath, fidstr,
12517                                                archive_id, type);
12518                 if (rc2 < 0) {
12519                         fprintf(stderr,
12520                                 "%s: cannot attach '%s' on '%s' to PCC with archive ID '%u': %s\n",
12521                                 argv[0], fidstr, mntpath, archive_id,
12522                                 strerror(rc2));
12523                 }
12524                 if (rc == 0 && rc2 < 0)
12525                         rc = rc2;
12526         }
12527         return rc;
12528 }
12529
12530 static int lfs_pcc_detach(int argc, char **argv)
12531 {
12532         struct option long_opts[] = {
12533         { .val = 'h',   .name = "help", .has_arg = no_argument },
12534         { .val = 'k',   .name = "keep", .has_arg = no_argument },
12535         { .name = NULL } };
12536         int c;
12537         int rc = 0;
12538         const char *path;
12539         char fullpath[PATH_MAX];
12540         __u32 detach_opt = PCC_DETACH_OPT_UNCACHE;
12541
12542         optind = 0;
12543         while ((c = getopt_long(argc, argv, "hk",
12544                                 long_opts, NULL)) != -1) {
12545                 switch (c) {
12546                 case 'k':
12547                         detach_opt = PCC_DETACH_OPT_NONE;
12548                         break;
12549                 default:
12550                         fprintf(stderr, "%s: unrecognized option '%s'\n",
12551                                 progname, argv[optind - 1]);
12552                         fallthrough;
12553                 case 'h':
12554                         return CMD_HELP;
12555                 }
12556         }
12557
12558         while (optind < argc) {
12559                 int rc2;
12560
12561                 path = argv[optind++];
12562                 if (!realpath(path, fullpath)) {
12563                         fprintf(stderr, "%s: could not find path '%s': %s\n",
12564                                 argv[0], path, strerror(errno));
12565                         if (rc == 0)
12566                                 rc = -EINVAL;
12567                         continue;
12568                 }
12569
12570                 rc2 = llapi_pcc_detach_file(fullpath, detach_opt);
12571                 if (rc2 < 0) {
12572                         rc2 = -errno;
12573                         fprintf(stderr,
12574                                 "%s: cannot detach '%s' from PCC: %s\n",
12575                                 argv[0], path, strerror(errno));
12576                         if (rc == 0)
12577                                 rc = rc2;
12578                 }
12579         }
12580         return rc;
12581 }
12582
12583 static int lfs_pcc_detach_fid(int argc, char **argv)
12584 {
12585         struct option long_opts[] = {
12586         { .val = 'h',   .name = "help", .has_arg = no_argument },
12587         { .val = 'k',   .name = "keep", .has_arg = no_argument },
12588         { .name = NULL } };
12589         int c;
12590         int rc = 0;
12591         const char *fid;
12592         const char *mntpath;
12593         __u32 detach_opt = PCC_DETACH_OPT_UNCACHE;
12594
12595         optind = 0;
12596         while ((c = getopt_long(argc, argv, "hk",
12597                                 long_opts, NULL)) != -1) {
12598                 switch (c) {
12599                 case 'k':
12600                         detach_opt = PCC_DETACH_OPT_NONE;
12601                         break;
12602                 default:
12603                         fprintf(stderr, "%s: unrecognized option '%s'\n",
12604                                 progname, argv[optind - 1]);
12605                         fallthrough;
12606                 case 'h':
12607                         return CMD_HELP;
12608                 }
12609         }
12610
12611         mntpath = argv[optind++];
12612
12613         while (optind < argc) {
12614                 int rc2;
12615
12616                 fid = argv[optind++];
12617
12618                 rc2 = llapi_pcc_detach_fid_str(mntpath, fid, detach_opt);
12619                 if (rc2 < 0) {
12620                         fprintf(stderr,
12621                                 "%s: cannot detach '%s' on '%s' from PCC: %s\n",
12622                                 argv[0], fid, mntpath, strerror(-rc2));
12623                         if (rc == 0)
12624                                 rc = rc2;
12625                 }
12626         }
12627         return rc;
12628 }
12629
12630 static int lfs_pcc_state(int argc, char **argv)
12631 {
12632         int rc = 0;
12633         const char *path;
12634         char fullpath[PATH_MAX];
12635         struct lu_pcc_state state;
12636
12637         optind = 1;
12638
12639         if (argc <= 1) {
12640                 fprintf(stderr, "%s: must specify one or more file names\n",
12641                         progname);
12642                 return CMD_HELP;
12643         }
12644
12645         while (optind < argc) {
12646                 int rc2;
12647
12648                 path = argv[optind++];
12649                 if (!realpath(path, fullpath)) {
12650                         fprintf(stderr, "%s: could not find path '%s': %s\n",
12651                                 argv[0], path, strerror(errno));
12652                         if (rc == 0)
12653                                 rc = -EINVAL;
12654                         continue;
12655                 }
12656
12657                 rc2 = llapi_pcc_state_get(fullpath, &state);
12658                 if (rc2 < 0) {
12659                         if (rc == 0)
12660                                 rc = rc2;
12661                         fprintf(stderr,
12662                                 "%s: cannot get PCC state of '%s': %s\n",
12663                                 argv[0], path, strerror(-rc2));
12664                         continue;
12665                 }
12666
12667                 printf("file: %s", path);
12668                 printf(", type: %s", pcc_type2string(state.pccs_type));
12669                 if (state.pccs_type == LU_PCC_NONE &&
12670                     state.pccs_open_count == 0) {
12671                         printf("\n");
12672                         continue;
12673                 }
12674
12675                 printf(", PCC file: %s", state.pccs_path);
12676                 printf(", user number: %u", state.pccs_open_count);
12677                 printf(", flags: %x", state.pccs_flags);
12678                 printf("\n");
12679         }
12680         return rc;
12681 }
12682
12683 /**
12684  * lfs_pcc_list_commands() - List lfs pcc commands.
12685  * @argc: The count of command line arguments.
12686  * @argv: Array of strings for command line arguments.
12687  *
12688  * This function lists lfs pcc commands defined in pcc_cmdlist[].
12689  *
12690  * Return: 0 on success.
12691  */
12692 static int lfs_pcc_list_commands(int argc, char **argv)
12693 {
12694         char buffer[81] = "";
12695
12696         Parser_list_commands(pcc_cmdlist, buffer, sizeof(buffer),
12697                              NULL, 0, 4);
12698
12699         return 0;
12700 }
12701
12702 /**
12703  * lfs_pcc() - Parse and execute lfs pcc commands.
12704  * @argc: The count of lfs pcc command line arguments.
12705  * @argv: Array of strings for lfs pcc command line arguments.
12706  *
12707  * This function parses lfs pcc commands and performs the
12708  * corresponding functions specified in pcc_cmdlist[].
12709  *
12710  * Return: 0 on success or an error code on failure.
12711  */
12712 static int lfs_pcc(int argc, char **argv)
12713 {
12714         char cmd[PATH_MAX];
12715         int rc = 0;
12716
12717         setlinebuf(stdout);
12718
12719         Parser_init("lfs-pcc > ", pcc_cmdlist);
12720
12721         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
12722         progname = cmd;
12723         program_invocation_short_name = cmd;
12724         if (argc > 1)
12725                 rc = Parser_execarg(argc - 1, argv + 1, pcc_cmdlist);
12726         else
12727                 rc = Parser_commands();
12728
12729         return rc < 0 ? -rc : rc;
12730 }
12731
12732 static int lfs_list_commands(int argc, char **argv)
12733 {
12734         char buffer[81] = ""; /* 80 printable chars + terminating NUL */
12735
12736         Parser_list_commands(cmdlist, buffer, sizeof(buffer), NULL, 0, 4);
12737
12738         return 0;
12739 }
12740
12741 int main(int argc, char **argv)
12742 {
12743         int rc;
12744
12745         /* Ensure that liblustreapi constructor has run */
12746         if (!llapi_liblustreapi_initialized())
12747                 fprintf(stderr, "liblustreapi was not properly initialized\n");
12748
12749         setlinebuf(stdout);
12750         opterr = 0;
12751
12752         Parser_init("lfs > ", cmdlist);
12753
12754         progname = program_invocation_short_name; /* Used in error messages */
12755         if (argc > 1) {
12756                 llapi_set_command_name(argv[1]);
12757                 rc = Parser_execarg(argc - 1, argv + 1, cmdlist);
12758                 llapi_clear_command_name();
12759         } else {
12760                 rc = Parser_commands();
12761         }
12762
12763         return rc < 0 ? -rc : rc;
12764 }
12765
12766 #ifdef _LUSTRE_IDL_H_
12767 /* Everything we need here should be included by lustreapi.h. */
12768 # error "lfs should not depend on lustre_idl.h"
12769 #endif /* _LUSTRE_IDL_H_ */