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