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