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