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