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