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