Whamcloud - gitweb
LU-15971 llite: implicit default LMV inherit
[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 #ifndef NSEC_PER_SEC
82 # define NSEC_PER_SEC 1000000000UL
83 #endif
84 #define ONE_MB 0x100000
85
86 /* all functions */
87 static int lfs_find(int argc, char **argv);
88 static int lfs_getstripe(int argc, char **argv);
89 static int lfs_getdirstripe(int argc, char **argv);
90 static int lfs_setdirstripe(int argc, char **argv);
91 static int lfs_rmentry(int argc, char **argv);
92 static int lfs_unlink_foreign(int argc, char **argv);
93 static int lfs_osts(int argc, char **argv);
94 static int lfs_mdts(int argc, char **argv);
95 static int lfs_df(int argc, char **argv);
96 static int lfs_getname(int argc, char **argv);
97 static int lfs_check(int argc, char **argv);
98 #ifdef HAVE_SYS_QUOTA_H
99 static int lfs_setquota(int argc, char **argv);
100 static int lfs_quota(int argc, char **argv);
101 static int lfs_project(int argc, char **argv);
102 #endif
103 static int lfs_flushctx(int argc, char **argv);
104 static int lfs_poollist(int argc, char **argv);
105 static int lfs_changelog(int argc, char **argv);
106 static int lfs_changelog_clear(int argc, char **argv);
107 static int lfs_fid2path(int argc, char **argv);
108 static int lfs_path2fid(int argc, char **argv);
109 static int lfs_rmfid(int argc, char **argv);
110 static int lfs_data_version(int argc, char **argv);
111 static int lfs_hsm_state(int argc, char **argv);
112 static int lfs_hsm_set(int argc, char **argv);
113 static int lfs_hsm_clear(int argc, char **argv);
114 static int lfs_hsm_action(int argc, char **argv);
115 static int lfs_hsm_archive(int argc, char **argv);
116 static int lfs_hsm_restore(int argc, char **argv);
117 static int lfs_hsm_release(int argc, char **argv);
118 static int lfs_hsm_remove(int argc, char **argv);
119 static int lfs_hsm_cancel(int argc, char **argv);
120 static int lfs_swap_layouts(int argc, char **argv);
121 static int lfs_mv(int argc, char **argv);
122 static int lfs_ladvise(int argc, char **argv);
123 static int lfs_getsom(int argc, char **argv);
124 static int lfs_heat_get(int argc, char **argv);
125 static int lfs_heat_set(int argc, char **argv);
126 static int lfs_mirror(int argc, char **argv);
127 static inline int lfs_mirror_resync(int argc, char **argv);
128 static inline int lfs_mirror_verify(int argc, char **argv);
129 static inline int lfs_mirror_read(int argc, char **argv);
130 static inline int lfs_mirror_write(int argc, char **argv);
131 static inline int lfs_mirror_copy(int argc, char **argv);
132 static int lfs_pcc_attach(int argc, char **argv);
133 static int lfs_pcc_attach_fid(int argc, char **argv);
134 static int lfs_pcc_detach(int argc, char **argv);
135 static int lfs_pcc_detach_fid(int argc, char **argv);
136 static int lfs_pcc_state(int argc, char **argv);
137 static int lfs_pcc(int argc, char **argv);
138
139 enum stats_flag {
140         STATS_ON,
141         STATS_OFF,
142 };
143
144 static int lfs_migrate_to_dom(int fd_src, int fd_dst, char *name,
145                               __u64 migration_flags,
146                               unsigned long long bandwidth_bytes_sec,
147                               enum stats_flag stats_flag,
148                               long stats_interval_sec);
149
150 struct pool_to_id_cbdata {
151         const char *pool;
152         __u32 id;
153 };
154
155 static int find_comp_id_by_pool(struct llapi_layout *layout, void *cbdata);
156 static int find_mirror_id_by_pool(struct llapi_layout *layout, void *cbdata);
157
158 enum setstripe_origin {
159         SO_SETSTRIPE,
160         SO_MIGRATE,
161         SO_MIGRATE_MDT,
162         SO_MIRROR_CREATE,
163         SO_MIRROR_EXTEND,
164         SO_MIRROR_SPLIT,
165         SO_MIRROR_DELETE,
166 };
167
168 static int lfs_setstripe_internal(int argc, char **argv,
169                                   enum setstripe_origin opc);
170
171 static inline int lfs_setstripe(int argc, char **argv)
172 {
173         return lfs_setstripe_internal(argc, argv, SO_SETSTRIPE);
174 }
175
176 static inline int lfs_setstripe_migrate(int argc, char **argv)
177 {
178         return lfs_setstripe_internal(argc, argv, SO_MIGRATE);
179 }
180
181 static inline int lfs_mirror_create(int argc, char **argv)
182 {
183         return lfs_setstripe_internal(argc, argv, SO_MIRROR_CREATE);
184 }
185
186 static inline int lfs_mirror_extend(int argc, char **argv)
187 {
188         return lfs_setstripe_internal(argc, argv, SO_MIRROR_EXTEND);
189 }
190
191 static inline int lfs_mirror_split(int argc, char **argv)
192 {
193         return lfs_setstripe_internal(argc, argv, SO_MIRROR_SPLIT);
194 }
195
196 static inline int lfs_mirror_delete(int argc, char **argv)
197 {
198         return lfs_setstripe_internal(argc, argv, SO_MIRROR_DELETE);
199 }
200
201 /* Setstripe and migrate share mostly the same parameters */
202 #define SSM_CMD_COMMON(cmd) \
203         "usage: "cmd" [--component-end|-E COMP_END]\n"                  \
204         "                 [--copy=LUSTRE_SRC]\n"                        \
205         "                 [--extension-size|--ext-size|-z SIZE]\n"      \
206         "                 [--help|-h] [--layout|-L PATTERN]\n"          \
207         "                 [--layout|-L PATTERN]\n"                      \
208         "                 [--mirror-count|-N[MIRROR_COUNT]]\n"          \
209         "                 [--ost|-o OST_INDICES]\n"                     \
210         "                 [--overstripe-count|-C STRIPE_COUNT]\n"       \
211         "                 [--pool|-p POOL_NAME]\n"                      \
212         "                 [--stripe-count|-c STRIPE_COUNT]\n"           \
213         "                 [--stripe-index|-i START_OST_IDX]\n"          \
214         "                 [--stripe-size|-S STRIPE_SIZE]\n"             \
215         "                 [--yaml|-y YAML_TEMPLATE_FILE]\n"
216
217 #define MIRROR_EXTEND_USAGE                                             \
218         "                 {--mirror-count|-N[MIRROR_COUNT]}\n"          \
219         "                 [SETSTRIPE_OPTIONS|-f|--file VICTIM_FILE]\n"  \
220         "                 [--no-verify]\n"
221
222 #define SETSTRIPE_USAGE                                                 \
223         SSM_CMD_COMMON("setstripe")                                     \
224         MIRROR_EXTEND_USAGE                                             \
225         "                 DIRECTORY|FILENAME\n"
226
227 #define MIGRATE_USAGE                                                   \
228         SSM_CMD_COMMON("migrate  ")                                     \
229         "                 [--block|-b] [--non-block|-n]\n"              \
230         "                 [--non-direct|-D] [--verbose|-v]\n"           \
231         "                 FILENAME\n"
232
233 #define SETDIRSTRIPE_USAGE                                              \
234         "               [--mdt-count|-c stripe_count>\n"                \
235         "               [--help|-h] [--mdt-hash|-H mdt_hash]\n"         \
236         "               [--mdt-index|-i mdt_index[,mdt_index,...]\n"    \
237         "               [--default|-D] [--mode|-o mode]\n"              \
238         "               [--max-inherit|-X max_inherit]\n"               \
239         "               [--max-inherit-rr max_inherit_rr] <dir>\n"      \
240         "To create dir with a foreign (free format) layout :\n"         \
241         "setdirstripe|mkdir --foreign[=FOREIGN_TYPE] -x|-xattr STRING " \
242         "               [--mode|-o MODE] [--flags HEX] DIRECTORY\n"
243
244 /**
245  * command_t mirror_cmdlist - lfs mirror commands.
246  */
247 command_t mirror_cmdlist[] = {
248         { .pc_name = "create", .pc_func = lfs_mirror_create,
249           .pc_help = "Create a mirrored file.\n"
250                 "usage: lfs mirror create --mirror-count|-N[MIRROR_COUNT]\n"
251                 "           [SETSTRIPE_OPTIONS] ... FILENAME|DIRECTORY ...\n" },
252         { .pc_name = "delete", .pc_func = lfs_mirror_delete,
253           .pc_help = "Delete a mirror from a file.\n"
254         "usage: lfs mirror delete {--mirror-id <mirror_id> |\n"
255         "\t               --component-id|--comp-id|-I COMP_ID |\n"
256         "\t               -p <pool>} MIRRORED_FILE ...\n"
257         },
258         { .pc_name = "extend", .pc_func = lfs_mirror_extend,
259           .pc_help = "Extend a mirrored file.\n"
260                 "usage: lfs mirror extend "
261                 "{--mirror-count|-N[MIRROR_COUNT]} [--no-verify] "
262                 "[SETSTRIPE_OPTIONS|-f VICTIM_FILE] ... FILENAME ...\n" },
263         { .pc_name = "split", .pc_func = lfs_mirror_split,
264           .pc_help = "Split a mirrored file.\n"
265         "usage: lfs mirror split {--mirror-id MIRROR_ID |\n"
266         "\t             --component-id|-I COMP_ID|-p POOL} [--destroy|-d]\n"
267         "\t             [-f NEW_FILE] MIRRORED_FILE ...\n" },
268         { .pc_name = "read", .pc_func = lfs_mirror_read,
269           .pc_help = "Read the content of a specified mirror of a file.\n"
270                 "usage: lfs mirror read {--mirror-id|-N MIRROR_ID}\n"
271                 "\t\t[--outfile|-o <output_file>] <mirrored_file>\n" },
272         { .pc_name = "write", .pc_func = lfs_mirror_write,
273           .pc_help = "Write to a specified mirror of a file.\n"
274                 "usage: lfs mirror write {--mirror-id|-N MIRROR_ID}\n"
275                 "\t\t[--inputfile|-i <input_file>] <mirrored_file>\n" },
276         { .pc_name = "copy", .pc_func = lfs_mirror_copy,
277           .pc_help = "Copy a specified mirror to other mirror(s) of a file.\n"
278                 "usage: lfs mirror copy {--read-mirror|-i MIRROR_ID0}\n"
279                 "\t\t{--write-mirror|-o MIRROR_ID1[,...]} <mirrored_file>\n" },
280         { .pc_name = "resync", .pc_func = lfs_mirror_resync,
281           .pc_help = "Resynchronizes out-of-sync mirrored file(s).\n"
282                 "usage: lfs mirror resync [--only MIRROR_ID[,...]>]\n"
283                 "\t\t<mirrored_file> [<mirrored_file2>...]\n" },
284         { .pc_name = "verify", .pc_func = lfs_mirror_verify,
285           .pc_help = "Verify mirrored file(s).\n"
286                 "usage: lfs mirror verify [--only MIRROR_ID[,...]]\n"
287                 "\t\t[--verbose|-v] <mirrored_file> [<mirrored_file2> ...]\n" },
288         { .pc_help = NULL }
289 };
290
291 /**
292  * command_t pcc_cmdlist - lfs pcc commands.
293  */
294 command_t pcc_cmdlist[] = {
295         { .pc_name = "attach", .pc_func = lfs_pcc_attach,
296           .pc_help = "Attach given files to the Persistent Client Cache.\n"
297                 "usage: lfs pcc attach <--id|-i NUM> <file> ...\n"
298                 "\t-i: archive id for RW-PCC\n" },
299         { .pc_name = "attach_fid", .pc_func = lfs_pcc_attach_fid,
300           .pc_help = "Attach given files into PCC by FID(s).\n"
301                 "usage: lfs pcc attach_id {--id|-i NUM} {--mnt|-m MOUNTPOINT} FID ...\n"
302                 "\t-i: archive id for RW-PCC\n"
303                 "\t-m: Lustre mount point\n" },
304         { .pc_name = "state", .pc_func = lfs_pcc_state,
305           .pc_help = "Display the PCC state for given files.\n"
306                 "usage: lfs pcc state <file> ...\n" },
307         { .pc_name = "detach", .pc_func = lfs_pcc_detach,
308           .pc_help = "Detach given files from the Persistent Client Cache.\n"
309                 "usage: lfs pcc detach <file> ...\n" },
310         { .pc_name = "detach_fid", .pc_func = lfs_pcc_detach_fid,
311           .pc_help = "Detach given files from PCC by FID(s).\n"
312                 "usage: lfs pcc detach_fid <mntpath> <fid>...\n" },
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] [--hex-idx]\n"
361          "                 [--component-id|-I[=COMP_ID]]\n"
362          "                 [--component-flags[=COMP_FLAGS]]\n"
363          "                 [--component-count]\n"
364          "                 [--extension-size|--ext-size|-z]\n"
365          "                 [--component-start[=[+-]COMP_START]]\n"
366          "                 [--component-end[=[+-]COMP_END]|-E[[+-]comp_end]]\n"
367          "                 [[!] --mirror-index=[+-]INDEX |\n"
368          "                 [!] --mirror-id=[+-]MIRROR_ID] [--mirror-count|-N]\n"
369          "                 [--no-follow]\n"
370          "                 <directory|filename> ..."},
371         {"setdirstripe", lfs_setdirstripe, 0,
372          "Create striped directory on specified MDT, same as mkdir.\n"
373          "May be restricted to root or group users, depending on settings.\n"
374          "usage: setdirstripe [OPTION] <directory>\n"
375          SETDIRSTRIPE_USAGE},
376         {"getdirstripe", lfs_getdirstripe, 0,
377          "To list the layout pattern info for a given directory\n"
378          "or recursively for all directories in a directory tree.\n"
379          "usage: getdirstripe [--mdt-count|-c] [--mdt-index|-m|-i]\n"
380          "                    [--help|-h] [--hex-idx] [--mdt-hash|-H]\n"
381          "                    [--obd|-O UUID] [--recursive|-r] [--raw|-R]\n"
382          "                    [--yaml|-y] [--verbose|-v] [--default|-D]\n"
383          "                    [--max-inherit|-X]\n"
384          "                    [--max-inherit-rr] <dir> ..."},
385         {"mkdir", lfs_setdirstripe, 0,
386          "Create striped directory on specified MDT, same as setdirstripe.\n"
387          "usage: mkdir [OPTION] <directory>\n"
388          SETDIRSTRIPE_USAGE},
389         {"rm_entry", lfs_rmentry, 0,
390          "To remove the name entry of the remote directory. Note: This\n"
391          "command will only delete the name entry, i.e. the remote directory\n"
392          "will become inaccessable after this command. This can only be done\n"
393          "by the administrator\n"
394          "usage: rm_entry <dir>\n"},
395         {"rmentry", lfs_rmentry, 0, "remove a dir entry, same as 'rm_entry'\n"},
396         {"unlink_foreign", lfs_unlink_foreign, 0,
397          "To remove the foreign file/dir.\n"
398          "Note: This is for files/dirs prevented to be removed using\n"
399          "unlink/rmdir, but works also for regular ones\n"
400          "usage: unlink_foreign <foreign_dir/file> [<foreign_dir/file> ...]\n"},
401         {"pool_list", lfs_poollist, 0,
402          "List pools or pool OSTs\n"
403          "usage: pool_list <fsname>[.<pool>] | <pathname>\n"},
404         {"find", lfs_find, 0,
405          "find files matching given attributes recursively in directory tree.\n"
406          "usage: find <directory|filename> ...\n"
407          "     [[!] --atime|-A [+-]N[smhdwy]] [[!] --btime|-B [+-]N[smhdwy]]\n"
408          "     [[!] --ctime|-C [+-]N[smhdwy]] [[!] --mtime|-M [+-]N[smhdwy]]\n"
409          "     [[!] --blocks|-b N] [[!] --component-count [+-]<comp_cnt>]\n"
410          "     [[!] --component-start [+-]N[kMGTPE]]\n"
411          "     [[!] --component-end|-E [+-]N[kMGTPE]]\n"
412          "     [[!] --component-flags {init,stale,prefer,offline,nosync,extension}]\n"
413          "     [[!] --extension-size|--ext-size|-z [+-]N[kMGT]]\n"
414          "     [[!] --foreign[=<foreign_type>]]\n"
415          "     [[!] --gid|-g|--group|-G <gid>|<gname>] [--help|-h]\n"
416          "     [[!] --layout|-L released,raid0,mdt] [--lazy|-l] [[!] --links [+-]n]\n"
417          "     [--maxdepth|-D N] [[!] --mdt-count|-T [+-]<stripes>]\n"
418          "     [[!] --mdt-hash|-H <[^][blm],[^]fnv_1a_64,all_char,crush,...>\n"
419          "     [[!] --mdt-index|--mdt|-m <uuid|index,...>]\n"
420          "     [[!] --mirror-count|-N [+-]<n>]\n"
421          "     [[!] --mirror-state <[^]state>]\n"
422          "     [[!] --name|-n <pattern>] [[!] --newer[XY] <reference>]\n"
423          "     [[!] --ost|-O <uuid|index,...>] [[!] --perm [/-]mode]\n"
424          "     [[!] --pool <pool>] [--print|-P] [--print0|-0] [--printf <format>]\n"
425          "     [[!] --projid <projid>] [[!] --size|-s [+-]N[bkMGTPE]]\n"
426          "     [[!] --stripe-count|-c [+-]<stripes>]\n"
427          "     [[!] --stripe-index|-i <index,...>]\n"
428          "     [[!] --stripe-size|-S [+-]N[kMGT]] [[!] --type|-t <filetype>]\n"
429          "     [[!] --uid|-u|--user|-U <uid>|<uname>]\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) [for specified path only].\n"
437          "usage: check {mgts|osts|mdts|all} [path]"},
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\n"
453          "       setquota {-u|-g|-p} --delete FILESYSTEM\n"},
454         {"quota", lfs_quota, 0, "Display disk usage and limits.\n"
455          "usage: quota [-q] [-v] [-h] [-o OBD_UUID|-i MDT_IDX|-I OST_IDX]\n"
456          "             [{-u|-g|-p} UNAME|UID|GNAME|GID|PROJID]\n"
457          "             [--pool <OST pool name>] <filesystem>\n"
458          "       quota -t <-u|-g|-p> [--pool <OST pool name>] <filesystem>\n"
459          "       quota [-q] [-v] [h] {-U|-G|-P} [--pool <OST pool name>] <filesystem>"},
460         {"project", lfs_project, 0,
461          "Change or list project attribute for specified file or directory.\n"
462          "usage: project [-d|-r] <file|directory...>\n"
463          "         list project ID and flags on file(s) or directories\n"
464          "       project [-p id] [-s] [-r] <file|directory...>\n"
465          "         set project ID and/or inherit flag for specified file(s) or directories\n"
466          "       project -c [-d|-r [-p id] [-0]] <file|directory...>\n"
467          "         check project ID and flags on file(s) or directories, print outliers\n"
468          "       project -C [-d|-r] [-k] <file|directory...>\n"
469          "         clear the project inherit flag and ID on the file or directory\n"
470         },
471 #endif
472         {"flushctx", lfs_flushctx, 0,
473          "Flush security context for current user.\n"
474          "usage: flushctx [-k] [-r] [mountpoint...]"},
475         {"changelog", lfs_changelog, 0,
476          "Show the metadata changes on an MDT."
477          "\nusage: changelog <mdtname> [startrec [endrec]]"},
478         {"changelog_clear", lfs_changelog_clear, 0,
479          "Indicate that old changelog records up to <endrec> are no longer of "
480          "interest to consumer <id>, allowing the system to free up space.\n"
481          "An <endrec> of 0 means all records.\n"
482          "usage: changelog_clear <mdtname> <id> <endrec>"},
483         {"fid2path", lfs_fid2path, 0,
484          "Resolve the full path(s) for given FID(s). For a specific hardlink "
485          "specify link number <linkno>.\n"
486          "usage: fid2path [--print-fid|-f] [--print-link|-c] [--link|-l <linkno>] "
487          "<fsname|root> <fid>..."},
488         {"path2fid", lfs_path2fid, 0, "Display the fid(s) for a given path(s).\n"
489          "usage: path2fid [--parents] <path> ..."},
490         {"rmfid", lfs_rmfid, 0, "Remove file(s) by FID(s)\n"
491          "usage: rmfid <fsname|rootpath> <fid> ..."},
492         {"data_version", lfs_data_version, 0, "Display file data version for "
493          "a given path.\n" "usage: data_version [-n|-r|-w] <path>"},
494         {"hsm_state", lfs_hsm_state, 0, "Display the HSM information (states, "
495          "undergoing actions) for given files.\n usage: hsm_state <file> ..."},
496         {"hsm_set", lfs_hsm_set, 0, "Set HSM user flag on specified files.\n"
497          "usage: hsm_set [--norelease] [--noarchive] [--dirty] [--exists] "
498          "[--archived] [--lost] [--archive-id NUM] <file> ..."},
499         {"hsm_clear", lfs_hsm_clear, 0, "Clear HSM user flag on specified "
500          "files.\n"
501          "usage: hsm_clear [--norelease] [--noarchive] [--dirty] [--exists] "
502          "[--archived] [--lost] <file> ..."},
503         {"hsm_action", lfs_hsm_action, 0, "Display current HSM request for "
504          "given files.\n" "usage: hsm_action <file> ..."},
505         {"hsm_archive", lfs_hsm_archive, 0,
506          "Archive file to external storage.\n"
507          "usage: hsm_archive [--filelist FILELIST] [--data DATA] [--archive NUM] "
508          "<file> ..."},
509         {"hsm_restore", lfs_hsm_restore, 0,
510          "Restore file from external storage.\n"
511          "usage: hsm_restore [--filelist FILELIST] [--data DATA] <file> ..."},
512         {"hsm_release", lfs_hsm_release, 0,
513          "Release files from Lustre.\n"
514          "usage: hsm_release [--filelist FILELIST] [--data DATA] <file> ..."},
515         {"hsm_remove", lfs_hsm_remove, 0,
516          "Remove file copy from external storage.\n"
517          "usage: hsm_remove [--filelist FILELIST] [--data DATA] "
518          "[--archive NUM]\n"
519          "                  (FILE [FILE ...] | "
520          "--mntpath MOUNTPATH FID [FID ...])\n"
521          "\n"
522          "Note: To remove an archived copy of a file already deleted from a "
523          "Lustre FS, the\n"
524          "--mntpath option and a list of FIDs must be specified"
525         },
526         {"hsm_cancel", lfs_hsm_cancel, 0,
527          "Cancel requests related to specified files.\n"
528          "usage: hsm_cancel [--filelist FILELIST] [--data DATA] <file> ..."},
529         {"swap_layouts", lfs_swap_layouts, 0, "Swap layouts between 2 files.\n"
530          "usage: swap_layouts <path1> <path2>"},
531         {"migrate", lfs_setstripe_migrate, 0,
532          "migrate directories and their inodes between MDTs.\n"
533          "usage: migrate [--mdt-count|-c STRIPE_COUNT] [--directory|-d]\n"
534          "               [--mdt-hash|-H HASH_TYPE]\n"
535          "               [--mdt-index|-m START_MDT_INDEX] [--verbose|-v]\n"
536          "               DIRECTORY\n"
537          "\n"
538          "migrate file objects from one OST layout to another\n"
539          "(may be not safe with concurent writes).\n"
540          MIGRATE_USAGE },
541         {"mv", lfs_mv, 0,
542          "To move directories between MDTs. This command is deprecated, "
543          "use \"migrate\" instead.\n"
544          "usage: mv <directory|filename> [--mdt-index|-m MDT_INDEX] "
545          "[--verbose|-v]\n"},
546         {"ladvise", lfs_ladvise, 0,
547          "Provide servers with advice about access patterns for a file.\n"
548          "usage: ladvise [--advice|-a ADVICE] [--start|-s START[kMGT]]\n"
549          "               [--background|-b] [--unset|-u]\n\n"
550          "               {--end|-e END[kMGT]|--length|-l LENGTH[kMGT]}\n"
551          "               {[--mode|-m [READ,WRITE]}\n"
552          "               <file> ...\n"},
553         {"mirror", lfs_mirror, mirror_cmdlist,
554          "lfs commands used to manage files with mirrored components:\n"
555          "lfs mirror create - create a mirrored file or directory\n"
556          "lfs mirror extend - add mirror(s) to an existing file\n"
557          "lfs mirror split  - split a mirror from an existing mirrored file\n"
558          "lfs mirror resync - resynchronize out-of-sync mirrored file(s)\n"
559          "lfs mirror read   - read a mirror content of a mirrored file\n"
560          "lfs mirror write  - write to a mirror of a mirrored file\n"
561          "lfs mirror copy   - copy a mirror to other mirror(s) of a file\n"
562          "lfs mirror verify - verify mirrored file(s)\n"},
563         {"getsom", lfs_getsom, 0, "To list the SOM info for a given file.\n"
564          "usage: getsom [-s] [-b] [-f] <path>\n"
565          "\t-s: Only show the size value of the SOM data for a given file\n"
566          "\t-b: Only show the blocks value of the SOM data for a given file\n"
567          "\t-f: Only show the flags value of the SOM data for a given file\n"},
568         {"heat_get", lfs_heat_get, 0,
569          "To get heat of files.\n"
570          "usage: heat_get <file> ...\n"},
571         {"heat_set", lfs_heat_set, 0,
572          "To set heat flags of files.\n"
573          "usage: heat_set [--clear|-c] [--off|-o] [--on|-O] <file> ...\n"
574          "\t--clear|-c: Clear file heat for given files\n"
575          "\t--off|-o:   Turn off file heat for given files\n"
576          "\t--on|-O:    Turn on file heat for given files\n"},
577         {"pcc", lfs_pcc, pcc_cmdlist,
578          "lfs commands used to interact with PCC features:\n"
579          "lfs pcc attach - attach given files to Persistent Client Cache\n"
580          "lfs pcc attach_fid - attach given files into PCC by FID(s)\n"
581          "lfs pcc state  - display the PCC state for given files\n"
582          "lfs pcc detach - detach given files from Persistent Client Cache\n"
583          "lfs pcc detach_fid - detach given files from PCC by FID(s)\n"},
584         { 0, 0, 0, NULL }
585 };
586
587 static int check_hashtype(const char *hashtype)
588 {
589         int type_num = atoi(hashtype);
590         int i;
591
592         /* numeric hash type */
593         if (hashtype && lmv_is_known_hash_type(type_num))
594                 return type_num;
595         /* string hash type */
596         for (i = LMV_HASH_TYPE_ALL_CHARS; i < ARRAY_SIZE(mdt_hash_name); i++)
597                 if (strcmp(hashtype, mdt_hash_name[i]) == 0)
598                         return i;
599
600         return 0;
601 }
602
603 static uint32_t check_foreign_type_name(const char *foreign_type_name)
604 {
605         uint32_t i;
606
607         for (i = 0; i < LU_FOREIGN_TYPE_UNKNOWN; i++) {
608                 if (!lu_foreign_types[i].lft_name)
609                         break;
610                 if (strcmp(foreign_type_name,
611                            lu_foreign_types[i].lft_name) == 0)
612                         return lu_foreign_types[i].lft_type;
613         }
614
615         return LU_FOREIGN_TYPE_UNKNOWN;
616 }
617
618 static const char *error_loc = "syserror";
619
620 static int
621 migrate_open_files(const char *name, __u64 migration_flags,
622                    const struct llapi_stripe_param *param,
623                    struct llapi_layout *layout, int *fd_src_ptr,
624                    int *fd_dst_ptr)
625 {
626         int                      fd_src = -1;
627         int                      fd_dst = -1;
628         int                      rflags;
629         int                      mdt_index;
630         int                      random_value;
631         char                     parent[PATH_MAX];
632         char                     volatile_file[PATH_MAX];
633         char                    *ptr;
634         int                      rc;
635         struct stat              st;
636         struct stat              stv;
637
638         if (!param && !layout) {
639                 error_loc = "layout information";
640                 return -EINVAL;
641         }
642
643         /* search for file directory pathname */
644         if (strlen(name) > sizeof(parent) - 1) {
645                 error_loc = "source file name";
646                 return -ERANGE;
647         }
648
649         strncpy(parent, name, sizeof(parent));
650         ptr = strrchr(parent, '/');
651         if (!ptr) {
652                 if (!getcwd(parent, sizeof(parent))) {
653                         error_loc = "getcwd";
654                         return -errno;
655                 }
656         } else {
657                 if (ptr == parent) /* leading '/' */
658                         ptr = parent + 1;
659                 *ptr = '\0';
660         }
661
662         /* even if the file is only read, WR mode is nedeed to allow
663          * layout swap on fd
664          */
665         /* Allow migrating even without the key on encrypted files */
666         rflags = O_RDWR | O_NOATIME | O_FILE_ENC;
667         if (!(migration_flags & LLAPI_MIGRATION_NONDIRECT))
668                 rflags |= O_DIRECT;
669 source_open:
670         fd_src = open(name, rflags);
671         if (fd_src < 0) {
672                 /* If encrypted file without the key,
673                  * retry mirror extend in O_DIRECT.
674                  */
675                 if (errno == ENOKEY && !(rflags & O_DIRECT) &&
676                     migration_flags & LLAPI_MIGRATION_MIRROR) {
677                         rflags |= O_DIRECT;
678                         goto source_open;
679                 }
680                 rc = -errno;
681                 error_loc = "cannot open source file";
682                 return rc;
683         }
684
685         rc = llapi_file_fget_mdtidx(fd_src, &mdt_index);
686         if (rc < 0) {
687                 error_loc = "cannot get MDT index";
688                 goto out;
689         }
690
691         do {
692                 int open_flags = O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW |
693                         /* Allow migrating without the key on encrypted files */
694                         O_FILE_ENC;
695                 mode_t open_mode = S_IRUSR | S_IWUSR;
696
697                 if (rflags & O_DIRECT)
698                         open_flags |= O_DIRECT;
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_src);
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                         fd_dst = llapi_layout_file_open(volatile_file,
713                                                          open_flags, open_mode,
714                                                          layout);
715                         if (fd_dst < 0)
716                                 fd_dst = -errno;
717                 } else {
718                         /* Does the right thing on error: */
719                         fd_dst = llapi_file_open_param(volatile_file,
720                                                         open_flags,
721                                                         open_mode, param);
722                 }
723         } while (fd_dst < 0 && (rc = fd_dst) == -EEXIST);
724
725         if (rc < 0) {
726                 error_loc = "cannot create volatile file";
727                 goto out;
728         }
729
730         /*
731          * In case the MDT does not support creation of volatile files
732          * we should try to unlink it.
733          */
734         (void)unlink(volatile_file);
735
736         /*
737          * Not-owner (root?) special case.
738          * Need to set owner/group of volatile file like original.
739          * This will allow to pass related check during layout_swap.
740          */
741         rc = fstat(fd_src, &st);
742         if (rc != 0) {
743                 rc = -errno;
744                 error_loc = "cannot stat source file";
745                 goto out;
746         }
747
748         rc = fstat(fd_dst, &stv);
749         if (rc != 0) {
750                 rc = -errno;
751                 error_loc = "cannot stat volatile";
752                 goto out;
753         }
754
755         if (st.st_uid != stv.st_uid || st.st_gid != stv.st_gid) {
756                 rc = fchown(fd_dst, st.st_uid, st.st_gid);
757                 if (rc != 0) {
758                         rc = -errno;
759                         error_loc = "cannot change ownwership of volatile";
760                         goto out;
761                 }
762         }
763
764 out:
765         if (rc < 0) {
766                 if (fd_src > 0)
767                         close(fd_src);
768                 if (fd_dst > 0)
769                         close(fd_dst);
770         } else {
771                 *fd_src_ptr = fd_src;
772                 *fd_dst_ptr = fd_dst;
773                 error_loc = NULL;
774         }
775         return rc;
776 }
777
778 struct timespec timespec_sub(struct timespec *before, struct timespec *after)
779 {
780         struct timespec ret;
781
782         ret.tv_sec = after->tv_sec - before->tv_sec;
783         if (after->tv_nsec < before->tv_nsec) {
784                 ret.tv_sec--;
785                 ret.tv_nsec = NSEC_PER_SEC + after->tv_nsec - before->tv_nsec;
786         } else {
787                 ret.tv_nsec = after->tv_nsec - before->tv_nsec;
788         }
789
790         return ret;
791 }
792
793 static void stats_log(struct timespec *now, struct timespec *start_time,
794                       enum stats_flag stats_flag,
795                       ssize_t read_bytes, size_t write_bytes,
796                       off_t file_size_bytes)
797 {
798         struct timespec diff = timespec_sub(start_time, now);
799
800         if (stats_flag == STATS_ON && ((diff.tv_sec != 0) ||
801                 (diff.tv_nsec != 0)) && file_size_bytes != 0)
802                 printf("- { seconds: %li, rmbps: %5.2g, wmbps: %5.2g, copied: %lu, size: %lu, pct: %lu%% }\n",
803                         diff.tv_sec,
804                         (double) read_bytes/((ONE_MB * diff.tv_sec) +
805                                 ((ONE_MB * diff.tv_nsec)/NSEC_PER_SEC)),
806                         (double) write_bytes/((ONE_MB * diff.tv_sec) +
807                                 ((ONE_MB * diff.tv_nsec)/NSEC_PER_SEC)),
808                         write_bytes/ONE_MB,
809                         file_size_bytes/ONE_MB,
810                         ((write_bytes*100)/file_size_bytes));
811 }
812
813 static int migrate_copy_data(int fd_src, int fd_dst, int (*check_file)(int),
814                              unsigned long long bandwidth_bytes_sec,
815                              enum stats_flag stats_flag,
816                              long stats_interval_sec, off_t file_size_bytes)
817 {
818         struct llapi_layout *layout;
819         size_t buf_size = 64 * 1024 * 1024;
820         void *buf = NULL;
821         off_t pos = 0;
822         off_t data_end = 0;
823         size_t page_size = sysconf(_SC_PAGESIZE);
824         bool sparse;
825         int rc;
826         size_t write_bytes = 0;
827         ssize_t read_bytes = 0;
828         struct timespec start_time;
829         struct timespec now;
830         struct timespec last_bw_print;
831
832         layout = llapi_layout_get_by_fd(fd_src, 0);
833         if (layout) {
834                 uint64_t stripe_size;
835
836                 rc = llapi_layout_stripe_size_get(layout, &stripe_size);
837                 if (rc == 0) {
838                         /* We like big bufs */
839                         if (stripe_size > buf_size)
840                                 buf_size = stripe_size;
841                         else
842                                 /* Trim to stripe_size multiple */
843                                 buf_size -= buf_size % stripe_size;
844                 }
845
846                 llapi_layout_free(layout);
847         }
848
849         /* Use a page-aligned buffer for direct I/O */
850         rc = posix_memalign(&buf, page_size, buf_size);
851         if (rc != 0)
852                 return -rc;
853
854         sparse = llapi_file_is_sparse(fd_src);
855         if (sparse) {
856                 rc = ftruncate(fd_dst, pos);
857                 if (rc < 0) {
858                         rc = -errno;
859                         return rc;
860                 }
861         }
862
863         clock_gettime(CLOCK_REALTIME, &start_time);
864         now = last_bw_print = start_time;
865
866         while (1) {
867                 off_t data_off;
868                 size_t to_read, to_write;
869                 ssize_t rsize;
870
871                 if (sparse && pos >= data_end) {
872                         size_t data_size;
873
874                         data_off = llapi_data_seek(fd_src, pos, &data_size);
875                         if (data_off < 0) {
876                                 /* Non-fatal, switch to full copy */
877                                 sparse = false;
878                                 continue;
879                         }
880                         /* hole at the end of file, truncate up to it */
881                         if (!data_size) {
882                                 rc = ftruncate(fd_dst, data_off);
883                                 if (rc < 0)
884                                         goto out;
885                         }
886                         pos = data_off & ~(page_size - 1);
887                         data_end = data_off + data_size;
888                         to_read = ((data_end - pos - 1) | (page_size - 1)) + 1;
889                         to_read = MIN(to_read, buf_size);
890                 } else {
891                         to_read = buf_size;
892                 }
893
894                 if (check_file) {
895                         rc = check_file(fd_src);
896                         if (rc < 0)
897                                 goto out;
898                 }
899
900                 rsize = pread(fd_src, buf, to_read, pos);
901                 read_bytes += rsize;
902                 if (rsize < 0) {
903                         rc = -errno;
904                         goto out;
905                 }
906                 /* EOF */
907                 if (rsize == 0)
908                         break;
909
910                 to_write = rsize;
911                 while (to_write > 0) {
912                         unsigned long long write_target;
913                         ssize_t written;
914                         struct timespec diff;
915
916                         written = pwrite(fd_dst, buf, to_write, pos);
917                         if (written < 0) {
918                                 rc = -errno;
919                                 goto out;
920                         }
921                         pos += written;
922                         to_write -= written;
923                         write_bytes += written;
924
925                         if (bandwidth_bytes_sec == 0)
926                                 continue;
927
928                         clock_gettime(CLOCK_REALTIME, &now);
929                         diff = timespec_sub(&start_time, &now);
930                         write_target = ((bandwidth_bytes_sec * diff.tv_sec) +
931                                 ((bandwidth_bytes_sec *
932                                 diff.tv_nsec)/NSEC_PER_SEC));
933
934                         if (write_target < write_bytes) {
935                                 unsigned long long excess;
936                                 struct timespec delay = { 0, 0 };
937
938                                 excess = write_bytes - write_target;
939
940                                 if (excess == 0)
941                                         continue;
942
943                                 delay.tv_sec = excess / bandwidth_bytes_sec;
944                                 delay.tv_nsec = (excess % bandwidth_bytes_sec) *
945                                         NSEC_PER_SEC / bandwidth_bytes_sec;
946
947                                 do {
948                                         rc = clock_nanosleep(CLOCK_REALTIME, 0,
949                                                              &delay, &delay);
950                                 } while (rc < 0 && errno == EINTR);
951
952                                 if (rc < 0) {
953                                         if (stats_flag == STATS_OFF)
954                                                 fprintf(stderr,
955                                                         "error %s: delay for bandwidth control failed: %s\n",
956                                                         progname,
957                                                         strerror(-rc));
958                                         rc = 0;
959                                 }
960                         }
961                 }
962
963                 clock_gettime(CLOCK_REALTIME, &now);
964                 if ((write_bytes != file_size_bytes) &&
965                         (now.tv_sec >= last_bw_print.tv_sec +
966                         stats_interval_sec)) {
967                         stats_log(&now, &start_time, stats_flag,
968                                   read_bytes, write_bytes,
969                                   file_size_bytes);
970                         last_bw_print = now;
971                 }
972
973                 if (rc || rsize < to_read)
974                         break;
975         }
976
977         /* Output at least one log, regardless of stats_interval */
978         clock_gettime(CLOCK_REALTIME, &now);
979         stats_log(&now, &start_time, stats_flag,
980                   read_bytes, write_bytes,
981                   file_size_bytes);
982
983         rc = fsync(fd_dst);
984         if (rc < 0)
985                 rc = -errno;
986 out:
987         /* Try to avoid page cache pollution after migration. */
988         (void)posix_fadvise(fd_src, 0, 0, POSIX_FADV_DONTNEED);
989         (void)posix_fadvise(fd_dst, 0, 0, POSIX_FADV_DONTNEED);
990
991         free(buf);
992         return rc;
993 }
994
995 static int migrate_set_timestamps(int fd, const struct stat *st)
996 {
997         struct timeval tv[2] = {
998                 {.tv_sec = st->st_atime},
999                 {.tv_sec = st->st_mtime}
1000         };
1001
1002         return futimes(fd, tv);
1003 }
1004
1005 static int migrate_block(int fd_src, int fd_dst,
1006                          unsigned long long bandwidth_bytes_sec,
1007                          enum stats_flag stats_flag,
1008                          long stats_interval_sec)
1009 {
1010         struct stat st;
1011         __u64   dv1;
1012         int     gid;
1013         int     rc;
1014         int     rc2;
1015
1016         do
1017                 gid = random();
1018         while (gid == 0);
1019
1020
1021         /* The grouplock blocks all concurrent accesses to the file. */
1022         rc = llapi_group_lock(fd_src, gid);
1023         if (rc < 0) {
1024                 error_loc = "cannot get group lock";
1025                 return rc;
1026         }
1027
1028         rc = fstat(fd_src, &st);
1029         if (rc < 0) {
1030                 error_loc = "cannot stat source file";
1031                 rc = -errno;
1032                 goto out_unlock;
1033         }
1034
1035         /*
1036          * LL_DV_RD_FLUSH should not be set, otherwise the servers will try to
1037          * get extent locks on the OST objects. This will conflict with our
1038          * extent group locks.
1039          */
1040         rc = llapi_get_data_version(fd_src, &dv1, 0);
1041         if (rc < 0) {
1042                 error_loc = "cannot get dataversion";
1043                 goto out_unlock;
1044         }
1045
1046         rc = migrate_copy_data(fd_src, fd_dst, NULL, bandwidth_bytes_sec,
1047                                stats_flag, stats_interval_sec,
1048                                st.st_size);
1049         if (rc < 0) {
1050                 error_loc = "data copy failed";
1051                 goto out_unlock;
1052         }
1053
1054         /* Make sure we keep original atime/mtime values */
1055         rc = migrate_set_timestamps(fd_dst, &st);
1056         if (rc < 0) {
1057                 error_loc = "set target file timestamp failed";
1058                 goto out_unlock;
1059         }
1060
1061         /*
1062          * swap layouts
1063          * for a migration we need to check data version on file did
1064          * not change.
1065          *
1066          * Pass in gid=0 since we already own grouplock.
1067          */
1068         rc = llapi_fswap_layouts_grouplock(fd_src, fd_dst, dv1, 0, 0,
1069                                            SWAP_LAYOUTS_CHECK_DV1);
1070         if (rc == -EAGAIN) {
1071                 error_loc = "file changed";
1072                 goto out_unlock;
1073         } else if (rc < 0) {
1074                 error_loc = "cannot swap layout";
1075                 goto out_unlock;
1076         }
1077
1078 out_unlock:
1079         rc2 = llapi_group_unlock(fd_src, gid);
1080         if (rc2 < 0 && rc == 0) {
1081                 error_loc = "unlock group lock";
1082                 rc = rc2;
1083         }
1084
1085         return rc;
1086 }
1087
1088 /**
1089  * Internal helper for migrate_copy_data(). Check lease and report error if
1090  * need be.
1091  *
1092  * \param[in]  fd           File descriptor on which to check the lease.
1093  *
1094  * \retval 0       Migration can keep on going.
1095  * \retval -errno  Error occurred, abort migration.
1096  */
1097 static int check_lease(int fd)
1098 {
1099         int rc;
1100
1101         rc = llapi_lease_check(fd);
1102         if (rc > 0)
1103                 return 0; /* llapi_check_lease returns > 0 on success. */
1104
1105         return -EBUSY;
1106 }
1107
1108 static int migrate_nonblock(int fd_src, int fd_dst,
1109                             unsigned long long bandwidth_bytes_sec,
1110                             enum stats_flag stats_flag,
1111                             long stats_interval_sec)
1112 {
1113         struct stat st;
1114         __u64   dv1;
1115         __u64   dv2;
1116         int     rc;
1117
1118         rc = fstat(fd_src, &st);
1119         if (rc < 0) {
1120                 error_loc = "cannot stat source file";
1121                 return -errno;
1122         }
1123
1124         rc = llapi_get_data_version(fd_src, &dv1, LL_DV_RD_FLUSH);
1125         if (rc < 0) {
1126                 error_loc = "cannot get data version";
1127                 return rc;
1128         }
1129
1130         rc = migrate_copy_data(fd_src, fd_dst, check_lease,
1131                                bandwidth_bytes_sec, stats_flag,
1132                                stats_interval_sec, st.st_size);
1133         if (rc < 0) {
1134                 error_loc = "data copy failed";
1135                 return rc;
1136         }
1137
1138         rc = llapi_get_data_version(fd_src, &dv2, LL_DV_RD_FLUSH);
1139         if (rc != 0) {
1140                 error_loc = "cannot get data version";
1141                 return rc;
1142         }
1143
1144         if (dv1 != dv2) {
1145                 rc = -EAGAIN;
1146                 error_loc = "source file changed";
1147                 return rc;
1148         }
1149
1150         /* Make sure we keep original atime/mtime values */
1151         rc = migrate_set_timestamps(fd_dst, &st);
1152         if (rc < 0) {
1153                 error_loc = "set target file timestamp failed";
1154                 return -errno;
1155         }
1156         return 0;
1157 }
1158
1159 static
1160 int lfs_layout_compid_by_pool(char *fname, const char *pool, int *comp_id)
1161 {
1162         struct pool_to_id_cbdata data = { .pool = pool };
1163         struct llapi_layout *layout = NULL;
1164         int rc;
1165
1166         layout = llapi_layout_get_by_path(fname, 0);
1167         if (!layout) {
1168                 fprintf(stderr,
1169                         "error %s: file '%s' couldn't get layout: rc=%d\n",
1170                         progname, fname, errno);
1171                 rc = -errno;
1172                 goto free_layout;
1173         }
1174         rc = llapi_layout_sanity(layout, false, true);
1175         if (rc < 0) {
1176                 llapi_layout_sanity_perror(errno);
1177                 goto free_layout;
1178         }
1179         rc = llapi_layout_comp_iterate(layout, find_comp_id_by_pool, &data);
1180         if (rc < 0)
1181                 goto free_layout;
1182
1183         *comp_id = data.id;
1184         rc = 0;
1185
1186 free_layout:
1187         if (layout)
1188                 llapi_layout_free(layout);
1189         return rc;
1190 }
1191
1192 static int lfs_component_set(char *fname, int comp_id, const char *pool,
1193                              __u32 flags, __u32 neg_flags)
1194 {
1195         __u32 ids[2];
1196         __u32 flags_array[2];
1197         size_t count = 0;
1198         int rc;
1199
1200         if (!comp_id) {
1201                 if (pool == NULL) {
1202                         fprintf(stderr,
1203                                 "error %s: neither component id nor pool is specified\n",
1204                                 progname);
1205                         return -EINVAL;
1206                 }
1207                 rc = lfs_layout_compid_by_pool(fname, pool, &comp_id);
1208                 if (rc)
1209                         return rc;
1210         }
1211
1212         if (flags) {
1213                 ids[count] = comp_id;
1214                 flags_array[count] = flags;
1215                 ++count;
1216         }
1217
1218         if (neg_flags) {
1219                 if (neg_flags & LCME_FL_STALE) {
1220                         fprintf(stderr,
1221                                 "%s: cannot clear 'stale' flags from component. Please use lfs-mirror-resync(1) instead\n",
1222                                 progname);
1223                         return -EINVAL;
1224                 }
1225
1226                 ids[count] = comp_id;
1227                 flags_array[count] = neg_flags | LCME_FL_NEG;
1228                 ++count;
1229         }
1230
1231         rc = llapi_layout_file_comp_set(fname, ids, flags_array, count);
1232         if (rc) {
1233                 if (errno == EUCLEAN) {
1234                         rc = -errno;
1235                         fprintf(stderr,
1236                                 "%s: cannot set 'stale' flag on component '%#x' of the last non-stale mirror of '%s'\n",
1237                                 progname, comp_id, fname);
1238                 } else {
1239                         fprintf(stderr,
1240                                 "%s: cannot change the flags of component '%#x' of file '%s': %x / ^(%x)\n",
1241                                 progname, comp_id, fname, flags, neg_flags);
1242                 }
1243         }
1244
1245         return rc;
1246 }
1247
1248 static int lfs_component_del(char *fname, __u32 comp_id,
1249                              __u32 flags, __u32 neg_flags)
1250 {
1251         int     rc = 0;
1252
1253         if (flags && neg_flags) {
1254                 fprintf(stderr,
1255                         "%s: cannot specify both positive and negative flags\n",
1256                         progname);
1257                 return -EINVAL;
1258         }
1259
1260         if (!flags && neg_flags)
1261                 flags = neg_flags | LCME_FL_NEG;
1262
1263         if (flags && comp_id) {
1264                 fprintf(stderr,
1265                         "%s: cannot specify component ID and flags at the same time\n",
1266                         progname);
1267                 return -EINVAL;
1268         }
1269
1270         if (!flags && !comp_id) {
1271                 fprintf(stderr,
1272                         "%s: neither flags nor component ID is specified\n",
1273                         progname);
1274                 return -EINVAL;
1275         }
1276
1277         if (flags) {
1278                 if (flags & ~LCME_KNOWN_FLAGS) {
1279                         fprintf(stderr,
1280                                 "%s setstripe: unknown flags %#x\n",
1281                                 progname, flags);
1282                         return -EINVAL;
1283                 }
1284         } else if (comp_id > LCME_ID_MAX) {
1285                 fprintf(stderr, "%s setstripe: invalid component id %u\n",
1286                         progname, comp_id);
1287                 return -EINVAL;
1288         }
1289
1290         rc = llapi_layout_file_comp_del(fname, comp_id, flags);
1291         if (rc)
1292                 fprintf(stderr,
1293                         "%s setstripe: cannot delete component %#x from '%s': %s\n",
1294                         progname, comp_id, fname, strerror(errno));
1295         return rc;
1296 }
1297
1298 static int lfs_component_add(char *fname, struct llapi_layout *layout)
1299 {
1300         int     rc;
1301
1302         if (!layout)
1303                 return -EINVAL;
1304
1305         rc = llapi_layout_file_comp_add(fname, layout);
1306         if (rc)
1307                 fprintf(stderr, "Add layout component(s) to %s failed. %s\n",
1308                         fname, strerror(errno));
1309         return rc;
1310 }
1311
1312 static int lfs_component_create(char *fname, int open_flags, mode_t open_mode,
1313                                 struct llapi_layout *layout)
1314 {
1315         struct stat     st;
1316         int     fd;
1317
1318         if (!layout)
1319                 return -EINVAL;
1320
1321         fd = lstat(fname, &st);
1322         if (fd == 0 && S_ISDIR(st.st_mode))
1323                 open_flags = O_DIRECTORY | O_RDONLY;
1324
1325         fd = llapi_layout_file_open(fname, open_flags, open_mode, layout);
1326         if (fd < 0)
1327                 fprintf(stderr, "%s: cannot %s '%s': %s\n", progname,
1328                         S_ISDIR(st.st_mode) ?
1329                                 "set default composite layout for" :
1330                                 "create composite file",
1331                         fname, strerror(errno));
1332         return fd;
1333 }
1334
1335 static int lfs_migrate(char *name, __u64 migration_flags,
1336                         struct llapi_stripe_param *param,
1337                         struct llapi_layout *layout,
1338                         unsigned long long bandwidth_bytes_sec,
1339                         enum stats_flag stats_flag, long stats_interval_sec)
1340 {
1341         struct llapi_layout *existing;
1342         uint64_t dom_new, dom_cur;
1343         int fd_src = -1;
1344         int fd_dst = -1;
1345         int rc;
1346
1347         rc = migrate_open_files(name, migration_flags, param, layout,
1348                                 &fd_src, &fd_dst);
1349         if (rc < 0)
1350                 goto out;
1351
1352         rc = llapi_layout_dom_size(layout, &dom_new);
1353         if (rc) {
1354                 error_loc = "cannot get new layout DoM size";
1355                 goto out;
1356         }
1357         /* special case for migration to DOM layout*/
1358         existing = llapi_layout_get_by_fd(fd_src, 0);
1359         if (!existing) {
1360                 error_loc = "cannot get existing layout";
1361                 goto out;
1362         }
1363
1364         rc = llapi_layout_dom_size(existing, &dom_cur);
1365         if (rc) {
1366                 error_loc = "cannot get current layout DoM size";
1367                 goto out;
1368         }
1369
1370         /*
1371          * if file has DoM layout already then migration is possible to
1372          * the new layout with the same DoM component via swap layout,
1373          * if new layout used bigger DOM size, then mirroring is used
1374          */
1375         if (dom_new > dom_cur) {
1376                 rc = lfs_migrate_to_dom(fd_src, fd_dst, name, migration_flags,
1377                                         bandwidth_bytes_sec, stats_flag,
1378                                         stats_interval_sec);
1379                 if (rc)
1380                         error_loc = "cannot migrate to DOM layout";
1381                 goto out_closed;
1382         }
1383
1384         if (stats_flag == STATS_ON)
1385                 printf("%s:\n", name);
1386
1387         if (!(migration_flags & LLAPI_MIGRATION_NONBLOCK)) {
1388                 /*
1389                  * Blocking mode (forced if servers do not support file lease).
1390                  * It is also the default mode, since we cannot distinguish
1391                  * between a broken lease and a server that does not support
1392                  * atomic swap/close (LU-6785)
1393                  */
1394                 rc = migrate_block(fd_src, fd_dst, bandwidth_bytes_sec,
1395                                    stats_flag, stats_interval_sec);
1396                 goto out;
1397         }
1398
1399         rc = llapi_lease_acquire(fd_src, LL_LEASE_RDLCK);
1400         if (rc < 0) {
1401                 error_loc = "cannot get lease";
1402                 goto out;
1403         }
1404
1405         rc = migrate_nonblock(fd_src, fd_dst, bandwidth_bytes_sec, stats_flag,
1406                               stats_interval_sec);
1407         if (rc < 0) {
1408                 llapi_lease_release(fd_src);
1409                 goto out;
1410         }
1411
1412         /*
1413          * Atomically put lease, swap layouts and close.
1414          * for a migration we need to check data version on file did
1415          * not change.
1416          */
1417         rc = llapi_fswap_layouts(fd_src, fd_dst, 0, 0, SWAP_LAYOUTS_CLOSE);
1418         if (rc < 0) {
1419                 error_loc = "cannot swap layout";
1420                 goto out;
1421         }
1422
1423 out:
1424         if (fd_src >= 0)
1425                 close(fd_src);
1426
1427         if (fd_dst >= 0)
1428                 close(fd_dst);
1429 out_closed:
1430         if (rc < 0)
1431                 fprintf(stderr, "error: %s: %s: %s: %s\n",
1432                         progname, name, error_loc, strerror(-rc));
1433         else if (migration_flags & LLAPI_MIGRATION_VERBOSE)
1434                 printf("%s\n", name);
1435
1436         return rc;
1437 }
1438
1439 static int comp_str2flags(char *string, __u32 *flags, __u32 *neg_flags)
1440 {
1441         char *name;
1442         char *dup_string = NULL;
1443         int rc = 0;
1444
1445         *flags = 0;
1446         *neg_flags = 0;
1447
1448         if (!string || !string[0])
1449                 return -EINVAL;
1450
1451         dup_string = strdup(string);
1452         if (!dup_string) {
1453                 llapi_printf(LLAPI_MSG_ERROR,
1454                              "%s: insufficient memory\n",
1455                              progname);
1456                 return -ENOMEM;
1457         }
1458
1459         for (name = strtok(dup_string, ","); name; name = strtok(NULL, ",")) {
1460                 bool found = false;
1461                 int i;
1462
1463                 for (i = 0; i < ARRAY_SIZE(comp_flags_table); i++) {
1464                         __u32 comp_flag = comp_flags_table[i].cfn_flag;
1465                         const char *comp_name = comp_flags_table[i].cfn_name;
1466
1467                         if (strcmp(name, comp_name) == 0) {
1468                                 *flags |= comp_flag;
1469                                 found = true;
1470                         } else if (strncmp(name, "^", 1) == 0 &&
1471                                    strcmp(name + 1, comp_name) == 0) {
1472                                 *neg_flags |= comp_flag;
1473                                 found = true;
1474                         }
1475                 }
1476                 if (!found) {
1477                         llapi_printf(LLAPI_MSG_ERROR,
1478                                      "%s: component flag '%s' not supported\n",
1479                                      progname, name);
1480                         rc = -EINVAL;
1481                         goto out_free;
1482                 }
1483         }
1484
1485         if (!*flags && !*neg_flags)
1486                 rc = -EINVAL;
1487
1488         /* don't allow to set and exclude the same flag */
1489         if (*flags & *neg_flags)
1490                 rc = -EINVAL;
1491
1492 out_free:
1493         free(dup_string);
1494         return rc;
1495 }
1496
1497 static int mdthash_input(char *string, __u32 *inflags,
1498                          __u32 *exflags, __u32 *type)
1499 {
1500         char *name;
1501         struct mhf_list {
1502                 char *name;
1503                 __u32 flag;
1504         } mhflist[] = {
1505                 {"migrating", LMV_HASH_FLAG_MIGRATION},
1506                 {"bad_type", LMV_HASH_FLAG_BAD_TYPE},
1507                 {"badtype", LMV_HASH_FLAG_BAD_TYPE},
1508                 {"lost_lmv", LMV_HASH_FLAG_LOST_LMV},
1509                 {"lostlmv", LMV_HASH_FLAG_LOST_LMV},
1510         };
1511
1512         if (string == NULL)
1513                 return -EINVAL;
1514
1515         *inflags = 0;
1516         *exflags = 0;
1517         *type = 0;
1518         for (name = strtok(string, ","); name; name = strtok(NULL, ",")) {
1519                 bool found = false;
1520                 int i;
1521
1522                 for (i = 0; i < ARRAY_SIZE(mhflist); i++) {
1523                         if (strcmp(name, mhflist[i].name) == 0 ||
1524                             name[0] == mhflist[i].name[0]) {
1525                                 *inflags |= mhflist[i].flag;
1526                                 found = true;
1527                         } else if (name[0] == '^' &&
1528                                    (strcmp(name + 1, mhflist[i].name) == 0 ||
1529                                     name[1] == mhflist[i].name[0])) {
1530                                 *exflags |= mhflist[i].flag;
1531                                 found = true;
1532                         }
1533                 }
1534                 if (!found) {
1535                         i = check_hashtype(name);
1536                         if (i > 0) {
1537                                 *type |= 1 << i;
1538                                 continue;
1539                         }
1540                         llapi_printf(LLAPI_MSG_ERROR,
1541                                      "%s: invalid mdt_hash value '%s'\n",
1542                                      progname, name);
1543                         return -EINVAL;
1544                 }
1545         }
1546
1547         /* don't allow to include and exclude the same flag */
1548         if (*inflags & *exflags) {
1549                 llapi_printf(LLAPI_MSG_ERROR,
1550                              "%s: include and exclude same flag '%s'\n",
1551                              progname, string);
1552                 return -EINVAL;
1553         }
1554
1555         return 0;
1556 }
1557
1558 static int mirror_str2state(char *string, __u16 *state, __u16 *neg_state)
1559 {
1560         if (!string)
1561                 return -EINVAL;
1562
1563         *state = 0;
1564         *neg_state = 0;
1565
1566         if (strncmp(string, "^", 1) == 0) {
1567                 *neg_state = llapi_layout_string_flags(string + 1);
1568                 if (*neg_state != 0)
1569                         return 0;
1570         } else {
1571                 *state = llapi_layout_string_flags(string);
1572                 if (*state != 0)
1573                         return 0;
1574         }
1575
1576         llapi_printf(LLAPI_MSG_ERROR,
1577                      "%s: mirrored file state '%s' not supported\n",
1578                      progname, string);
1579         return -EINVAL;
1580 }
1581
1582 /**
1583  * struct mirror_args - Command-line arguments for mirror(s).
1584  * @m_count:  Number of mirrors to be created with this layout.
1585  * @m_flags:  Mirror level flags, only 'prefer' is supported.
1586  * @m_layout: Mirror layout.
1587  * @m_file:   A victim file. Its layout will be split and used as a mirror.
1588  * @m_next:   Point to the next node of the list.
1589  *
1590  * Command-line arguments for mirror(s) will be parsed and stored in
1591  * a linked list that consists of this structure.
1592  */
1593 struct mirror_args {
1594         __u32                   m_count;
1595         __u32                   m_flags;
1596         struct llapi_layout     *m_layout;
1597         const char              *m_file;
1598         struct mirror_args      *m_next;
1599         bool                    m_inherit;
1600 };
1601
1602 /**
1603  * enum mirror_flags - Flags for extending a mirrored file.
1604  * @MF_NO_VERIFY: Indicates not to verify the mirror(s) from victim file(s)
1605  *             in case the victim file(s) contains the same data as the
1606  *             original mirrored file.
1607  * @MF_DESTROY: Indicates to delete the mirror from the mirrored file.
1608  * @MF_COMP_ID: specified component id instead of mirror id
1609  *
1610  * Flags for extending a mirrored file.
1611  */
1612 enum mirror_flags {
1613         MF_NO_VERIFY    = 0x1,
1614         MF_DESTROY      = 0x2,
1615         MF_COMP_ID      = 0x4,
1616         MF_COMP_POOL    = 0x8,
1617 };
1618
1619 /**
1620  * mirror_create_sanity_check() - Check mirror list.
1621  * @list:  A linked list that stores the mirror arguments.
1622  *
1623  * This function does a sanity check on @list for creating
1624  * a mirrored file.
1625  *
1626  * Return: 0 on success or a negative error code on failure.
1627  */
1628 static int mirror_create_sanity_check(const char *fname,
1629                                       struct mirror_args *list,
1630                                       bool check_fname)
1631 {
1632         int rc = 0;
1633         bool has_m_file = false;
1634         bool has_m_layout = false;
1635
1636         if (!list)
1637                 return -EINVAL;
1638
1639         if (fname && check_fname) {
1640                 struct llapi_layout *layout;
1641
1642                 layout = llapi_layout_get_by_path(fname, 0);
1643                 if (!layout) {
1644                         fprintf(stderr,
1645                                 "error: %s: file '%s' couldn't get layout\n",
1646                                 progname, fname);
1647                         return -ENODATA;
1648                 }
1649
1650                 rc = llapi_layout_sanity(layout, false, true);
1651
1652                 llapi_layout_free(layout);
1653
1654                 if (rc) {
1655                         llapi_layout_sanity_perror(rc);
1656                         return rc;
1657                 }
1658         }
1659
1660         while (list) {
1661                 if (list->m_file) {
1662                         has_m_file = true;
1663                         llapi_layout_free(list->m_layout);
1664
1665                         list->m_layout =
1666                                 llapi_layout_get_by_path(list->m_file, 0);
1667                         if (!list->m_layout) {
1668                                 fprintf(stderr,
1669                                         "error: %s: file '%s' has no layout\n",
1670                                         progname, list->m_file);
1671                                 return -ENODATA;
1672                         }
1673                 } else {
1674                         has_m_layout = true;
1675                         if (!list->m_layout) {
1676                                 fprintf(stderr, "error: %s: no mirror layout\n",
1677                                         progname);
1678                                 return -EINVAL;
1679                         }
1680                 }
1681
1682                 rc = llapi_layout_sanity(list->m_layout, false, true);
1683                 if (rc) {
1684                         llapi_layout_sanity_perror(rc);
1685                         return rc;
1686                 }
1687
1688                 list = list->m_next;
1689         }
1690
1691         if (has_m_file && has_m_layout) {
1692                 fprintf(stderr,
1693                         "error: %s: -f <victim_file> option should not be specified with setstripe options\n",
1694                         progname);
1695                 return -EINVAL;
1696         }
1697
1698         return 0;
1699 }
1700
1701 static int mirror_set_flags(struct llapi_layout *layout, void *cbdata)
1702 {
1703         __u32 mirror_flags = *(__u32 *)cbdata;
1704         uint32_t flags;
1705         int rc;
1706
1707         rc = llapi_layout_comp_flags_get(layout, &flags);
1708         if (rc < 0)
1709                 return rc;
1710
1711         if (!flags) {
1712                 rc = llapi_layout_comp_flags_set(layout, mirror_flags);
1713                 if (rc)
1714                         return rc;
1715         }
1716
1717         return LLAPI_LAYOUT_ITER_CONT;
1718 }
1719
1720 /**
1721  * mirror_create() - Create a mirrored file.
1722  * @fname:        The file to be created.
1723  * @mirror_list:  A linked list that stores the mirror arguments.
1724  *
1725  * This function creates a mirrored file @fname with the mirror(s)
1726  * from @mirror_list.
1727  *
1728  * Return: 0 on success or a negative error code on failure.
1729  */
1730 static int mirror_create(char *fname, struct mirror_args *mirror_list)
1731 {
1732         struct llapi_layout *layout = NULL;
1733         struct mirror_args *cur_mirror = NULL;
1734         uint16_t mirror_count = 0;
1735         int i = 0;
1736         int rc = 0;
1737
1738         rc = mirror_create_sanity_check(fname, mirror_list, false);
1739         if (rc)
1740                 return rc;
1741
1742         cur_mirror = mirror_list;
1743         while (cur_mirror) {
1744                 rc = llapi_layout_comp_iterate(cur_mirror->m_layout,
1745                                                mirror_set_flags,
1746                                                &cur_mirror->m_flags);
1747                 if (rc) {
1748                         rc = -errno;
1749                         fprintf(stderr, "%s: failed to set mirror flags\n",
1750                                 progname);
1751                         goto error;
1752                 }
1753
1754                 for (i = 0; i < cur_mirror->m_count; i++) {
1755                         rc = llapi_layout_merge(&layout, cur_mirror->m_layout);
1756                         if (rc) {
1757                                 rc = -errno;
1758                                 fprintf(stderr,
1759                                         "error: %s: merge layout failed: %s\n",
1760                                         progname, strerror(errno));
1761                                 goto error;
1762                         }
1763                 }
1764                 mirror_count += cur_mirror->m_count;
1765                 cur_mirror = cur_mirror->m_next;
1766         }
1767
1768         if (!layout) {
1769                 fprintf(stderr, "error: %s: layout is NULL\n", progname);
1770                 return -EINVAL;
1771         }
1772
1773         rc = llapi_layout_mirror_count_set(layout, mirror_count);
1774         if (rc) {
1775                 rc = -errno;
1776                 fprintf(stderr, "error: %s: set mirror count failed: %s\n",
1777                         progname, strerror(errno));
1778                 goto error;
1779         }
1780
1781         rc = lfs_component_create(fname, O_CREAT | O_WRONLY, 0666,
1782                                   layout);
1783         if (rc >= 0) {
1784                 close(rc);
1785                 rc = 0;
1786         }
1787
1788 error:
1789         llapi_layout_free(layout);
1790         return rc;
1791 }
1792
1793 /**
1794  * Compare files and check lease on @fd.
1795  *
1796  * \retval bytes number of bytes are the same
1797  */
1798 static ssize_t mirror_file_compare(int fd_src, int fd_dst)
1799 {
1800         const size_t buflen = 4 * 1024 * 1024; /* 4M */
1801         void *buf;
1802         ssize_t bytes_done = 0;
1803         ssize_t bytes_read = 0;
1804
1805         buf = malloc(buflen * 2);
1806         if (!buf)
1807                 return -ENOMEM;
1808
1809         while (1) {
1810                 if (!llapi_lease_check(fd_src)) {
1811                         bytes_done = -EBUSY;
1812                         break;
1813                 }
1814
1815                 bytes_read = read(fd_src, buf, buflen);
1816                 if (bytes_read <= 0)
1817                         break;
1818
1819                 if (bytes_read != read(fd_dst, buf + buflen, buflen))
1820                         break;
1821
1822                 /*
1823                  * XXX: should compute the checksum on each buffer and then
1824                  * compare checksum to avoid cache collision
1825                  */
1826                 if (memcmp(buf, buf + buflen, bytes_read))
1827                         break;
1828
1829                 bytes_done += bytes_read;
1830         }
1831
1832         free(buf);
1833
1834         return bytes_done;
1835 }
1836
1837 static int mirror_extend_file(const char *fname, const char *victim_file,
1838                               enum mirror_flags mirror_flags)
1839 {
1840         int fd = -1;
1841         int fdv = -1;
1842         struct stat stbuf;
1843         struct stat stbuf_v;
1844         struct ll_ioc_lease *data = NULL;
1845         int rc;
1846
1847         fd = open(fname, O_RDWR);
1848         if (fd < 0) {
1849                 error_loc = "open source file";
1850                 rc = -errno;
1851                 goto out;
1852         }
1853
1854         fdv = open(victim_file, O_RDWR);
1855         if (fdv < 0) {
1856                 error_loc = "open target file";
1857                 rc = -errno;
1858                 goto out;
1859         }
1860
1861         if (fstat(fd, &stbuf) || fstat(fdv, &stbuf_v)) {
1862                 error_loc = "stat source or target file";
1863                 rc = -errno;
1864                 goto out;
1865         }
1866
1867         if (stbuf.st_dev != stbuf_v.st_dev) {
1868                 error_loc = "stat source and target file";
1869                 rc = -EXDEV;
1870                 goto out;
1871         }
1872
1873         /* mirrors should be of the same size */
1874         if (stbuf.st_size != stbuf_v.st_size) {
1875                 error_loc = "file sizes don't match";
1876                 rc = -EINVAL;
1877                 goto out;
1878         }
1879
1880         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
1881         if (rc < 0) {
1882                 error_loc = "cannot get lease";
1883                 goto out;
1884         }
1885
1886         if (!(mirror_flags & MF_NO_VERIFY)) {
1887                 ssize_t ret;
1888                 /* mirrors should have the same contents */
1889                 ret = mirror_file_compare(fd, fdv);
1890                 if (ret != stbuf.st_size) {
1891                         error_loc = "file busy or contents don't match";
1892                         rc = ret < 0 ? ret : -EINVAL;
1893                         goto out;
1894                 }
1895         }
1896
1897         /* Get rid of caching pages from clients */
1898         rc = llapi_file_flush(fd);
1899         if (rc < 0) {
1900                 error_loc = "cannot get data version";
1901                 goto out;
1902         }
1903
1904         rc = llapi_file_flush(fdv);
1905         if (rc < 0) {
1906                 error_loc = "cannot get data version";
1907                 goto out;
1908         }
1909
1910         rc = migrate_set_timestamps(fd, &stbuf);
1911         if (rc < 0) {
1912                 error_loc = "cannot set source file timestamp";
1913                 goto out;
1914         }
1915
1916         /* Atomically put lease, merge layouts and close. */
1917         data = calloc(1, offsetof(typeof(*data), lil_ids[1]));
1918         if (!data) {
1919                 error_loc = "memory allocation";
1920                 goto out;
1921         }
1922         data->lil_mode = LL_LEASE_UNLCK;
1923         data->lil_flags = LL_LEASE_LAYOUT_MERGE;
1924         data->lil_count = 1;
1925         data->lil_ids[0] = fdv;
1926         rc = llapi_lease_set(fd, data);
1927         if (rc < 0) {
1928                 error_loc = "cannot merge layout";
1929                 goto out;
1930         } else if (rc == 0) {
1931                 rc = -EBUSY;
1932                 error_loc = "lost lease lock";
1933                 goto out;
1934         }
1935         rc = 0;
1936
1937 out:
1938         if (data)
1939                 free(data);
1940         if (fd >= 0)
1941                 close(fd);
1942         if (fdv >= 0)
1943                 close(fdv);
1944         if (!rc)
1945                 (void) unlink(victim_file);
1946         if (rc < 0)
1947                 fprintf(stderr, "error: %s: %s: %s: %s\n",
1948                         progname, fname, error_loc, strerror(-rc));
1949         return rc;
1950 }
1951
1952 static int mirror_extend_layout(char *name, struct llapi_layout *m_layout,
1953                                 bool inherit, uint32_t flags,
1954                                 unsigned long long bandwidth_bytes_sec,
1955                                 enum stats_flag stats_flag,
1956                                 long stats_interval_sec)
1957 {
1958         struct llapi_layout *f_layout = NULL;
1959         struct ll_ioc_lease *data = NULL;
1960         struct stat st;
1961         int fd_src = -1;
1962         int fd_dst = -1;
1963         int rc = 0;
1964
1965         if (inherit) {
1966                 f_layout = llapi_layout_get_by_path(name, 0);
1967                 if (!f_layout) {
1968                         rc = -EINVAL;
1969                         fprintf(stderr, "%s: cannot get layout\n", progname);
1970                         goto out;
1971                 }
1972                 rc = llapi_layout_get_last_init_comp(f_layout);
1973                 if (rc) {
1974                         fprintf(stderr, "%s: cannot get the last init comp\n",
1975                                 progname);
1976                         goto out;
1977                 }
1978                 rc = llapi_layout_mirror_inherit(f_layout, m_layout);
1979                 if (rc) {
1980                         fprintf(stderr,
1981                                 "%s: cannot inherit from the last init comp\n",
1982                                 progname);
1983                         goto out;
1984                 }
1985         }
1986
1987         llapi_layout_comp_flags_set(m_layout, flags);
1988         rc = migrate_open_files(name,
1989                              LLAPI_MIGRATION_NONDIRECT | LLAPI_MIGRATION_MIRROR,
1990                              NULL, m_layout, &fd_src, &fd_dst);
1991         if (rc < 0)
1992                 goto out;
1993
1994         rc = llapi_lease_acquire(fd_src, LL_LEASE_RDLCK);
1995         if (rc < 0) {
1996                 error_loc = "cannot get lease";
1997                 goto out;
1998         }
1999
2000         rc = fstat(fd_src, &st);
2001         if (rc < 0) {
2002                 error_loc = "cannot stat source file";
2003                 goto out;
2004         }
2005
2006         if (stats_flag)
2007                 printf("%s:\n", name);
2008
2009         rc = migrate_nonblock(fd_src, fd_dst, bandwidth_bytes_sec, stats_flag,
2010                               stats_interval_sec);
2011         if (rc < 0) {
2012                 llapi_lease_release(fd_src);
2013                 goto out;
2014         }
2015
2016         rc = migrate_set_timestamps(fd_src, &st);
2017         if (rc < 0) {
2018                 error_loc = "cannot set source file timestamp";
2019                 goto out;
2020         }
2021
2022         /* Atomically put lease, merge layouts and close. */
2023         data = calloc(1, offsetof(typeof(*data), lil_ids[1]));
2024         if (!data) {
2025                 error_loc = "memory allocation";
2026                 goto out;
2027         }
2028         data->lil_mode = LL_LEASE_UNLCK;
2029         data->lil_flags = LL_LEASE_LAYOUT_MERGE;
2030         data->lil_count = 1;
2031         data->lil_ids[0] = fd_dst;
2032         rc = llapi_lease_set(fd_src, data);
2033         if (rc < 0) {
2034                 error_loc = "cannot merge layout";
2035                 goto out;
2036         } else if (rc == 0) {
2037                 rc = -EBUSY;
2038                 error_loc = "lost lease lock";
2039                 goto out;
2040         }
2041         rc = 0;
2042
2043 out:
2044         if (data)
2045                 free(data);
2046         if (fd_src >= 0)
2047                 close(fd_src);
2048         if (fd_dst >= 0)
2049                 close(fd_dst);
2050         if (rc < 0)
2051                 fprintf(stderr, "error: %s: %s: %s: %s\n",
2052                         progname, name, error_loc, strerror(-rc));
2053         return rc;
2054 }
2055
2056 static int mirror_extend(char *fname, struct mirror_args *mirror_list,
2057                          enum mirror_flags mirror_flags,
2058                          unsigned long long bandwidth_bytes_sec,
2059                          enum stats_flag stats_flag, long stats_interval_sec)
2060 {
2061         int rc = 0;
2062
2063         while (mirror_list) {
2064                 if (mirror_list->m_file) {
2065                         rc = mirror_extend_file(fname, mirror_list->m_file,
2066                                                 mirror_flags);
2067                 } else {
2068                         __u32 mirror_count = mirror_list->m_count;
2069
2070                         while (mirror_count > 0) {
2071                                 rc = mirror_extend_layout(fname,
2072                                                         mirror_list->m_layout,
2073                                                         mirror_list->m_inherit,
2074                                                         mirror_list->m_flags,
2075                                                         bandwidth_bytes_sec,
2076                                                         stats_flag,
2077                                                         stats_interval_sec);
2078                                 if (rc)
2079                                         break;
2080
2081                                 --mirror_count;
2082                         }
2083                 }
2084                 if (rc)
2085                         break;
2086
2087                 mirror_list = mirror_list->m_next;
2088         }
2089
2090         return rc;
2091 }
2092
2093 static int find_mirror_id(struct llapi_layout *layout, void *cbdata)
2094 {
2095         uint32_t id;
2096         int rc;
2097
2098         rc = llapi_layout_mirror_id_get(layout, &id);
2099         if (rc < 0)
2100                 return rc;
2101
2102         if ((__u16)id == *(__u16 *)cbdata)
2103                 return LLAPI_LAYOUT_ITER_STOP;
2104
2105         return LLAPI_LAYOUT_ITER_CONT;
2106 }
2107
2108 static int find_comp_id(struct llapi_layout *layout, void *cbdata)
2109 {
2110         uint32_t id;
2111         int rc;
2112
2113         rc = llapi_layout_comp_id_get(layout, &id);
2114         if (rc < 0)
2115                 return rc;
2116
2117         if (id == *(__u32 *)cbdata)
2118                 return LLAPI_LAYOUT_ITER_STOP;
2119
2120         return LLAPI_LAYOUT_ITER_CONT;
2121 }
2122
2123 static int find_mirror_id_by_pool(struct llapi_layout *layout, void *cbdata)
2124 {
2125         char buf[LOV_MAXPOOLNAME + 1];
2126         struct pool_to_id_cbdata *d = (void *)cbdata;
2127         uint32_t id;
2128         int rc;
2129
2130         rc = llapi_layout_pool_name_get(layout, buf, sizeof(buf));
2131         if (rc < 0)
2132                 return rc;
2133         if (strcmp(d->pool, buf))
2134                 return LLAPI_LAYOUT_ITER_CONT;
2135
2136         rc = llapi_layout_mirror_id_get(layout, &id);
2137         if (rc < 0)
2138                 return rc;
2139         d->id = id;
2140
2141         return LLAPI_LAYOUT_ITER_STOP;
2142 }
2143
2144 static int find_comp_id_by_pool(struct llapi_layout *layout, void *cbdata)
2145 {
2146         char buf[LOV_MAXPOOLNAME + 1];
2147         struct pool_to_id_cbdata *d = (void *)cbdata;
2148         uint32_t id;
2149         int rc;
2150
2151         rc = llapi_layout_pool_name_get(layout, buf, sizeof(buf));
2152         if (rc < 0)
2153                 return rc;
2154         if (strcmp(d->pool, buf))
2155                 return LLAPI_LAYOUT_ITER_CONT;
2156
2157         rc = llapi_layout_comp_id_get(layout, &id);
2158         if (rc < 0)
2159                 return rc;
2160         d->id = id;
2161
2162         return LLAPI_LAYOUT_ITER_STOP;
2163 }
2164
2165 struct collect_ids_data {
2166         __u16   *cid_ids;
2167         int     cid_count;
2168         __u16   cid_exclude;
2169 };
2170
2171 static int collect_mirror_id(struct llapi_layout *layout, void *cbdata)
2172 {
2173         struct collect_ids_data *cid = cbdata;
2174         uint32_t id;
2175         int rc;
2176
2177         rc = llapi_layout_mirror_id_get(layout, &id);
2178         if (rc < 0)
2179                 return rc;
2180
2181         if ((__u16)id != cid->cid_exclude) {
2182                 int i;
2183
2184                 for (i = 0; i < cid->cid_count; i++) {
2185                         /* already collected the mirror id */
2186                         if (id == cid->cid_ids[i])
2187                                 return LLAPI_LAYOUT_ITER_CONT;
2188                 }
2189                 cid->cid_ids[cid->cid_count] = id;
2190                 cid->cid_count++;
2191         }
2192
2193         return LLAPI_LAYOUT_ITER_CONT;
2194 }
2195
2196 /**
2197  * last_non_stale_mirror() - Check if a mirror is the last non-stale mirror.
2198  * @mirror_id: Mirror id to be checked.
2199  * @layout:    Mirror component list.
2200  *
2201  * This function checks if a mirror with specified @mirror_id is the last
2202  * non-stale mirror of a layout @layout.
2203  *
2204  * Return: true or false.
2205  */
2206 static inline
2207 bool last_non_stale_mirror(__u16 mirror_id, struct llapi_layout *layout)
2208 {
2209         __u16 mirror_ids[128] = { 0 };
2210         struct collect_ids_data cid = { .cid_ids = mirror_ids,
2211                                         .cid_count = 0,
2212                                         .cid_exclude = mirror_id, };
2213         int i;
2214
2215         llapi_layout_comp_iterate(layout, collect_mirror_id, &cid);
2216
2217         for (i = 0; i < cid.cid_count; i++) {
2218                 struct llapi_resync_comp comp_array[1024] = { { 0 } };
2219                 int comp_size = 0;
2220
2221                 comp_size = llapi_mirror_find_stale(layout, comp_array,
2222                                                     ARRAY_SIZE(comp_array),
2223                                                     &mirror_ids[i], 1);
2224                 if (comp_size == 0)
2225                         return false;
2226         }
2227
2228         return true;
2229 }
2230
2231 static int mirror_split(const char *fname, __u32 id, const char *pool,
2232                         enum mirror_flags mflags, const char *victim_file)
2233 {
2234         struct llapi_layout *layout;
2235         char parent[PATH_MAX];
2236         char victim[PATH_MAX];
2237         int flags = O_CREAT | O_EXCL | O_LOV_DELAY_CREATE | O_NOFOLLOW;
2238         char *ptr;
2239         struct ll_ioc_lease *data;
2240         uint16_t mirror_count;
2241         __u32 mirror_id;
2242         int mdt_index;
2243         int fd, fdv;
2244         bool purge = true; /* delete mirror by setting fdv=fd */
2245         bool is_encrypted;
2246         int rc;
2247
2248         if (victim_file && (strcmp(fname, victim_file) == 0)) {
2249                 fprintf(stderr,
2250                         "error %s: the source file '%s' and -f file are the same\n",
2251                         progname, fname);
2252                 return -EINVAL;
2253         }
2254
2255         /* check fname contains mirror with mirror_id/comp_id */
2256         layout = llapi_layout_get_by_path(fname, 0);
2257         if (!layout) {
2258                 fprintf(stderr,
2259                         "error %s: file '%s' couldn't get layout\n",
2260                         progname, fname);
2261                 return -EINVAL;
2262         }
2263
2264         rc = llapi_layout_sanity(layout, false, true);
2265         if (rc) {
2266                 llapi_layout_sanity_perror(rc);
2267                 goto free_layout;
2268         }
2269
2270         rc = llapi_layout_mirror_count_get(layout, &mirror_count);
2271         if (rc) {
2272                 fprintf(stderr,
2273                         "error %s: file '%s' couldn't get mirror count\n",
2274                         progname, fname);
2275                 goto free_layout;
2276         }
2277         if (mirror_count < 2) {
2278                 fprintf(stderr,
2279                         "error %s: file '%s' has %d component, cannot split\n",
2280                         progname, fname, mirror_count);
2281                 goto free_layout;
2282         }
2283
2284         if (mflags & MF_COMP_POOL) {
2285                 struct pool_to_id_cbdata data = { .pool = pool };
2286
2287                 rc = llapi_layout_comp_iterate(layout, find_mirror_id_by_pool,
2288                                                &data);
2289                 mirror_id = data.id;
2290         } else if (mflags & MF_COMP_ID) {
2291                 rc = llapi_layout_comp_iterate(layout, find_comp_id, &id);
2292                 mirror_id = mirror_id_of(id);
2293         } else {
2294                 rc = llapi_layout_comp_iterate(layout, find_mirror_id, &id);
2295                 mirror_id = id;
2296         }
2297         if (rc < 0) {
2298                 fprintf(stderr, "error %s: failed to iterate layout of '%s'\n",
2299                         progname, fname);
2300                 goto free_layout;
2301         } else if (rc == LLAPI_LAYOUT_ITER_CONT) {
2302                 if (mflags & MF_COMP_POOL) {
2303                         fprintf(stderr,
2304                                 "error %s: file '%s' does not contain mirror with pool '%s'\n",
2305                                 progname, fname, pool);
2306                         goto free_layout;
2307                 } else if (mflags & MF_COMP_ID) {
2308                         fprintf(stderr,
2309                                 "error %s: file '%s' does not contain mirror with comp-id %u\n",
2310                                 progname, fname, id);
2311                         goto free_layout;
2312                 } else {
2313                         fprintf(stderr,
2314                                 "error %s: file '%s' does not contain mirror with id %u\n",
2315                                 progname, fname, id);
2316                         goto free_layout;
2317                 }
2318         }
2319
2320         if (!victim_file && mflags & MF_DESTROY)
2321                 /* Allow mirror split even without the key on encrypted files,
2322                  * and in this case of a 'split -d', open file with O_DIRECT
2323                  * (no IOs will be done).
2324                  */
2325                 fd = open(fname, O_RDWR | O_DIRECT | O_FILE_ENC);
2326         else
2327                 fd = open(fname, O_RDWR);
2328
2329         if (fd < 0) {
2330                 fprintf(stderr,
2331                         "error %s: open file '%s' failed: %s\n",
2332                         progname, fname, strerror(errno));
2333                 goto free_layout;
2334         }
2335
2336         /* get victim file directory pathname */
2337         if (strlen(fname) > sizeof(parent) - 1) {
2338                 fprintf(stderr, "error %s: file name of '%s' too long\n",
2339                         progname, fname);
2340                 rc = -ERANGE;
2341                 goto close_fd;
2342         }
2343         strncpy(parent, fname, sizeof(parent));
2344         ptr = strrchr(parent, '/');
2345         if (!ptr) {
2346                 if (!getcwd(parent, sizeof(parent))) {
2347                         fprintf(stderr, "error %s: getcwd failed: %s\n",
2348                                 progname, strerror(errno));
2349                         rc = -errno;
2350                         goto close_fd;
2351                 }
2352         } else {
2353                 if (ptr == parent)
2354                         ptr = parent + 1;
2355                 *ptr = '\0';
2356         }
2357
2358         rc = llapi_file_fget_mdtidx(fd, &mdt_index);
2359         if (rc < 0) {
2360                 fprintf(stderr, "%s: cannot get MDT index of '%s'\n",
2361                         progname, fname);
2362                 goto close_fd;
2363         }
2364
2365         rc = llapi_file_is_encrypted(fd);
2366         if (rc < 0) {
2367                 fprintf(stderr, "%s: cannot get flags of '%s': %d\n",
2368                         progname, fname, rc);
2369                 goto close_fd;
2370         }
2371         is_encrypted = rc;
2372
2373 again:
2374         if (!victim_file) {
2375                 /* use a temp file to store the splitted layout */
2376                 if (mflags & MF_DESTROY) {
2377                         char file_path[PATH_MAX];
2378                         unsigned int rnumber;
2379                         int open_flags;
2380
2381                         if (last_non_stale_mirror(mirror_id, layout)) {
2382                                 rc = -EUCLEAN;
2383                                 fprintf(stderr,
2384                                         "%s: cannot destroy the last non-stale mirror of file '%s'\n",
2385                                         progname, fname);
2386                                 goto close_fd;
2387                         }
2388
2389                         if (purge) {
2390                                 /* don't use volatile file for mirror destroy */
2391                                 fdv = fd;
2392                         } else {
2393                                 /**
2394                                  * try the old way to delete mirror using
2395                                  * volatile file.
2396                                  */
2397                                 do {
2398                                         rnumber = random();
2399                                         rc = snprintf(file_path,
2400                                                       sizeof(file_path),
2401                                                       "%s/" LUSTRE_VOLATILE_HDR ":%.4X:%.4X:fd=%.2d",
2402                                                       parent, mdt_index,
2403                                                       rnumber, fd);
2404                                         if (rc < 0 ||
2405                                             rc >= sizeof(file_path)) {
2406                                                 fdv = -ENAMETOOLONG;
2407                                                 break;
2408                                         }
2409
2410                                         open_flags = O_RDWR |
2411                                              (O_LOV_DELAY_CREATE & ~O_ACCMODE) |
2412                                              O_CREAT | O_EXCL | O_NOFOLLOW |
2413                                              /* O_DIRECT for mirror split -d */
2414                                              O_DIRECT |
2415                                              /* Allow split without the key */
2416                                              O_FILE_ENC;
2417                                         fdv = open(file_path, open_flags,
2418                                                    S_IRUSR | S_IWUSR);
2419                                         if (fdv < 0)
2420                                                 rc = -errno;
2421                                 } while (fdv < 0 && rc == -EEXIST);
2422                         }
2423                 } else {
2424                         if (is_encrypted) {
2425                                 rc = -1;
2426                                 fprintf(stderr,
2427                                         "error %s: not permitted on encrypted file '%s': %d\n",
2428                                         progname, fname, rc);
2429                                 goto close_fd;
2430                         }
2431
2432                         snprintf(victim, sizeof(victim), "%s.mirror~%u",
2433                                  fname, mirror_id);
2434                         fdv = open(victim, flags, S_IRUSR | S_IWUSR);
2435                 }
2436         } else {
2437                 /* user specified victim file */
2438                 if (is_encrypted) {
2439                         rc = -1;
2440                         fprintf(stderr,
2441                                 "error %s: not permitted on encrypted file '%s': %d\n",
2442                                 progname, fname, rc);
2443                         goto close_fd;
2444                 }
2445                 fdv = open(victim_file, flags, S_IRUSR | S_IWUSR);
2446         }
2447
2448         if (fdv < 0) {
2449                 fprintf(stderr,
2450                         "error %s: create victim file failed: %s\n",
2451                         progname, strerror(errno));
2452                 goto close_fd;
2453         }
2454
2455         /* get lease lock of fname */
2456         rc = llapi_lease_acquire(fd, LL_LEASE_WRLCK);
2457         if (rc < 0) {
2458                 fprintf(stderr,
2459                         "error %s: cannot get lease of file '%s': %d\n",
2460                         progname, fname, rc);
2461                 goto close_victim;
2462         }
2463
2464         /* Atomatically put lease, split layouts and close. */
2465         data = malloc(offsetof(typeof(*data), lil_ids[2]));
2466         if (!data) {
2467                 rc = -ENOMEM;
2468                 goto close_victim;
2469         }
2470
2471         data->lil_mode = LL_LEASE_UNLCK;
2472         data->lil_flags = LL_LEASE_LAYOUT_SPLIT;
2473         data->lil_count = 2;
2474         data->lil_ids[0] = fdv;
2475         data->lil_ids[1] = mirror_id;
2476         rc = llapi_lease_set(fd, data);
2477         if (rc <= 0) {
2478                 if ((rc == -EINVAL || rc == -EBUSY) && purge) {
2479                         /* could be old MDS which prohibit fd==fdv */
2480                         purge = false;
2481                         goto again;
2482
2483                 }
2484                 if (rc == 0) /* lost lease lock */
2485                         rc = -EBUSY;
2486                 fprintf(stderr,
2487                         "error %s: cannot split '%s': %s\n",
2488                         progname, fname, strerror(-rc));
2489         } else {
2490                 rc = 0;
2491         }
2492         free(data);
2493
2494 close_victim:
2495         if (!purge)
2496                 close(fdv);
2497 close_fd:
2498         close(fd);
2499 free_layout:
2500         llapi_layout_free(layout);
2501         return rc;
2502 }
2503
2504 static inline
2505 int lfs_mirror_resync_file(const char *fname, struct ll_ioc_lease *ioc,
2506                            __u16 *mirror_ids, int ids_nr);
2507
2508 static int lfs_migrate_to_dom(int fd_src, int fd_dst, char *name,
2509                               __u64 migration_flags,
2510                               unsigned long long bandwidth_bytes_sec,
2511                               enum stats_flag stats_flag,
2512                               long stats_interval_sec)
2513 {
2514         struct ll_ioc_lease *data = NULL;
2515         int rc;
2516
2517         rc = llapi_lease_acquire(fd_src, LL_LEASE_RDLCK);
2518         if (rc < 0) {
2519                 error_loc = "cannot get lease";
2520                 goto out_close;
2521         }
2522
2523         if (stats_flag)
2524                 printf("%s:\n", name);
2525
2526         rc = migrate_nonblock(fd_src, fd_dst, bandwidth_bytes_sec, stats_flag,
2527                               stats_interval_sec);
2528         if (rc < 0)
2529                 goto out_release;
2530
2531         /* Atomically put lease, merge layouts, resync and close. */
2532         data = calloc(1, offsetof(typeof(*data), lil_ids[1]));
2533         if (!data) {
2534                 error_loc = "memory allocation";
2535                 goto out_release;
2536         }
2537         data->lil_mode = LL_LEASE_UNLCK;
2538         data->lil_flags = LL_LEASE_LAYOUT_MERGE;
2539         data->lil_count = 1;
2540         data->lil_ids[0] = fd_dst;
2541         rc = llapi_lease_set(fd_src, data);
2542         if (rc < 0) {
2543                 error_loc = "cannot merge layout";
2544                 goto out_close;
2545         } else if (rc == 0) {
2546                 rc = -EBUSY;
2547                 error_loc = "lost lease lock";
2548                 goto out_close;
2549         }
2550         close(fd_src);
2551         close(fd_dst);
2552
2553         rc = lfs_mirror_resync_file(name, data, NULL, 0);
2554         if (rc) {
2555                 error_loc = "cannot resync file";
2556                 goto out;
2557         }
2558
2559         /* delete first mirror now */
2560         rc = mirror_split(name, 1, NULL, MF_DESTROY, NULL);
2561         if (rc < 0)
2562                 error_loc = "cannot delete old layout";
2563         goto out;
2564
2565 out_release:
2566         llapi_lease_release(fd_src);
2567 out_close:
2568         close(fd_src);
2569         close(fd_dst);
2570 out:
2571         if (rc < 0)
2572                 fprintf(stderr, "error: %s: %s: %s: %s\n",
2573                         progname, name, error_loc, strerror(-rc));
2574         else if (migration_flags & LLAPI_MIGRATION_VERBOSE)
2575                 printf("%s\n", name);
2576         if (data)
2577                 free(data);
2578         return rc;
2579 }
2580
2581 /**
2582  * Parse a string containing an target index list into an array of integers.
2583  *
2584  * The input string contains a comma delimited list of individual
2585  * indices and ranges, for example "1,2-4,7". Add the indices into the
2586  * \a tgts array and remove duplicates.
2587  *
2588  * \param[out] tgts             array to store indices in
2589  * \param[in] size              size of \a tgts array
2590  * \param[in] offset            starting index in \a tgts
2591  * \param[in] arg               string containing OST index list
2592  * \param[in/out] overstriping  index list may contain duplicates
2593  *
2594  * \retval positive    number of indices in \a tgts
2595  * \retval -EINVAL     unable to parse \a arg
2596  */
2597 static int parse_targets(__u32 *tgts, int size, int offset, char *arg,
2598                          unsigned long long *pattern)
2599 {
2600         int rc;
2601         int nr = offset;
2602         int slots = size - offset;
2603         char *ptr = NULL;
2604         bool overstriped = false;
2605         bool end_of_loop;
2606
2607         if (!arg)
2608                 return -EINVAL;
2609
2610         end_of_loop = false;
2611         while (!end_of_loop) {
2612                 int start_index = 0;
2613                 int end_index = 0;
2614                 int i;
2615                 char *endptr = NULL;
2616
2617                 rc = -EINVAL;
2618
2619                 ptr = strchrnul(arg, ',');
2620
2621                 end_of_loop = *ptr == '\0';
2622                 *ptr = '\0';
2623
2624                 errno = 0;
2625                 start_index = strtol(arg, &endptr, 0);
2626                 if (endptr == arg) /* no data at all */
2627                         break;
2628                 if (errno != 0 || start_index < -1 ||
2629                     (*endptr != '-' && *endptr != '\0'))
2630                         break;
2631
2632                 end_index = start_index;
2633                 if (*endptr == '-') {
2634                         errno = 0;
2635                         end_index = strtol(endptr + 1, &endptr, 0);
2636                         if (errno != 0 || *endptr != '\0' || end_index < -1)
2637                                 break;
2638                         if (end_index < start_index)
2639                                 break;
2640                 }
2641
2642                 for (i = start_index; i <= end_index && slots > 0; i++) {
2643                         int j;
2644
2645                         /* remove duplicate */
2646                         for (j = 0; j < offset; j++) {
2647                                 if (tgts[j] == i && pattern &&
2648                                     *pattern == LLAPI_LAYOUT_OVERSTRIPING)
2649                                         overstriped = true;
2650                                 else if (tgts[j] == i)
2651                                         return -EINVAL;
2652                         }
2653
2654                         j = offset;
2655
2656                         if (j == offset) { /* check complete */
2657                                 tgts[nr++] = i;
2658                                 --slots;
2659                         }
2660                 }
2661
2662                 if (slots == 0 && i < end_index)
2663                         break;
2664
2665                 *ptr = ',';
2666                 arg = ++ptr;
2667                 offset = nr;
2668                 rc = 0;
2669         }
2670         if (!end_of_loop && ptr)
2671                 *ptr = ',';
2672
2673         if (!overstriped && pattern)
2674                 *pattern = LLAPI_LAYOUT_DEFAULT;
2675
2676         return rc < 0 ? rc : nr;
2677 }
2678
2679 struct lfs_setstripe_args {
2680         unsigned long long       lsa_comp_end;
2681         unsigned long long       lsa_stripe_size;
2682         unsigned long long       lsa_extension_size;
2683         long long                lsa_stripe_count;
2684         long long                lsa_stripe_off;
2685         __u32                    lsa_comp_flags;
2686         __u32                    lsa_comp_neg_flags;
2687         unsigned long long       lsa_pattern;
2688         unsigned int             lsa_mirror_count;
2689         int                      lsa_nr_tgts;
2690         bool                     lsa_first_comp;
2691         bool                     lsa_extension_comp;
2692         __u32                   *lsa_tgts;
2693         char                    *lsa_pool_name;
2694 };
2695
2696 static inline void setstripe_args_init(struct lfs_setstripe_args *lsa)
2697 {
2698         unsigned int mirror_count = lsa->lsa_mirror_count;
2699         bool first_comp = lsa->lsa_first_comp;
2700
2701         memset(lsa, 0, sizeof(*lsa));
2702
2703         lsa->lsa_stripe_size = LLAPI_LAYOUT_DEFAULT;
2704         lsa->lsa_stripe_count = LLAPI_LAYOUT_DEFAULT;
2705         lsa->lsa_stripe_off = LLAPI_LAYOUT_DEFAULT;
2706         lsa->lsa_pattern = LLAPI_LAYOUT_RAID0;
2707         lsa->lsa_pool_name = NULL;
2708
2709         lsa->lsa_mirror_count = mirror_count;
2710         lsa->lsa_first_comp = first_comp;
2711 }
2712
2713 /**
2714  * setstripe_args_init_inherit() - Initialize and inherit stripe options.
2715  * @lsa: Stripe options to be initialized and inherited.
2716  *
2717  * This function initializes stripe options in @lsa and inherit
2718  * stripe_size, stripe_count and OST pool_name options.
2719  *
2720  * Return: void.
2721  */
2722 static inline void setstripe_args_init_inherit(struct lfs_setstripe_args *lsa)
2723 {
2724         unsigned long long stripe_size;
2725         long long stripe_count;
2726         char *pool_name = NULL;
2727
2728         stripe_size = lsa->lsa_stripe_size;
2729         stripe_count = lsa->lsa_stripe_count;
2730         pool_name = lsa->lsa_pool_name;
2731
2732         setstripe_args_init(lsa);
2733
2734         lsa->lsa_stripe_size = stripe_size;
2735         lsa->lsa_stripe_count = stripe_count;
2736         lsa->lsa_pool_name = pool_name;
2737 }
2738
2739 static inline bool setstripe_args_specified(struct lfs_setstripe_args *lsa)
2740 {
2741         return (lsa->lsa_stripe_size != LLAPI_LAYOUT_DEFAULT ||
2742                 lsa->lsa_stripe_count != LLAPI_LAYOUT_DEFAULT ||
2743                 lsa->lsa_stripe_off != LLAPI_LAYOUT_DEFAULT ||
2744                 lsa->lsa_pattern != LLAPI_LAYOUT_RAID0 ||
2745                 lsa->lsa_comp_end != 0);
2746 }
2747
2748 static int lsa_args_stripe_count_check(struct lfs_setstripe_args *lsa)
2749 {
2750         if (lsa->lsa_nr_tgts) {
2751                 if (lsa->lsa_nr_tgts < 0 ||
2752                     lsa->lsa_nr_tgts >= LOV_MAX_STRIPE_COUNT) {
2753                         fprintf(stderr, "Invalid nr_tgts(%d)\n",
2754                                 lsa->lsa_nr_tgts);
2755                         errno = EINVAL;
2756                         return -1;
2757                 }
2758
2759                 if (lsa->lsa_stripe_count > 0 &&
2760                     lsa->lsa_stripe_count != LLAPI_LAYOUT_DEFAULT &&
2761                     lsa->lsa_stripe_count != LLAPI_LAYOUT_WIDE &&
2762                     lsa->lsa_nr_tgts != lsa->lsa_stripe_count) {
2763                         fprintf(stderr, "stripe_count(%lld) != nr_tgts(%d)\n",
2764                                 lsa->lsa_stripe_count,
2765                                 lsa->lsa_nr_tgts);
2766                         errno = EINVAL;
2767                         return -1;
2768                 }
2769         }
2770
2771         return 0;
2772
2773 }
2774
2775 /**
2776  * comp_args_to_layout() - Create or extend a composite layout.
2777  * @composite:       Pointer to the composite layout.
2778  * @lsa:             Stripe options for the new component.
2779  *
2780  * This function creates or extends a composite layout by adding a new
2781  * component with stripe options from @lsa.
2782  *
2783  * When modified, adjust llapi_stripe_param_verify() if needed as well.
2784  *
2785  * Return: 0 on success or an error code on failure.
2786  */
2787 static int comp_args_to_layout(struct llapi_layout **composite,
2788                                struct lfs_setstripe_args *lsa,
2789                                bool set_extent)
2790 {
2791         struct llapi_layout *layout = *composite;
2792         uint64_t prev_end = 0;
2793         uint64_t size;
2794         int i = 0, rc;
2795
2796 new_comp:
2797         if (!layout) {
2798                 layout = llapi_layout_alloc();
2799                 if (!layout) {
2800                         fprintf(stderr, "Alloc llapi_layout failed. %s\n",
2801                                 strerror(errno));
2802                         errno = ENOMEM;
2803                         return -1;
2804                 }
2805                 *composite = layout;
2806                 lsa->lsa_first_comp = true;
2807         } else {
2808                 uint64_t start;
2809
2810                 /*
2811                  * Get current component extent, current component
2812                  * must be the tail component.
2813                  */
2814                 rc = llapi_layout_comp_extent_get(layout, &start, &prev_end);
2815                 if (rc) {
2816                         fprintf(stderr, "Get comp extent failed. %s\n",
2817                                 strerror(errno));
2818                         return rc;
2819                 }
2820
2821                 if (lsa->lsa_first_comp) {
2822                         prev_end = 0;
2823                         rc = llapi_layout_add_first_comp(layout);
2824                 } else {
2825                         rc = llapi_layout_comp_add(layout);
2826                 }
2827                 if (rc) {
2828                         fprintf(stderr, "Add component failed. %s\n",
2829                                 strerror(errno));
2830                         return rc;
2831                 }
2832         }
2833
2834         rc = llapi_layout_comp_flags_set(layout, lsa->lsa_comp_flags);
2835         if (rc) {
2836                 fprintf(stderr, "Set flags 0x%x failed: %s\n",
2837                         lsa->lsa_comp_flags, strerror(errno));
2838                 return rc;
2839         }
2840
2841         if (set_extent) {
2842                 uint64_t comp_end = lsa->lsa_comp_end;
2843
2844                 /*
2845                  * The extendable component is 0-length, so it can be removed
2846                  * if there is insufficient space to extend it.
2847                  */
2848                 if (lsa->lsa_extension_comp)
2849                         comp_end = prev_end;
2850
2851                 rc = llapi_layout_comp_extent_set(layout, prev_end,
2852                                                   comp_end);
2853                 if (rc) {
2854                         fprintf(stderr, "Set extent [%lu, %lu) failed. %s\n",
2855                                 prev_end, comp_end, strerror(errno));
2856                         return rc;
2857                 }
2858         }
2859         /* reset lsa_first_comp */
2860         lsa->lsa_first_comp = false;
2861
2862         /* Data-on-MDT component setting */
2863         if (lsa->lsa_pattern == LLAPI_LAYOUT_MDT) {
2864                 /* Yaml support */
2865                 if (lsa->lsa_stripe_count == 0)
2866                         lsa->lsa_stripe_count = LLAPI_LAYOUT_DEFAULT;
2867                 if (lsa->lsa_stripe_size == lsa->lsa_comp_end)
2868                         lsa->lsa_stripe_size = LLAPI_LAYOUT_DEFAULT;
2869                 if (lsa->lsa_stripe_off == -1 ||
2870                     lsa->lsa_stripe_off == 0)
2871                         lsa->lsa_stripe_off = LLAPI_LAYOUT_DEFAULT;
2872                 /*
2873                  * In case of Data-on-MDT patterns the only extra option
2874                  * applicable is stripe size option.
2875                  */
2876                 if (lsa->lsa_stripe_count != LLAPI_LAYOUT_DEFAULT) {
2877                         fprintf(stderr,
2878                                 "Option 'stripe-count' can't be specified with Data-on-MDT component: %lld\n",
2879                                 lsa->lsa_stripe_count);
2880                         errno = EINVAL;
2881                         return -1;
2882                 }
2883                 if (lsa->lsa_stripe_size != LLAPI_LAYOUT_DEFAULT &&
2884                     lsa->lsa_stripe_size != lsa->lsa_comp_end - prev_end) {
2885                         fprintf(stderr,
2886                                 "Option 'stripe-size' can't be specified with Data-on-MDT component: %llu\n",
2887                                 lsa->lsa_stripe_size);
2888                         errno = EINVAL;
2889                         return -1;
2890                 }
2891                 if (lsa->lsa_nr_tgts != 0) {
2892                         fprintf(stderr,
2893                                 "Option 'ost-list' can't be specified with Data-on-MDT component: '%i'\n",
2894                                 lsa->lsa_nr_tgts);
2895                         errno = EINVAL;
2896                         return -1;
2897                 }
2898                 if (lsa->lsa_stripe_off != LLAPI_LAYOUT_DEFAULT) {
2899                         fprintf(stderr,
2900                                 "Option 'stripe-offset' can't be specified with Data-on-MDT component: %lld\n",
2901                                 lsa->lsa_stripe_off);
2902                         errno = EINVAL;
2903                         return -1;
2904                 }
2905                 if (lsa->lsa_pool_name != 0) {
2906                         fprintf(stderr,
2907                                 "Option 'pool' can't be specified with Data-on-MDT component: '%s'\n",
2908                                 lsa->lsa_pool_name);
2909                         errno = EINVAL;
2910                         return -1;
2911                 }
2912
2913                 rc = llapi_layout_pattern_set(layout, lsa->lsa_pattern);
2914                 if (rc) {
2915                         fprintf(stderr, "Set stripe pattern %#llx failed. %s\n",
2916                                 lsa->lsa_pattern,
2917                                 strerror(errno));
2918                         return rc;
2919                 }
2920                 /* Data-on-MDT component has always single stripe up to end */
2921                 lsa->lsa_stripe_size = lsa->lsa_comp_end;
2922         } else if (lsa->lsa_pattern == LLAPI_LAYOUT_OVERSTRIPING) {
2923                 rc = llapi_layout_pattern_set(layout, lsa->lsa_pattern);
2924                 if (rc) {
2925                         fprintf(stderr, "Set stripe pattern %#llx failed. %s\n",
2926                                 lsa->lsa_pattern,
2927                                 strerror(errno));
2928                         return rc;
2929                 }
2930         }
2931
2932         size = lsa->lsa_comp_flags & LCME_FL_EXTENSION ?
2933                 lsa->lsa_extension_size : lsa->lsa_stripe_size;
2934
2935         if (lsa->lsa_comp_flags & LCME_FL_EXTENSION)
2936                 rc = llapi_layout_extension_size_set(layout, size);
2937         else
2938                 rc = llapi_layout_stripe_size_set(layout, size);
2939
2940         if (rc) {
2941                 fprintf(stderr, "Set stripe size %lu failed: %s\n",
2942                         size, strerror(errno));
2943                 return rc;
2944         }
2945
2946         rc = llapi_layout_stripe_count_set(layout, lsa->lsa_stripe_count);
2947         if (rc) {
2948                 fprintf(stderr, "Set stripe count %lld failed: %s\n",
2949                         lsa->lsa_stripe_count, strerror(errno));
2950                 return rc;
2951         }
2952
2953         if (lsa->lsa_pool_name) {
2954                 rc = llapi_layout_pool_name_set(layout, lsa->lsa_pool_name);
2955                 if (rc) {
2956                         fprintf(stderr, "Set pool name: %s failed. %s\n",
2957                                 lsa->lsa_pool_name, strerror(errno));
2958                         return rc;
2959                 }
2960         } else {
2961                 rc = llapi_layout_pool_name_set(layout, "");
2962                 if (rc) {
2963                         fprintf(stderr, "Clear pool name failed: %s\n",
2964                                 strerror(errno));
2965                         return rc;
2966                 }
2967         }
2968
2969         rc = lsa_args_stripe_count_check(lsa);
2970         if (rc)
2971                 return rc;
2972
2973         if (lsa->lsa_nr_tgts > 0) {
2974                 bool found = false;
2975
2976                 for (i = 0; i < lsa->lsa_nr_tgts; i++) {
2977                         rc = llapi_layout_ost_index_set(layout, i,
2978                                                         lsa->lsa_tgts[i]);
2979                         if (rc)
2980                                 break;
2981
2982                         /* Make sure stripe offset is in OST list. */
2983                         if (lsa->lsa_tgts[i] == lsa->lsa_stripe_off)
2984                                 found = true;
2985                 }
2986                 if (!found) {
2987                         fprintf(stderr, "Invalid stripe offset '%lld', not in the target list",
2988                                 lsa->lsa_stripe_off);
2989                         errno = EINVAL;
2990                         return -1;
2991                 }
2992         } else if (lsa->lsa_stripe_off != LLAPI_LAYOUT_DEFAULT &&
2993                    lsa->lsa_stripe_off != -1) {
2994                 rc = llapi_layout_ost_index_set(layout, 0, lsa->lsa_stripe_off);
2995         }
2996         if (rc) {
2997                 fprintf(stderr, "Set ost index %d failed. %s\n",
2998                         i, strerror(errno));
2999                 return rc;
3000         }
3001
3002         /* Create the second, virtual component of extension space */
3003         if (lsa->lsa_extension_comp) {
3004                 lsa->lsa_comp_flags |= LCME_FL_EXTENSION;
3005                 lsa->lsa_extension_comp = false;
3006                 goto new_comp;
3007         }
3008
3009         return rc;
3010 }
3011
3012 static int build_component(struct llapi_layout **layout,
3013                            struct lfs_setstripe_args *lsa, bool set_extent)
3014 {
3015         int rc;
3016
3017         rc = comp_args_to_layout(layout, lsa, set_extent);
3018         if (rc)
3019                 return rc;
3020
3021         if (lsa->lsa_mirror_count > 0) {
3022                 rc = llapi_layout_mirror_count_set(*layout,
3023                                                    lsa->lsa_mirror_count);
3024                 if (rc)
3025                         return rc;
3026
3027                 rc = llapi_layout_flags_set(*layout, LCM_FL_RDONLY);
3028                 if (rc)
3029                         return rc;
3030                 lsa->lsa_mirror_count = 0;
3031         }
3032
3033         return rc;
3034 }
3035
3036 static int build_prev_component(struct llapi_layout **layout,
3037                                 struct lfs_setstripe_args *prev,
3038                                 struct lfs_setstripe_args *lsa,
3039                                 bool set_extent)
3040 {
3041         int extension = lsa->lsa_comp_flags & LCME_FL_EXTENSION;
3042         int rc;
3043
3044         if (prev->lsa_stripe_size) {
3045                 if (extension) {
3046                         prev->lsa_comp_end = lsa->lsa_comp_end;
3047                         prev->lsa_extension_size = lsa->lsa_extension_size;
3048                         prev->lsa_extension_comp = true;
3049                 }
3050
3051                 rc = build_component(layout, prev, true);
3052                 if (rc)
3053                         return rc;
3054         }
3055
3056         /*
3057          * Copy lsa to previous lsa;
3058          * if this is an extension component, make the previous invalid;
3059          */
3060         if (extension)
3061                 prev->lsa_stripe_size = 0;
3062         else
3063                 *prev = *lsa;
3064
3065         return 0;
3066 }
3067
3068 #ifndef LCME_TEMPLATE_FLAGS
3069 #define LCME_TEMPLATE_FLAGS     (LCME_FL_PREF_RW | LCME_FL_NOSYNC | \
3070                                  LCME_FL_EXTENSION)
3071 #endif
3072
3073 static int build_layout_from_yaml_node(struct cYAML *node,
3074                                        struct llapi_layout **layout,
3075                                        struct lfs_setstripe_args *lsa,
3076                                        struct lfs_setstripe_args *prevp)
3077 {
3078         struct lfs_setstripe_args prev = { 0 };
3079         __u32 *osts = lsa->lsa_tgts;
3080         char *string;
3081         int rc = 0;
3082
3083         if (!prevp)
3084                 prevp = &prev;
3085
3086         while (node) {
3087                 string = node->cy_string;
3088
3089                 if (node->cy_type == CYAML_TYPE_OBJECT) {
3090                         /* go deep to sub blocks */
3091                         if (string && !strncmp(string, "component", 9) &&
3092                             strncmp(string, "component0", 10) &&
3093                             strncmp(string, "components", 10)) {
3094                                 rc = build_prev_component(layout, prevp, lsa,
3095                                                           true);
3096                                 if (rc)
3097                                         return rc;
3098
3099                                 /* initialize lsa. */
3100                                 setstripe_args_init(lsa);
3101                                 lsa->lsa_first_comp = false;
3102                                 lsa->lsa_tgts = osts;
3103                         }
3104
3105                         rc = build_layout_from_yaml_node(node->cy_child, layout,
3106                                                          lsa, prevp);
3107                         if (rc)
3108                                 return rc;
3109                 } else {
3110                         if (!node->cy_string)
3111                                 return -EINVAL;
3112
3113                         /* skip leading lmm_ if present, to simplify parsing */
3114                         if (strncmp(string, "lmm_", 4) == 0)
3115                                 string += 4;
3116
3117                         if (node->cy_type == CYAML_TYPE_STRING) {
3118                                 if (!strcmp(string, "lcme_extent.e_end")) {
3119                                         if (!strcmp(node->cy_valuestring, "EOF") ||
3120                                             !strcmp(node->cy_valuestring, "eof"))
3121                                                 lsa->lsa_comp_end = LUSTRE_EOF;
3122                                 } else if (!strcmp(string, "pool")) {
3123                                         lsa->lsa_pool_name = node->cy_valuestring;
3124                                 } else if (!strcmp(string, "pattern")) {
3125                                         if (!strcmp(node->cy_valuestring, "mdt"))
3126                                                 lsa->lsa_pattern = LLAPI_LAYOUT_MDT;
3127                                         if (!strcmp(node->cy_valuestring,
3128                                                     "raid0,overstriped"))
3129                                                 lsa->lsa_pattern =
3130                                                         LLAPI_LAYOUT_OVERSTRIPING;
3131                                 } else if (!strcmp(string, "lcme_flags")) {
3132                                         rc = comp_str2flags(node->cy_valuestring,
3133                                                             &lsa->lsa_comp_flags,
3134                                                             &lsa->lsa_comp_neg_flags);
3135                                         if (rc)
3136                                                 return rc;
3137                                         /*
3138                                          * Only template flags have meaning in
3139                                          * the layout for a new file
3140                                          */
3141                                         lsa->lsa_comp_flags &= LCME_TEMPLATE_FLAGS;
3142                                 }
3143                         } else if (node->cy_type == CYAML_TYPE_NUMBER) {
3144                                 if (!strcmp(string, "lcm_mirror_count")) {
3145                                         lsa->lsa_mirror_count = node->cy_valueint;
3146                                 } else if (!strcmp(string, "lcme_extent.e_start")) {
3147                                         if (node->cy_valueint == 0)
3148                                                 lsa->lsa_first_comp = true;
3149                                 } else if (!strcmp(string, "lcme_extent.e_end")) {
3150                                         if (node->cy_valueint == -1)
3151                                                 lsa->lsa_comp_end = LUSTRE_EOF;
3152                                         else
3153                                                 lsa->lsa_comp_end = node->cy_valueint;
3154                                 } else if (!strcmp(string, "stripe_count")) {
3155                                         lsa->lsa_stripe_count = node->cy_valueint;
3156                                 } else if (!strcmp(string, "stripe_size")) {
3157                                         lsa->lsa_stripe_size = node->cy_valueint;
3158                                 } else if (!strcmp(string, "extension_size")) {
3159                                         lsa->lsa_extension_size = node->cy_valueint;
3160                                         lsa->lsa_extension_comp = true;
3161                                 } else if (!strcmp(string, "stripe_offset")) {
3162                                         lsa->lsa_stripe_off = node->cy_valueint;
3163                                 } else if (!strcmp(string, "l_ost_idx")) {
3164                                         osts[lsa->lsa_nr_tgts] = node->cy_valueint;
3165                                         lsa->lsa_nr_tgts++;
3166                                 }
3167                         }
3168                 }
3169                 node = node->cy_next;
3170         }
3171
3172         if (prevp == &prev) {
3173                 rc = build_prev_component(layout, prevp, lsa, true);
3174                 if (rc)
3175                         return rc;
3176
3177                 if (!(lsa->lsa_comp_flags & LCME_FL_EXTENSION))
3178                         rc = build_component(layout, lsa, *layout != NULL);
3179         }
3180
3181         return rc;
3182 }
3183
3184 static int lfs_comp_create_from_yaml(char *template,
3185                                      struct llapi_layout **layout,
3186                                      struct lfs_setstripe_args *lsa,
3187                                      __u32 *osts)
3188 {
3189         struct cYAML *tree = NULL, *err_rc = NULL;
3190         int rc = 0;
3191
3192         tree = cYAML_build_tree(template, NULL, 0, &err_rc, false);
3193         if (!tree) {
3194                 fprintf(stderr, "%s: cannot parse YAML file %s\n",
3195                         progname, template);
3196                 cYAML_build_error(-EINVAL, -1, "yaml", "from comp yaml",
3197                                   "can't parse", &err_rc);
3198                 cYAML_print_tree2file(stderr, err_rc);
3199                 cYAML_free_tree(err_rc);
3200                 rc = -EINVAL;
3201                 goto err;
3202         }
3203
3204         /* initialize lsa for plain file */
3205         setstripe_args_init(lsa);
3206         lsa->lsa_tgts = osts;
3207
3208         rc = build_layout_from_yaml_node(tree, layout, lsa, NULL);
3209         if (rc) {
3210                 fprintf(stderr, "%s: cannot build layout from YAML file %s.\n",
3211                         progname, template);
3212                 goto err;
3213         }
3214         /* clean clean lsa */
3215         setstripe_args_init(lsa);
3216
3217 err:
3218         if (tree)
3219                 cYAML_free_tree(tree);
3220         return rc;
3221 }
3222
3223 /**
3224  * Get the extension size from the next (SEL) component and extend the
3225  * current component on it. The start of the next component is to be
3226  * adjusted as well.
3227  *
3228  * \param[in] layout    the current layout
3229  * \param[in] start     the start of the current component
3230  * \param[in,out] end   the end of the current component
3231  * \param[in] offset    the offset to adjust the end position to instead of
3232  *                      extension size
3233  *
3234  * \retval 0            - extended successfully
3235  * \retval < 0          - error
3236  */
3237 static int layout_extend_comp(struct llapi_layout *layout,
3238                               uint64_t start, uint64_t *end,
3239                               uint64_t offset)
3240 {
3241         uint64_t size, next_start, next_end;
3242         int rc;
3243
3244         rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_NEXT);
3245         if (rc < 0) {
3246                 fprintf(stderr,
3247                         "%s setstripe: cannot move component cursor: %s\n",
3248                         progname, strerror(errno));
3249                 return rc;
3250         }
3251
3252         /*
3253          * Even if the @size will not be used below, this will fail if
3254          * this is not a SEL component - a good confirmation we are
3255          * working on right components.
3256          */
3257         rc = llapi_layout_extension_size_get(layout, &size);
3258         if (rc < 0) {
3259                 fprintf(stderr,
3260                         "%s setstripe: cannot get component ext size: %s\n",
3261                         progname, strerror(errno));
3262                 return rc;
3263         }
3264
3265         rc = llapi_layout_comp_extent_get(layout, &next_start, &next_end);
3266         if (rc) {
3267                 fprintf(stderr, "%s setstripe: cannot get extent: %s\n",
3268                         progname, strerror(errno));
3269                 return rc;
3270         }
3271
3272         next_start += offset ?: size;
3273         rc = llapi_layout_comp_extent_set(layout, next_start, next_end);
3274         if (rc) {
3275                 fprintf(stderr, "%s setstripe: cannot set extent: %s\n",
3276                         progname, strerror(errno));
3277                 return rc;
3278         }
3279
3280         rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_PREV);
3281         if (rc < 0) {
3282                 fprintf(stderr,
3283                         "%s setstripe: cannot move component cursor: %s\n",
3284                         progname, strerror(errno));
3285                 return rc;
3286         }
3287
3288         *end += offset ?: size;
3289         rc = llapi_layout_comp_extent_set(layout, start, *end);
3290         if (rc) {
3291                 fprintf(stderr, "%s setstripe: cannot set extent: %s\n",
3292                         progname, strerror(errno));
3293                 return rc;
3294         }
3295
3296         return 0;
3297 }
3298
3299 /**
3300  * In 'lfs setstripe --component-add' mode, we need to fetch the extent
3301  * end of the last component in the existing file, and adjust the
3302  * first extent start of the components to be added accordingly.
3303  *
3304  * In the create mode, we need to check if the first component is an extendable
3305  * SEL component and extend its length to the extension size (first component
3306  * of the PFL file is initialised at the create time, cannot be 0-lenght.
3307  */
3308 static int layout_adjust_first_extent(char *fname, struct llapi_layout *layout,
3309                                       bool comp_add)
3310 {
3311         struct llapi_layout *head;
3312         uint64_t start = 0, prev_end = 0;
3313         uint64_t end;
3314         int rc, ret = 0;
3315
3316         if (!layout || !(comp_add || llapi_layout_is_composite(layout)))
3317                 return 0;
3318
3319         errno = 0;
3320         while (comp_add) {
3321                 head = llapi_layout_get_by_path(fname, 0);
3322                 if (!head) {
3323                         fprintf(stderr,
3324                                 "%s setstripe: cannot read layout from '%s': %s\n",
3325                                 progname, fname, strerror(errno));
3326                         return -EINVAL;
3327                 } else if (errno == ENODATA) {
3328                         /*
3329                          * file without LOVEA, this component-add will be turned
3330                          * into a component-create.
3331                          */
3332                         llapi_layout_free(head);
3333                         ret = -ENODATA;
3334
3335                         /*
3336                          * the new layout will be added to an empty one, it
3337                          * still needs to be adjusted below
3338                          */
3339                         comp_add = 0;
3340                         break;
3341                 } else if (!llapi_layout_is_composite(head)) {
3342                         fprintf(stderr,
3343                                 "%s setstripe: '%s' not a composite file\n",
3344                                 progname, fname);
3345                         llapi_layout_free(head);
3346                         return -EINVAL;
3347                 }
3348
3349                 rc = llapi_layout_comp_extent_get(head, &start, &prev_end);
3350                 if (rc) {
3351                         fprintf(stderr,
3352                                 "%s setstripe: cannot get prev extent: %s\n",
3353                                 progname, strerror(errno));
3354                         llapi_layout_free(head);
3355                         return rc;
3356                 }
3357
3358                 llapi_layout_free(head);
3359                 break;
3360         }
3361
3362         /* Make sure we use the first component of the layout to be added. */
3363         rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_FIRST);
3364         if (rc < 0) {
3365                 fprintf(stderr,
3366                         "%s setstripe: cannot move component cursor: %s\n",
3367                         progname, strerror(errno));
3368                 return rc;
3369         }
3370
3371         rc = llapi_layout_comp_extent_get(layout, &start, &end);
3372         if (rc) {
3373                 fprintf(stderr, "%s setstripe: cannot get extent: %s\n",
3374                         progname, strerror(errno));
3375                 return rc;
3376         }
3377
3378         if (start == 0 && end == 0) {
3379                 rc = layout_extend_comp(layout, start, &end,
3380                                         comp_add ? prev_end : 0);
3381                 if (rc)
3382                         return rc;
3383         }
3384
3385         if (start > prev_end || end < prev_end) {
3386                 fprintf(stderr,
3387                         "%s setstripe: first extent [%lu, %lu) not adjacent with extent end %lu\n",
3388                         progname, start, end, prev_end);
3389                 return -EINVAL;
3390         }
3391
3392         rc = llapi_layout_comp_extent_set(layout, prev_end, end);
3393         if (rc) {
3394                 fprintf(stderr,
3395                         "%s setstripe: cannot set component extent [%lu, %lu): %s\n",
3396                         progname, prev_end, end, strerror(errno));
3397                 return rc;
3398         }
3399
3400         return ret;
3401 }
3402
3403 static int mirror_adjust_first_extents(struct mirror_args *list)
3404 {
3405         int rc = 0;
3406
3407         if (!list)
3408                 return 0;
3409
3410         while (list) {
3411                 rc = layout_adjust_first_extent(NULL, list->m_layout, false);
3412                 if (rc)
3413                         break;
3414                 list = list->m_next;
3415         }
3416
3417         return rc;
3418 }
3419
3420 static inline bool arg_is_eof(char *arg)
3421 {
3422         return !strncmp(arg, "-1", strlen("-1")) ||
3423                !strncmp(arg, "EOF", strlen("EOF")) ||
3424                !strncmp(arg, "eof", strlen("eof"));
3425 }
3426
3427 /**
3428  * lfs_mirror_alloc() - Allocate a mirror argument structure.
3429  *
3430  * Return: Valid mirror_args pointer on success and
3431  *         NULL if memory allocation fails.
3432  */
3433 static struct mirror_args *lfs_mirror_alloc(void)
3434 {
3435         struct mirror_args *mirror = NULL;
3436
3437         while (1) {
3438                 mirror = calloc(1, sizeof(*mirror));
3439                 if (mirror) {
3440                         mirror->m_inherit = false;
3441                         break;
3442                 }
3443
3444                 sleep(1);
3445         }
3446
3447         return mirror;
3448 }
3449
3450 /**
3451  * lfs_mirror_free() - Free memory allocated for a mirror argument
3452  *                     structure.
3453  * @mirror: Previously allocated mirror argument structure by
3454  *          lfs_mirror_alloc().
3455  *
3456  * Free memory allocated for @mirror.
3457  *
3458  * Return: void.
3459  */
3460 static void lfs_mirror_free(struct mirror_args *mirror)
3461 {
3462         if (mirror->m_layout)
3463                 llapi_layout_free(mirror->m_layout);
3464         free(mirror);
3465 }
3466
3467 /**
3468  * lfs_mirror_list_free() - Free memory allocated for a mirror list.
3469  * @mirror_list: Previously allocated mirror list.
3470  *
3471  * Free memory allocated for @mirror_list.
3472  *
3473  * Return: void.
3474  */
3475 static void lfs_mirror_list_free(struct mirror_args *mirror_list)
3476 {
3477         struct mirror_args *next_mirror = NULL;
3478
3479         while (mirror_list) {
3480                 next_mirror = mirror_list->m_next;
3481                 lfs_mirror_free(mirror_list);
3482                 mirror_list = next_mirror;
3483         }
3484 }
3485
3486 enum {
3487         LFS_SETQUOTA_DELETE = (CHAR_MAX + 1),
3488         LFS_POOL_OPT,
3489         LFS_COMP_COUNT_OPT,
3490         LFS_COMP_START_OPT,
3491         LFS_COMP_FLAGS_OPT,
3492         LFS_COMP_DEL_OPT,
3493         LFS_COMP_SET_OPT,
3494         LFS_COMP_ADD_OPT,
3495         LFS_COMP_NO_VERIFY_OPT,
3496         LFS_PROJID_OPT,
3497         LFS_LAYOUT_FLAGS_OPT, /* used for mirror and foreign flags */
3498         LFS_MIRROR_ID_OPT,
3499         LFS_MIRROR_STATE_OPT,
3500         LFS_LAYOUT_COPY,
3501         LFS_MIRROR_INDEX_OPT,
3502         LFS_LAYOUT_FOREIGN_OPT,
3503         LFS_MODE_OPT,
3504         LFS_NEWERXY_OPT,
3505         LFS_INHERIT_RR_OPT,
3506         LFS_FIND_PERM,
3507         LFS_PRINTF_OPT,
3508         LFS_NO_FOLLOW_OPT,
3509         LFS_HEX_IDX_OPT,
3510         LFS_STATS_OPT,
3511         LFS_STATS_INTERVAL_OPT,
3512         LFS_LINKS_OPT
3513 };
3514
3515 #ifndef LCME_USER_MIRROR_FLAGS
3516 /* The mirror flags can be set by users at creation time. */
3517 #define LCME_USER_MIRROR_FLAGS  (LCME_FL_PREF_RW)
3518 #endif
3519
3520 /* functions */
3521 static int lfs_setstripe_internal(int argc, char **argv,
3522                                   enum setstripe_origin opc)
3523 {
3524         struct lfs_setstripe_args        lsa = { 0 };
3525         struct llapi_stripe_param       *param = NULL;
3526         struct find_param                migrate_mdt_param = {
3527                 .fp_max_depth = -1,
3528                 .fp_mdt_index = -1,
3529         };
3530         char                            *fname;
3531         int                              result = 0;
3532         int                              result2 = 0;
3533         char                            *end;
3534         int                              c;
3535         int                              delete = 0;
3536         unsigned long long               size_units = 1;
3537         bool                             migrate_mode = false;
3538         bool                             migrate_mdt_mode = false;
3539         bool                             setstripe_mode = false;
3540         bool                             migration_block = false;
3541         __u64                            migration_flags = 0;
3542         __u32                            tgts[LOV_MAX_STRIPE_COUNT] = { 0 };
3543         int                              comp_del = 0, comp_set = 0;
3544         int                              comp_add = 0;
3545         __u32                            comp_id = 0;
3546         struct llapi_layout             *layout = NULL;
3547         struct llapi_layout             **lpp = &layout;
3548         bool                             mirror_mode = false;
3549         bool                             has_m_file = false;
3550         __u32                            mirror_count = 0;
3551         enum mirror_flags                mirror_flags = 0;
3552         struct mirror_args              *mirror_list = NULL;
3553         struct mirror_args              *new_mirror = NULL;
3554         struct mirror_args              *last_mirror = NULL;
3555         __u16                            mirror_id = 0;
3556         char                             cmd[PATH_MAX];
3557         bool from_yaml = false;
3558         bool from_copy = false;
3559         char *template = NULL;
3560         bool foreign_mode = false;
3561         char *xattr = NULL;
3562         uint32_t type = LU_FOREIGN_TYPE_NONE, flags = 0;
3563         char *mode_opt = NULL;
3564         mode_t previous_umask = 0;
3565         mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
3566         unsigned long long bandwidth_bytes_sec = 0;
3567         unsigned long long bandwidth_unit = ONE_MB;
3568         enum stats_flag stats_flag = STATS_OFF;
3569         long stats_interval_sec = 5;
3570
3571         struct option long_opts[] = {
3572 /* find { .val = '0',   .name = "null",         .has_arg = no_argument }, */
3573 /* find { .val = 'A',   .name = "atime",        .has_arg = required_argument }*/
3574         /* --block is only valid in migrate mode */
3575         { .val = 'b',   .name = "block",        .has_arg = no_argument },
3576 /* find { .val = 'B',   .name = "btime",        .has_arg = required_argument }*/
3577         { .val = LFS_COMP_ADD_OPT,
3578                         .name = "comp-add",     .has_arg = no_argument },
3579         { .val = LFS_COMP_ADD_OPT,
3580                         .name = "component-add", .has_arg = no_argument },
3581         { .val = LFS_COMP_DEL_OPT,
3582                         .name = "comp-del",     .has_arg = no_argument },
3583         { .val = LFS_COMP_DEL_OPT,
3584                         .name = "component-del", .has_arg = no_argument },
3585         { .val = LFS_COMP_FLAGS_OPT,
3586                         .name = "comp-flags",   .has_arg = required_argument },
3587         { .val = LFS_COMP_FLAGS_OPT,
3588                         .name = "component-flags",
3589                                                 .has_arg = required_argument },
3590         { .val = LFS_COMP_SET_OPT,
3591                         .name = "comp-set",     .has_arg = no_argument },
3592         { .val = LFS_COMP_SET_OPT,
3593                         .name = "component-set",
3594                                                 .has_arg = no_argument},
3595         { .val = LFS_COMP_NO_VERIFY_OPT,
3596                         .name = "no-verify",    .has_arg = no_argument},
3597         { .val = LFS_LAYOUT_FLAGS_OPT,
3598                         .name = "flags",        .has_arg = required_argument},
3599         { .val = LFS_LAYOUT_FOREIGN_OPT,
3600                         .name = "foreign",      .has_arg = optional_argument},
3601         { .val = LFS_MIRROR_ID_OPT,
3602                         .name = "mirror-id",    .has_arg = required_argument},
3603         { .val = LFS_MODE_OPT,
3604                         .name = "mode",         .has_arg = required_argument},
3605         { .val = LFS_LAYOUT_COPY,
3606                         .name = "copy",         .has_arg = required_argument},
3607         { .val = LFS_STATS_OPT,
3608                         .name = "stats",        .has_arg = no_argument},
3609         { .val = LFS_STATS_INTERVAL_OPT,
3610                         .name = "stats-interval",
3611                                                 .has_arg = required_argument},
3612         { .val = 'c',   .name = "stripe-count", .has_arg = required_argument},
3613         { .val = 'c',   .name = "stripe_count", .has_arg = required_argument},
3614         { .val = 'c',   .name = "mdt-count",    .has_arg = required_argument},
3615         { .val = 'C',   .name = "overstripe-count",
3616                                                 .has_arg = required_argument},
3617         { .val = 'd',   .name = "delete",       .has_arg = no_argument},
3618         { .val = 'd',   .name = "destroy",      .has_arg = no_argument},
3619         /* used with "lfs migrate -m" */
3620         { .val = 'd',   .name = "directory",    .has_arg = no_argument},
3621         /* --non-direct is only valid in migrate mode */
3622         { .val = 'D',   .name = "non-direct",   .has_arg = no_argument },
3623         { .val = 'E',   .name = "comp-end",     .has_arg = required_argument},
3624         { .val = 'E',   .name = "component-end",
3625                                                 .has_arg = required_argument},
3626         { .val = 'f',   .name = "file",         .has_arg = required_argument },
3627 /* find { .val = 'F',   .name = "fid",          .has_arg = no_argument }, */
3628 /* find { .val = 'g',   .name = "gid",          .has_arg = no_argument }, */
3629 /* find { .val = 'G',   .name = "group",        .has_arg = required_argument }*/
3630         { .val = 'h',   .name = "help",         .has_arg = no_argument },
3631         { .val = 'H',   .name = "mdt-hash",     .has_arg = required_argument},
3632         { .val = 'i',   .name = "stripe-index", .has_arg = required_argument},
3633         { .val = 'i',   .name = "stripe_index", .has_arg = required_argument},
3634         { .val = 'I',   .name = "comp-id",      .has_arg = required_argument},
3635         { .val = 'I',   .name = "component-id", .has_arg = required_argument},
3636 /* find { .val = 'l',   .name = "lazy",         .has_arg = no_argument }, */
3637         { .val = 'L',   .name = "layout",       .has_arg = required_argument },
3638         { .val = 'm',   .name = "mdt",          .has_arg = required_argument},
3639         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument},
3640         { .val = 'm',   .name = "mdt_index",    .has_arg = required_argument},
3641         /* --non-block is only valid in migrate mode */
3642         { .val = 'n',   .name = "non-block",    .has_arg = no_argument },
3643         { .val = 'N',   .name = "mirror-count", .has_arg = optional_argument},
3644         { .val = 'o',   .name = "ost",          .has_arg = required_argument },
3645 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
3646         { .val = 'o',   .name = "ost-list",     .has_arg = required_argument },
3647         { .val = 'o',   .name = "ost_list",     .has_arg = required_argument },
3648 #endif
3649         { .val = 'p',   .name = "pool",         .has_arg = required_argument },
3650 /* find { .val = 'P',   .name = "print",        .has_arg = no_argument }, */
3651 /* getstripe { .val = 'q', .name = "quiet",     .has_arg = no_argument }, */
3652 /* getstripe { .val = 'R', .name = "raw",       .has_arg = no_argument }, */
3653         { .val = 'S',   .name = "stripe-size",  .has_arg = required_argument },
3654         { .val = 'S',   .name = "stripe_size",  .has_arg = required_argument },
3655 /* find { .val = 't',   .name = "type",         .has_arg = required_argument }*/
3656 /* dirstripe { .val = 'T', .name = "mdt-count", .has_arg = required_argument }*/
3657 /* find { .val = 'u',   .name = "uid",          .has_arg = required_argument }*/
3658 /* find { .val = 'U',   .name = "user",         .has_arg = required_argument }*/
3659         /* --verbose is only valid in migrate mode */
3660         { .val = 'v',   .name = "verbose",      .has_arg = no_argument},
3661         { .val = 'W',   .name = "bandwidth",    .has_arg = required_argument },
3662         { .val = 'x',   .name = "xattr",        .has_arg = required_argument },
3663 /* dirstripe { .val = 'X',.name = "max-inherit",.has_arg = required_argument }*/
3664         { .val = 'y',   .name = "yaml",         .has_arg = required_argument },
3665         { .val = 'z',   .name = "ext-size",     .has_arg = required_argument},
3666         { .val = 'z',   .name = "extension-size", .has_arg = required_argument},
3667         { .name = NULL } };
3668
3669         setstripe_args_init(&lsa);
3670
3671         migrate_mode = (opc == SO_MIGRATE);
3672         mirror_mode = (opc == SO_MIRROR_CREATE || opc == SO_MIRROR_EXTEND);
3673         setstripe_mode = (opc == SO_SETSTRIPE);
3674         if (opc == SO_MIRROR_DELETE) {
3675                 delete = 1;
3676                 mirror_flags = MF_DESTROY;
3677         }
3678
3679         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
3680         progname = cmd;
3681         while ((c = getopt_long(argc, argv,
3682                                 "bc:C:dDE:f:hH:i:I:m:N::no:p:L:s:S:vx:W:y:z:",
3683                                 long_opts, NULL)) >= 0) {
3684                 size_units = 1;
3685                 switch (c) {
3686                 case 0:
3687                         /* Long options. */
3688                         break;
3689                 case LFS_COMP_ADD_OPT:
3690                         comp_add = 1;
3691                         break;
3692                 case LFS_COMP_DEL_OPT:
3693                         comp_del = 1;
3694                         break;
3695                 case LFS_COMP_FLAGS_OPT:
3696                         result = comp_str2flags(optarg, &lsa.lsa_comp_flags,
3697                                                 &lsa.lsa_comp_neg_flags);
3698                         if (result != 0)
3699                                 goto usage_error;
3700                         if (mirror_mode && lsa.lsa_comp_neg_flags) {
3701                                 fprintf(stderr,
3702                                         "%s: inverted flags are not supported\n",
3703                                         progname);
3704                                 goto usage_error;
3705                         }
3706                         break;
3707                 case LFS_COMP_SET_OPT:
3708                         comp_set = 1;
3709                         break;
3710                 case LFS_COMP_NO_VERIFY_OPT:
3711                         mirror_flags |= MF_NO_VERIFY;
3712                         break;
3713                 case LFS_MIRROR_ID_OPT: {
3714                         unsigned long int id;
3715
3716                         errno = 0;
3717                         id = strtoul(optarg, &end, 0);
3718                         if (errno != 0 || *end != '\0' || id == 0 ||
3719                             id > UINT16_MAX) {
3720                                 fprintf(stderr,
3721                                         "%s %s: invalid mirror ID '%s'\n",
3722                                         progname, argv[0], optarg);
3723                                 goto usage_error;
3724                         }
3725
3726                         mirror_id = (__u16)id;
3727                         break;
3728                 }
3729                 case LFS_LAYOUT_FLAGS_OPT: {
3730                         uint32_t neg_flags;
3731
3732                         /* check for numeric flags (foreign and mirror cases) */
3733                         if (setstripe_mode && !mirror_mode && !last_mirror) {
3734                                 errno = 0;
3735                                 flags = strtoul(optarg, &end, 16);
3736                                 if (errno != 0 || *end != '\0' ||
3737                                     flags >= UINT32_MAX) {
3738                                         fprintf(stderr,
3739                                                 "%s %s: invalid hex flags '%s'\n",
3740                                                 progname, argv[0], optarg);
3741                                         return CMD_HELP;
3742                                 }
3743                                 if (!foreign_mode) {
3744                                         fprintf(stderr,
3745                                                 "%s %s: hex flags must be specified with --foreign option\n",
3746                                                 progname, argv[0]);
3747                                         return CMD_HELP;
3748                                 }
3749                                 break;
3750                         }
3751
3752                         if (!mirror_mode || !last_mirror) {
3753                                 fprintf(stderr,
3754                                         "error: %s: --flags must be specified with --mirror-count|-N option\n",
3755                                         progname);
3756                                 goto usage_error;
3757                         }
3758
3759                         result = comp_str2flags(optarg, &last_mirror->m_flags,
3760                                                 &neg_flags);
3761                         if (result != 0)
3762                                 goto usage_error;
3763
3764                         if (neg_flags) {
3765                                 fprintf(stderr,
3766                                         "%s: inverted flags are not supported\n",
3767                                         progname);
3768                                 result = -EINVAL;
3769                                 goto usage_error;
3770                         }
3771                         if (last_mirror->m_flags & ~LCME_USER_MIRROR_FLAGS) {
3772                                 fprintf(stderr,
3773                                         "%s: unsupported mirror flags: %s\n",
3774                                         progname, optarg);
3775                                 result = -EINVAL;
3776                                 goto error;
3777                         }
3778                         break;
3779                 }
3780                 case LFS_LAYOUT_FOREIGN_OPT:
3781                         if (optarg) {
3782                                 /* check pure numeric */
3783                                 type = strtoul(optarg, &end, 0);
3784                                 if (*end) {
3785                                         /* check name */
3786                                         type = check_foreign_type_name(optarg);
3787                                         if (type == LU_FOREIGN_TYPE_UNKNOWN) {
3788                                                 fprintf(stderr,
3789                                                         "%s %s: unrecognized foreign type '%s'\n",
3790                                                         progname, argv[0],
3791                                                         optarg);
3792                                                 return CMD_HELP;
3793                                         }
3794                                 } else if (type >= UINT32_MAX) {
3795                                         fprintf(stderr,
3796                                                 "%s %s: invalid foreign type '%s'\n",
3797                                                 progname, argv[0], optarg);
3798                                         return CMD_HELP;
3799                                 }
3800                         }
3801                         foreign_mode = true;
3802                         break;
3803                 case LFS_MODE_OPT:
3804                         mode_opt = optarg;
3805                         if (mode_opt) {
3806                                 mode = strtoul(mode_opt, &end, 8);
3807                                 if (*end != '\0') {
3808                                         fprintf(stderr,
3809                                                 "%s %s: bad mode '%s'\n",
3810                                                 progname, argv[0], mode_opt);
3811                                         return CMD_HELP;
3812                                 }
3813                                 previous_umask = umask(0);
3814                         }
3815                         break;
3816                 case LFS_LAYOUT_COPY:
3817                         from_copy = true;
3818                         template = optarg;
3819                         break;
3820                 case LFS_STATS_OPT:
3821                         stats_flag = STATS_ON;
3822                         break;
3823                 case LFS_STATS_INTERVAL_OPT:
3824                         stats_flag = STATS_ON;
3825                         stats_interval_sec = strtol(optarg, &end, 0);
3826                         if (stats_interval_sec == 0)
3827                                 stats_interval_sec = 5;
3828                         break;
3829                 case 'b':
3830                         if (!migrate_mode) {
3831                                 fprintf(stderr,
3832                                         "%s %s: -b|--block valid only for migrate command\n",
3833                                         progname, argv[0]);
3834                                 goto usage_error;
3835                         }
3836                         migration_block = true;
3837                         break;
3838                 case 'C':
3839                         if (lsa.lsa_pattern == LLAPI_LAYOUT_MDT) {
3840                                 fprintf(stderr,
3841                                         "%s %s: -C|--overstripe-count incompatible with DoM layout\n",
3842                                         progname, argv[0]);
3843                                 goto usage_error;
3844                         }
3845                         lsa.lsa_pattern = LLAPI_LAYOUT_OVERSTRIPING;
3846                         fallthrough;
3847                 case 'c':
3848                         errno = 0;
3849                         lsa.lsa_stripe_count = strtoul(optarg, &end, 0);
3850                         if (errno != 0 || *end != '\0'|| optarg == end ||
3851                             lsa.lsa_stripe_count < -1 ||
3852                             lsa.lsa_stripe_count > LOV_MAX_STRIPE_COUNT) {
3853                                 fprintf(stderr,
3854                                         "%s %s: invalid stripe count '%s'\n",
3855                                         progname, argv[0], optarg);
3856                                 goto usage_error;
3857                         }
3858
3859                         if (lsa.lsa_stripe_count == -1)
3860                                 lsa.lsa_stripe_count = LLAPI_LAYOUT_WIDE;
3861                         break;
3862                 case 'd':
3863                         if (migrate_mode) {
3864                                 migrate_mdt_param.fp_max_depth = 1;
3865                         } else {
3866                                 /* delete the default striping pattern */
3867                                 delete = 1;
3868                                 if (opc == SO_MIRROR_SPLIT) {
3869                                         if (has_m_file) {
3870                                                 fprintf(stderr,
3871                                                       "%s %s: -d cannot used with -f\n",
3872                                                         progname, argv[0]);
3873                                                 goto usage_error;
3874                                         }
3875                                         mirror_flags |= MF_DESTROY;
3876                                 }
3877                         }
3878                         break;
3879                 case 'D':
3880                         if (!migrate_mode) {
3881                                 fprintf(stderr,
3882                                         "%s %s: -D|--non-direct is valid only for migrate command\n",
3883                                         progname, argv[0]);
3884                                 goto usage_error;
3885                         }
3886                         migration_flags |= LLAPI_MIGRATION_NONDIRECT;
3887                         break;
3888                 case 'E':
3889                         if (lsa.lsa_comp_end != 0) {
3890                                 result = comp_args_to_layout(lpp, &lsa, true);
3891                                 if (result) {
3892                                         fprintf(stderr, "%s: invalid layout\n",
3893                                                 progname);
3894                                         goto usage_error;
3895                                 }
3896
3897                                 setstripe_args_init_inherit(&lsa);
3898                         }
3899
3900                         if (arg_is_eof(optarg)) {
3901                                 lsa.lsa_comp_end = LUSTRE_EOF;
3902                         } else {
3903                                 result = llapi_parse_size(optarg,
3904                                                           &lsa.lsa_comp_end,
3905                                                           &size_units, 0);
3906                                 /* assume units of KB if too small */
3907                                 if (lsa.lsa_comp_end < 4096)
3908                                         lsa.lsa_comp_end *= 1024;
3909                                 if (result ||
3910                                     lsa.lsa_comp_end & (LOV_MIN_STRIPE_SIZE - 1)) {
3911                                         fprintf(stderr,
3912                                                 "%s %s: invalid component end '%s'\n",
3913                                                 progname, argv[0], optarg);
3914                                         goto usage_error;
3915                                 }
3916                         }
3917                         break;
3918                 case 'H':
3919                         if (!migrate_mode) {
3920                                 fprintf(stderr,
3921                                         "--mdt-hash is valid only for migrate command\n");
3922                                 return CMD_HELP;
3923                         }
3924
3925                         lsa.lsa_pattern = check_hashtype(optarg);
3926                         if (lsa.lsa_pattern == 0) {
3927                                 fprintf(stderr,
3928                                         "%s %s: bad stripe hash type '%s'\n",
3929                                         progname, argv[0], optarg);
3930                                 return CMD_HELP;
3931                         }
3932                         break;
3933                 case 'i':
3934                         errno = 0;
3935                         lsa.lsa_stripe_off = strtol(optarg, &end, 0);
3936                         if (errno != 0 || *end != '\0' || optarg == end ||
3937                             lsa.lsa_stripe_off < -1 ||
3938                             lsa.lsa_stripe_off > LOV_V1_INSANE_STRIPE_COUNT) {
3939                                 fprintf(stderr,
3940                                         "%s %s: invalid stripe offset '%s'\n",
3941                                         progname, argv[0], optarg);
3942                                 goto usage_error;
3943                         }
3944                         if (lsa.lsa_stripe_off == -1)
3945                                 lsa.lsa_stripe_off = LLAPI_LAYOUT_DEFAULT;
3946                         break;
3947                 case 'I':
3948                         comp_id = strtoul(optarg, &end, 0);
3949                         if (*end != '\0' || comp_id == 0 ||
3950                             comp_id > LCME_ID_MAX) {
3951                                 fprintf(stderr,
3952                                         "%s %s: invalid component ID '%s'\n",
3953                                         progname, argv[0], optarg);
3954                                 goto usage_error;
3955                         }
3956                         break;
3957                 case 'f':
3958                         if (opc != SO_MIRROR_EXTEND && opc != SO_MIRROR_SPLIT) {
3959                                 fprintf(stderr,
3960                                         "error: %s: invalid option: %s\n",
3961                                         progname, argv[optopt + 1]);
3962                                 goto usage_error;
3963                         }
3964                         if (opc == SO_MIRROR_EXTEND) {
3965                                 if (!last_mirror) {
3966                                         fprintf(stderr,
3967                                 "error: %s: '-N' must exist in front of '%s'\n",
3968                                                 progname, argv[optopt + 1]);
3969                                         goto usage_error;
3970                                 }
3971                                 last_mirror->m_file = optarg;
3972                                 last_mirror->m_count = 1;
3973                         } else {
3974                                 /* mirror split */
3975                                 if (!mirror_list)
3976                                         mirror_list = lfs_mirror_alloc();
3977                                 mirror_list->m_file = optarg;
3978                         }
3979                         has_m_file = true;
3980                         break;
3981                 case 'L':
3982                         if (strcmp(argv[optind - 1], "mdt") == 0) {
3983                                 /* Can be only the first component */
3984                                 if (layout) {
3985                                         result = -EINVAL;
3986                                         fprintf(stderr,
3987                                                 "error: 'mdt' layout can be only the first one\n");
3988                                         goto error;
3989                                 }
3990                                 if (lsa.lsa_comp_end > (1ULL << 30)) { /* 1Gb */
3991                                         result = -EFBIG;
3992                                         fprintf(stderr,
3993                                                 "error: 'mdt' layout size is too big\n");
3994                                         goto error;
3995                                 }
3996                                 lsa.lsa_pattern = LLAPI_LAYOUT_MDT;
3997                                 lsa.lsa_stripe_size = LLAPI_LAYOUT_DEFAULT;
3998                         } else if (strcmp(argv[optind - 1], "raid0") != 0) {
3999                                 result = -EINVAL;
4000                                 fprintf(stderr,
4001                                         "error: layout '%s' is unknown, supported layouts are: 'mdt', 'raid0'\n",
4002                                         argv[optind]);
4003                                 goto error;
4004                         }
4005                         break;
4006                 case 'm':
4007                         if (!migrate_mode) {
4008                                 fprintf(stderr,
4009                                         "%s %s: -m|--mdt-index is valid only for migrate command\n",
4010                                         progname, argv[0]);
4011                                 goto usage_error;
4012                         }
4013                         migrate_mdt_mode = true;
4014                         lsa.lsa_nr_tgts = parse_targets(tgts,
4015                                                 sizeof(tgts) / sizeof(__u32),
4016                                                 lsa.lsa_nr_tgts, optarg, NULL);
4017                         if (lsa.lsa_nr_tgts < 0) {
4018                                 fprintf(stderr,
4019                                         "%s: invalid MDT target(s) '%s'\n",
4020                                         progname, optarg);
4021                                 goto usage_error;
4022                         }
4023
4024                         lsa.lsa_tgts = tgts;
4025                         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
4026                                 lsa.lsa_stripe_off = tgts[0];
4027                         break;
4028                 case 'n':
4029                         if (!migrate_mode) {
4030                                 fprintf(stderr,
4031                                         "%s %s: -n|--non-block valid only for migrate command\n",
4032                                         progname, argv[0]);
4033                                 goto usage_error;
4034                         }
4035                         migration_flags |= LLAPI_MIGRATION_NONBLOCK;
4036                         break;
4037                 case 'N':
4038                         if (opc == SO_SETSTRIPE) {
4039                                 opc = SO_MIRROR_CREATE;
4040                                 mirror_mode = true;
4041                         }
4042                         mirror_count = 1;
4043                         if (optarg) {
4044                                 errno = 0;
4045                                 mirror_count = strtoul(optarg, &end, 0);
4046                                 if (errno != 0 || *end != '\0' ||
4047                                     mirror_count == 0 ||
4048                                     mirror_count > LUSTRE_MIRROR_COUNT_MAX) {
4049                                         fprintf(stderr,
4050                                                 "error: %s: bad mirror count: %s\n",
4051                                                 progname, optarg);
4052                                         result = -EINVAL;
4053                                         goto error;
4054                                 }
4055                         }
4056
4057                         new_mirror = lfs_mirror_alloc();
4058                         new_mirror->m_count = mirror_count;
4059
4060                         if (!mirror_list)
4061                                 mirror_list = new_mirror;
4062
4063                         if (last_mirror) {
4064                                 /* wrap up last mirror */
4065                                 if (!setstripe_args_specified(&lsa))
4066                                         last_mirror->m_inherit = true;
4067                                 if (lsa.lsa_comp_end == 0)
4068                                         lsa.lsa_comp_end = LUSTRE_EOF;
4069
4070                                 result = comp_args_to_layout(lpp, &lsa, true);
4071                                 if (result) {
4072                                         lfs_mirror_free(new_mirror);
4073                                         goto error;
4074                                 }
4075
4076                                 setstripe_args_init_inherit(&lsa);
4077
4078                                 last_mirror->m_next = new_mirror;
4079                         }
4080
4081                         last_mirror = new_mirror;
4082                         lpp = &last_mirror->m_layout;
4083                         break;
4084                 case 'o':
4085 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
4086                         if (strcmp(argv[optind - 1], "--ost-list") == 0)
4087                                 fprintf(stderr,
4088                                         "warning: '--ost-list' is deprecated, use '--ost' instead\n");
4089 #endif
4090                         if (lsa.lsa_pattern == LLAPI_LAYOUT_MDT) {
4091                                 fprintf(stderr,
4092                                         "%s %s: -o|--ost incompatible with DoM layout\n",
4093                                         progname, argv[0]);
4094                                 goto usage_error;
4095                         }
4096                         /*
4097                          * -o allows overstriping, and must note it because
4098                          * parse_targets is shared with MDT striping, which
4099                          * does not allow duplicates
4100                          */
4101                         lsa.lsa_pattern = LLAPI_LAYOUT_OVERSTRIPING;
4102                         lsa.lsa_nr_tgts = parse_targets(tgts,
4103                                                 sizeof(tgts) / sizeof(__u32),
4104                                                 lsa.lsa_nr_tgts, optarg,
4105                                                 &lsa.lsa_pattern);
4106                         if (lsa.lsa_nr_tgts < 0) {
4107                                 fprintf(stderr,
4108                                         "%s %s: invalid OST target(s) '%s'\n",
4109                                         progname, argv[0], optarg);
4110                                 goto usage_error;
4111                         }
4112
4113                         lsa.lsa_tgts = tgts;
4114                         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
4115                                 lsa.lsa_stripe_off = tgts[0];
4116                         break;
4117                 case 'p':
4118                         if (!optarg)
4119                                 goto usage_error;
4120
4121                         if (optarg[0] == '\0' || lov_pool_is_inherited(optarg))
4122                                 lsa.lsa_pool_name = NULL;
4123                         else
4124                                 lsa.lsa_pool_name = optarg;
4125                         break;
4126                 case 'S':
4127                         result = llapi_parse_size(optarg, &lsa.lsa_stripe_size,
4128                                                   &size_units, 0);
4129                         /* assume units of KB if too small to be valid */
4130                         if (lsa.lsa_stripe_size < 4096)
4131                                 lsa.lsa_stripe_size *= 1024;
4132                         if (result ||
4133                             lsa.lsa_stripe_size & (LOV_MIN_STRIPE_SIZE - 1)) {
4134                                 fprintf(stderr,
4135                                         "%s %s: invalid stripe size '%s'\n",
4136                                         progname, argv[0], optarg);
4137                                 goto usage_error;
4138                         }
4139                         break;
4140                 case 'v':
4141                         if (!migrate_mode) {
4142                                 fprintf(stderr,
4143                                         "%s %s: -v|--verbose valid only for migrate command\n",
4144                                         progname, argv[0]);
4145                                 goto usage_error;
4146                         }
4147                         migrate_mdt_param.fp_verbose = VERBOSE_DETAIL;
4148                         migration_flags = LLAPI_MIGRATION_VERBOSE;
4149                         break;
4150                 case 'x':
4151                         xattr = optarg;
4152                         break;
4153                 case 'W':
4154                         if (!migrate_mode) {
4155                                 fprintf(stderr,
4156                                         "--bandwidth is valid only for migrate and mirror mode\n");
4157                                 goto error;
4158                         }
4159                         if (llapi_parse_size(optarg, &bandwidth_bytes_sec,
4160                                              &bandwidth_unit, 0) < 0) {
4161                                 fprintf(stderr,
4162                                         "error: %s: bad value for bandwidth '%s'\n",
4163                                         argv[0], optarg);
4164                                 goto error;
4165                         }
4166                         break;
4167                 case 'y':
4168                         from_yaml = true;
4169                         template = optarg;
4170                         break;
4171                 case 'z':
4172                         result = llapi_parse_size(optarg,
4173                                                   &lsa.lsa_extension_size,
4174                                                   &size_units, 0);
4175                         if (result) {
4176                                 fprintf(stderr,
4177                                         "%s %s: invalid extension size '%s'\n",
4178                                         progname, argv[0], optarg);
4179                                 goto usage_error;
4180                         }
4181
4182                         lsa.lsa_extension_comp = true;
4183                         break;
4184                 default:
4185                         fprintf(stderr, "%s: unrecognized option '%s'\n",
4186                                 progname, argv[optind - 1]);
4187                 case 'h':
4188                         goto usage_error;
4189                 }
4190         }
4191
4192         fname = argv[optind];
4193
4194         if (optind == argc) {
4195                 fprintf(stderr, "%s %s: FILE must be specified\n",
4196                         progname, argv[0]);
4197                 goto usage_error;
4198         }
4199
4200         /* lfs migrate $filename should keep the file's layout by default */
4201         if (migrate_mode && !layout && !from_yaml &&
4202             !setstripe_args_specified(&lsa) && !lsa.lsa_pool_name)
4203                 from_copy = true;
4204
4205         if (xattr && !foreign_mode) {
4206                 /*
4207                  * only print a warning as this is harmless and will be ignored
4208                  */
4209                 fprintf(stderr,
4210                         "%s %s: xattr has been specified for non-foreign layout\n",
4211                         progname, argv[0]);
4212         } else if (foreign_mode && !xattr) {
4213                 fprintf(stderr,
4214                         "%s %s: xattr must be provided in foreign mode\n",
4215                         progname, argv[0]);
4216                 goto usage_error;
4217         }
4218
4219         if (foreign_mode && (!setstripe_mode || comp_add | comp_del ||
4220             comp_set || comp_id || delete || from_copy ||
4221             setstripe_args_specified(&lsa) || lsa.lsa_nr_tgts ||
4222             lsa.lsa_tgts)) {
4223                 fprintf(stderr,
4224                         "%s %s: only --xattr/--flags/--mode options are valid with --foreign\n",
4225                         progname, argv[0]);
4226                 return CMD_HELP;
4227         }
4228
4229         if (mirror_mode && mirror_count == 0) {
4230                 fprintf(stderr,
4231                         "error: %s: --mirror-count|-N option is required\n",
4232                         progname);
4233                 result = -EINVAL;
4234                 goto error;
4235         }
4236
4237         if (mirror_mode) {
4238                 if (!setstripe_args_specified(&lsa))
4239                         last_mirror->m_inherit = true;
4240                 if (lsa.lsa_comp_end == 0)
4241                         lsa.lsa_comp_end = LUSTRE_EOF;
4242         }
4243
4244         if (lsa.lsa_comp_end != 0) {
4245                 result = comp_args_to_layout(lpp, &lsa, true);
4246                 if (result) {
4247                         fprintf(stderr, "error: %s: invalid layout\n",
4248                                 progname);
4249                         result = -EINVAL;
4250                         goto error;
4251                 }
4252         }
4253
4254         if (mirror_flags & MF_NO_VERIFY) {
4255                 if (opc != SO_MIRROR_EXTEND) {
4256                         fprintf(stderr,
4257                                 "error: %s: --no-verify is valid only for lfs mirror extend command\n",
4258                                 progname);
4259                         result = -EINVAL;
4260                         goto error;
4261                 } else if (!has_m_file) {
4262                         fprintf(stderr,
4263                                 "error: %s: --no-verify must be specified with -f <victim_file> option\n",
4264                                 progname);
4265                         result = -EINVAL;
4266                         goto error;
4267                 }
4268         }
4269
4270         if (comp_set && !comp_id && !lsa.lsa_pool_name) {
4271                 fprintf(stderr,
4272                         "%s %s: --component-set doesn't have component-id set\n",
4273                         progname, argv[0]);
4274                 goto usage_error;
4275         }
4276
4277         if ((delete + comp_set + comp_del + comp_add) > 1) {
4278                 fprintf(stderr,
4279                         "%s %s: options --component-set, --component-del, --component-add and -d are mutually exclusive\n",
4280                         progname, argv[0]);
4281                 goto usage_error;
4282         }
4283
4284         if (delete && (setstripe_args_specified(&lsa) || comp_id != 0 ||
4285                        lsa.lsa_comp_flags != 0 || layout != NULL)) {
4286                 fprintf(stderr,
4287                         "%s %s: option -d is mutually exclusive with -s, -c, -o, -p, -I, -F and -E options\n",
4288                         progname, argv[0]);
4289                 goto usage_error;
4290         }
4291
4292         if ((comp_set || comp_del) &&
4293             (setstripe_args_specified(&lsa) || layout != NULL)) {
4294                 fprintf(stderr,
4295                         "%s %s: options --component-del and --component-set are mutually exclusive when used with -c, -E, -o, -p, or -s\n",
4296                         progname, argv[0]);
4297                 goto usage_error;
4298         }
4299
4300         if (comp_del && comp_id != 0 && lsa.lsa_comp_flags != 0) {
4301                 fprintf(stderr,
4302                         "%s %s: options -I and -F are mutually exclusive when used with --component-del\n",
4303                         progname, argv[0]);
4304                 goto usage_error;
4305         }
4306
4307         if (comp_add || comp_del) {
4308                 struct stat st;
4309
4310                 result = lstat(fname, &st);
4311                 if (result == 0 && S_ISDIR(st.st_mode)) {
4312                         fprintf(stderr,
4313                                 "%s setstripe: cannot use --component-add or --component-del for directory\n",
4314                                 progname);
4315                         goto usage_error;
4316                 }
4317
4318                 if (mirror_mode) {
4319                         fprintf(stderr,
4320                                 "error: %s: can't use --component-add or --component-del for mirror operation\n",
4321                                 progname);
4322                         goto usage_error;
4323                 }
4324         }
4325
4326         if (comp_add) {
4327                 if (!layout) {
4328                         fprintf(stderr,
4329                                 "%s %s: option -E must be specified with --component-add\n",
4330                                 progname, argv[0]);
4331                         goto usage_error;
4332                 }
4333         }
4334
4335         if (from_yaml && from_copy) {
4336                 fprintf(stderr,
4337                         "%s: can't specify --yaml and --copy together\n",
4338                         progname);
4339                 goto error;
4340         }
4341
4342         if ((from_yaml || from_copy) &&
4343             (setstripe_args_specified(&lsa) || layout != NULL)) {
4344                 fprintf(stderr,
4345                         "error: %s: can't specify --yaml or --copy with -c, -S, -i, -o, -p or -E options.\n",
4346                         argv[0]);
4347                 goto error;
4348         }
4349
4350         if ((migration_flags & LLAPI_MIGRATION_NONBLOCK) && migration_block) {
4351                 fprintf(stderr,
4352                         "%s %s: options --non-block and --block are mutually exclusive\n",
4353                         progname, argv[0]);
4354                 goto usage_error;
4355         }
4356
4357         if (!comp_del && !comp_set && opc != SO_MIRROR_SPLIT &&
4358             opc != SO_MIRROR_DELETE && comp_id != 0) {
4359                 fprintf(stderr,
4360                         "%s: option -I can only be used with --component-del or --component-set or lfs mirror split\n",
4361                         progname);
4362                 goto usage_error;
4363         }
4364
4365         if (migrate_mdt_mode) {
4366                 struct lmv_user_md *lmu;
4367
4368                 /* initialize migrate mdt parameters */
4369                 lmu = calloc(1, lmv_user_md_size(lsa.lsa_nr_tgts,
4370                                                  LMV_USER_MAGIC_SPECIFIC));
4371                 if (!lmu) {
4372                         fprintf(stderr,
4373                                 "%s %s: cannot allocate memory for lmv_user_md: %s\n",
4374                                 progname, argv[0], strerror(ENOMEM));
4375                         result = -ENOMEM;
4376                         goto error;
4377                 }
4378                 if (lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT)
4379                         lmu->lum_stripe_count = lsa.lsa_stripe_count;
4380                 if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT) {
4381                         fprintf(stderr,
4382                                 "%s %s: migrate should specify MDT index\n",
4383                                 progname, argv[0]);
4384                         free(lmu);
4385                         goto usage_error;
4386                 }
4387                 lmu->lum_stripe_offset = lsa.lsa_stripe_off;
4388                 if (lsa.lsa_pattern != LLAPI_LAYOUT_RAID0)
4389                         lmu->lum_hash_type = lsa.lsa_pattern;
4390                 else
4391                         lmu->lum_hash_type = LMV_HASH_TYPE_UNKNOWN;
4392                 if (lsa.lsa_pool_name) {
4393                         strncpy(lmu->lum_pool_name, lsa.lsa_pool_name,
4394                                 sizeof(lmu->lum_pool_name) - 1);
4395                         lmu->lum_pool_name[sizeof(lmu->lum_pool_name) - 1] = 0;
4396                 }
4397                 if (lsa.lsa_nr_tgts > 1) {
4398                         int i;
4399
4400                         if (lsa.lsa_stripe_count > 0 &&
4401                             lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT &&
4402                             lsa.lsa_stripe_count != lsa.lsa_nr_tgts) {
4403                                 fprintf(stderr,
4404                                         "error: %s: stripe count %lld doesn't match the number of MDTs: %d\n",
4405                                         progname, lsa.lsa_stripe_count,
4406                                         lsa.lsa_nr_tgts);
4407                                 free(lmu);
4408                                 goto usage_error;
4409                         }
4410
4411                         lmu->lum_magic = LMV_USER_MAGIC_SPECIFIC;
4412                         lmu->lum_stripe_count = lsa.lsa_nr_tgts;
4413                         for (i = 0; i < lsa.lsa_nr_tgts; i++)
4414                                 lmu->lum_objects[i].lum_mds = lsa.lsa_tgts[i];
4415                 } else {
4416                         lmu->lum_magic = LMV_USER_MAGIC;
4417                 }
4418
4419                 migrate_mdt_param.fp_lmv_md = lmu;
4420                 migrate_mdt_param.fp_migrate = 1;
4421         } else if (!layout) {
4422                 if (lsa_args_stripe_count_check(&lsa))
4423                         goto usage_error;
4424
4425                 /* initialize stripe parameters */
4426                 param = calloc(1, offsetof(typeof(*param),
4427                                lsp_osts[lsa.lsa_nr_tgts]));
4428                 if (!param) {
4429                         fprintf(stderr,
4430                                 "%s %s: cannot allocate memory for parameters: %s\n",
4431                                 progname, argv[0], strerror(ENOMEM));
4432                         result = -ENOMEM;
4433                         goto error;
4434                 }
4435
4436                 if (lsa.lsa_stripe_size != LLAPI_LAYOUT_DEFAULT)
4437                         param->lsp_stripe_size = lsa.lsa_stripe_size;
4438                 if (lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT) {
4439                         if (lsa.lsa_stripe_count == LLAPI_LAYOUT_WIDE)
4440                                 param->lsp_stripe_count = -1;
4441                         else
4442                                 param->lsp_stripe_count = lsa.lsa_stripe_count;
4443                 }
4444                 if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
4445                         param->lsp_stripe_offset = -1;
4446                 else
4447                         param->lsp_stripe_offset = lsa.lsa_stripe_off;
4448                 param->lsp_stripe_pattern =
4449                                 llapi_pattern_to_lov(lsa.lsa_pattern);
4450                 if (param->lsp_stripe_pattern == EINVAL) {
4451                         fprintf(stderr, "error: %s: invalid stripe pattern\n",
4452                                 argv[0]);
4453                         free(param);
4454                         goto usage_error;
4455                 }
4456                 param->lsp_pool = lsa.lsa_pool_name;
4457                 param->lsp_is_specific = false;
4458
4459                 if (lsa.lsa_nr_tgts > 0) {
4460                         param->lsp_is_specific = true;
4461                         param->lsp_stripe_count = lsa.lsa_nr_tgts;
4462                         memcpy(param->lsp_osts, tgts,
4463                                sizeof(*tgts) * lsa.lsa_nr_tgts);
4464                 }
4465         }
4466
4467         if (from_yaml) {
4468                 /* generate a layout from a YAML template */
4469                 result = lfs_comp_create_from_yaml(template, &layout,
4470                                                    &lsa, tgts);
4471                 if (result) {
4472                         fprintf(stderr,
4473                                 "error: %s: can't create composite layout from template file %s\n",
4474                                 argv[0], template);
4475                         goto error;
4476                 }
4477         }
4478
4479         if (layout != NULL || mirror_list != NULL) {
4480                 if (mirror_list)
4481                         result = mirror_adjust_first_extents(mirror_list);
4482                 else
4483                         result = layout_adjust_first_extent(fname, layout,
4484                                                             comp_add);
4485                 if (result == -ENODATA)
4486                         comp_add = 0;
4487                 else if (result != 0) {
4488                         fprintf(stderr, "error: %s: invalid layout\n",
4489                                 progname);
4490                         goto error;
4491                 }
4492         }
4493
4494         for (fname = argv[optind]; fname != NULL; fname = argv[++optind]) {
4495                 if (from_copy) {
4496                         layout = llapi_layout_get_by_path(template ?: fname, 0);
4497                         if (!layout) {
4498                                 fprintf(stderr,
4499                                         "%s: can't create composite layout from file %s: %s\n",
4500                                         progname, template ?: fname,
4501                                         strerror(errno));
4502                                 result = -errno;
4503                                 goto error;
4504                         }
4505                 }
4506
4507                 if (migrate_mdt_mode) {
4508                         result = llapi_migrate_mdt(fname, &migrate_mdt_param);
4509                 } else if (migrate_mode) {
4510                         if (from_copy) {
4511                                 /*
4512                                  * Strip the source layout of specific
4513                                  * OST object/index values.
4514                                  */
4515                                 result = llapi_layout_ost_index_set(layout, 0,
4516                                                 LLAPI_LAYOUT_DEFAULT);
4517                                 if (result) {
4518                                         fprintf(stderr,
4519                                                 "%s: set default ost index failed: %s\n",
4520                                                 progname, strerror(errno));
4521                                         result = -errno;
4522                                         goto error;
4523                                 }
4524                         }
4525
4526                         result = lfs_migrate(fname, migration_flags, param,
4527                                              layout, bandwidth_bytes_sec,
4528                                              stats_flag, stats_interval_sec);
4529                 } else if (comp_set != 0) {
4530                         result = lfs_component_set(fname, comp_id,
4531                                                    lsa.lsa_pool_name,
4532                                                    lsa.lsa_comp_flags,
4533                                                    lsa.lsa_comp_neg_flags);
4534                 } else if (comp_del != 0) {
4535                         result = lfs_component_del(fname, comp_id,
4536                                                    lsa.lsa_comp_flags,
4537                                                    lsa.lsa_comp_neg_flags);
4538                 } else if (comp_add != 0) {
4539                         result = lfs_component_add(fname, layout);
4540                 } else if (opc == SO_MIRROR_CREATE) {
4541                         result = mirror_create(fname, mirror_list);
4542                 } else if (opc == SO_MIRROR_EXTEND) {
4543                         result = mirror_extend(fname, mirror_list,
4544                                                mirror_flags,
4545                                                bandwidth_bytes_sec,
4546                                                stats_flag, stats_interval_sec);
4547                 } else if (opc == SO_MIRROR_SPLIT || opc == SO_MIRROR_DELETE) {
4548                         if (!mirror_id && !comp_id && !lsa.lsa_pool_name) {
4549                                 fprintf(stderr,
4550                                         "%s: no mirror id, component id, or pool name specified to delete from '%s'\n",
4551                                         progname, fname);
4552                                 goto usage_error;
4553                         }
4554                         if (lsa.lsa_pool_name)
4555                                 mirror_flags |= MF_COMP_POOL;
4556                         else if (mirror_id != 0)
4557                                 comp_id = mirror_id;
4558                         else
4559                                 mirror_flags |= MF_COMP_ID;
4560                         if (has_m_file && !strcmp(fname, mirror_list->m_file)) {
4561                                 fprintf(stderr,
4562                                         "%s: the file specified by -f cannot be same as the source file '%s'\n",
4563                                         progname, fname);
4564                                 goto usage_error;
4565                         }
4566                         result = mirror_split(fname, comp_id, lsa.lsa_pool_name,
4567                                               mirror_flags,
4568                                               has_m_file ? mirror_list->m_file :
4569                                               NULL);
4570                 } else if (layout) {
4571                         result = lfs_component_create(fname, O_CREAT | O_WRONLY,
4572                                                       mode, layout);
4573                         if (result >= 0) {
4574                                 close(result);
4575                                 result = 0;
4576                         }
4577                 } else if (foreign_mode) {
4578                         result = llapi_file_create_foreign(fname, mode, type,
4579                                                            flags, xattr);
4580                         if (result >= 0) {
4581                                 close(result);
4582                                 result = 0;
4583                         }
4584                 } else {
4585                         result = llapi_file_open_param(fname,
4586                                                        O_CREAT | O_WRONLY,
4587                                                        mode, param);
4588                         if (result >= 0) {
4589                                 close(result);
4590                                 result = 0;
4591                         }
4592                 }
4593                 if (result) {
4594                         /* Save the first error encountered. */
4595                         if (result2 == 0)
4596                                 result2 = result;
4597                         continue;
4598                 }
4599         }
4600
4601         if (mode_opt)
4602                 umask(previous_umask);
4603
4604         free(param);
4605         free(migrate_mdt_param.fp_lmv_md);
4606         llapi_layout_free(layout);
4607         lfs_mirror_list_free(mirror_list);
4608         return result2;
4609 usage_error:
4610         result = CMD_HELP;
4611 error:
4612         llapi_layout_free(layout);
4613         lfs_mirror_list_free(mirror_list);
4614         return result;
4615 }
4616
4617 static int lfs_poollist(int argc, char **argv)
4618 {
4619         if (argc != 2)
4620                 return CMD_HELP;
4621
4622         return llapi_poollist(argv[1]);
4623 }
4624
4625 #define FP_DEFAULT_TIME_MARGIN (24 * 60 * 60)
4626 static int set_time(struct find_param *param, time_t *time, time_t *set,
4627                     char *str)
4628 {
4629         long long t = 0;
4630         int sign = 0;
4631         char *endptr = "AD";
4632         char *timebuf;
4633
4634         if (str[0] == '+')
4635                 sign = 1;
4636         else if (str[0] == '-')
4637                 sign = -1;
4638
4639         if (sign)
4640                 str++;
4641
4642         for (timebuf = str; *endptr && *(endptr + 1); timebuf = endptr + 1) {
4643                 long long val = strtoll(timebuf, &endptr, 0);
4644                 int unit = 1;
4645
4646                 switch (*endptr) {
4647                 case  'y':
4648                         unit *= 52; /* 52 weeks + 1 day below */
4649                         fallthrough;
4650                 case  'w':
4651                         unit *= 7;
4652                         if (param->fp_time_margin == FP_DEFAULT_TIME_MARGIN)
4653                                 param->fp_time_margin *= (1 + unit / 52);
4654                         unit += (*endptr == 'y'); /* +1 day for 365 days/year */
4655                         fallthrough;
4656                 case '\0': /* days are default unit if none used */
4657                         fallthrough;
4658                 case  'd':
4659                         unit *= 24;
4660                         fallthrough;
4661                 case  'h':
4662                         unit *= 60;
4663                         fallthrough;
4664                 case  'm':
4665                         unit *= 60;
4666                         fallthrough;
4667                 case  's':
4668                         break;
4669                         /* don't need to multiply by 1 for seconds */
4670                 default:
4671                         fprintf(stderr,
4672                                 "%s find: bad time string '%s': %s\n",
4673                                 progname, timebuf, strerror(EINVAL));
4674                         return INT_MAX;
4675                 }
4676
4677                 if (param->fp_time_margin == 0 ||
4678                     (*endptr && unit < param->fp_time_margin))
4679                         param->fp_time_margin = unit;
4680
4681                 t += val * unit;
4682         }
4683         if (*time < t) {
4684                 if (sign != 0)
4685                         str--;
4686                 fprintf(stderr, "%s find: bad time '%s': too large\n",
4687                         progname, str);
4688                 return INT_MAX;
4689         }
4690
4691         *set = *time - t;
4692
4693         return sign;
4694 }
4695
4696 static int str2quotaid(__u32 *id, const char *arg)
4697 {
4698         unsigned long int projid_tmp = 0;
4699         char *endptr = NULL;
4700
4701         projid_tmp = strtoul(arg, &endptr, 10);
4702         if (*endptr != '\0')
4703                 return -EINVAL;
4704         /* UINT32_MAX is not allowed - see projid_valid()/INVALID_PROJID */
4705         if (projid_tmp >= UINT32_MAX)
4706                 return -ERANGE;
4707
4708         *id = projid_tmp;
4709         return 0;
4710 }
4711
4712 static int name2uid(unsigned int *id, const char *name)
4713 {
4714         struct passwd *passwd;
4715
4716         passwd = getpwnam(name);
4717         if (!passwd)
4718                 return -ENOENT;
4719         *id = passwd->pw_uid;
4720
4721         return 0;
4722 }
4723
4724 static int name2gid(unsigned int *id, const char *name)
4725 {
4726         struct group *group;
4727
4728         group = getgrnam(name);
4729         if (!group)
4730                 return -ENOENT;
4731         *id = group->gr_gid;
4732
4733         return 0;
4734 }
4735
4736 static inline int name2projid(unsigned int *id, const char *name)
4737 {
4738         return -ENOTSUP;
4739 }
4740
4741 static int uid2name(char **name, unsigned int id)
4742 {
4743         struct passwd *passwd;
4744
4745         passwd = getpwuid(id);
4746         if (!passwd)
4747                 return -ENOENT;
4748         *name = passwd->pw_name;
4749
4750         return 0;
4751 }
4752
4753 static inline int gid2name(char **name, unsigned int id)
4754 {
4755         struct group *group;
4756
4757         group = getgrgid(id);
4758         if (!group)
4759                 return -ENOENT;
4760         *name = group->gr_name;
4761
4762         return 0;
4763 }
4764
4765 static int name2layout(__u32 *layout, char *name)
4766 {
4767         char *ptr, *layout_name;
4768
4769         *layout = 0;
4770         for (ptr = name; ; ptr = NULL) {
4771                 layout_name = strtok(ptr, ",");
4772                 if (!layout_name)
4773                         break;
4774                 if (strcmp(layout_name, "released") == 0)
4775                         *layout |= LOV_PATTERN_F_RELEASED;
4776                 else if (strcmp(layout_name, "raid0") == 0)
4777                         *layout |= LOV_PATTERN_RAID0;
4778                 else if (strcmp(layout_name, "mdt") == 0)
4779                         *layout |= LOV_PATTERN_MDT;
4780                 else if (strcmp(layout_name, "overstriping") == 0)
4781                         *layout |= LOV_PATTERN_OVERSTRIPING;
4782                 else
4783                         return -1;
4784         }
4785         return 0;
4786 }
4787
4788 static int parse_symbolic(const char *input, mode_t *outmode, const char **end)
4789 {
4790         int loop;
4791         int user, group, other;
4792         int who, all;
4793         char c, op;
4794         mode_t perm;
4795         mode_t usermask;
4796         mode_t previous_flags;
4797
4798         user = group = other = 0;
4799         all = 0;
4800         loop = 1;
4801         perm = 0;
4802         previous_flags = 0;
4803         *end = input;
4804         usermask = 0;
4805
4806         while (loop) {
4807                 switch (*input) {
4808                 case 'u':
4809                         user = 1;
4810                         break;
4811                 case 'g':
4812                         group = 1;
4813                         break;
4814                 case 'o':
4815                         other = 1;
4816                         break;
4817                 case 'a':
4818                         user = group = other = 1;
4819                         all = 1;
4820                         break;
4821                 default:
4822                         loop = 0;
4823                 }
4824
4825                 if (loop)
4826                         input++;
4827         }
4828
4829         who = user || group || other;
4830         if (!who) {
4831                 /* get the umask */
4832                 usermask = umask(0022);
4833                 umask(usermask);
4834                 usermask &= 07777;
4835         }
4836
4837         if (*input == '-' || *input == '+' || *input == '=')
4838                 op = *input++;
4839         else
4840                 /* operation is required */
4841                 return -1;
4842
4843         /* get the flags in *outmode */
4844         switch (*input) {
4845         case 'u':
4846                 previous_flags = (*outmode & 0700);
4847                 perm |= user  ? previous_flags : 0;
4848                 perm |= group ? (previous_flags >> 3) : 0;
4849                 perm |= other ? (previous_flags >> 6) : 0;
4850                 input++;
4851                 goto write_perm;
4852         case 'g':
4853                 previous_flags = (*outmode & 0070);
4854                 perm |= user  ? (previous_flags << 3) : 0;
4855                 perm |= group ? previous_flags : 0;
4856                 perm |= other ? (previous_flags >> 3) : 0;
4857                 input++;
4858                 goto write_perm;
4859         case 'o':
4860                 previous_flags = (*outmode & 0007);
4861                 perm |= user  ? (previous_flags << 6) : 0;
4862                 perm |= group ? (previous_flags << 3) : 0;
4863                 perm |= other ? previous_flags : 0;
4864                 input++;
4865                 goto write_perm;
4866         default:
4867                 break;
4868         }
4869
4870         /* this part is optional,
4871          * if empty perm = 0 and *outmode is not modified
4872          */
4873         loop = 1;
4874         while (loop) {
4875                 c = *input;
4876                 switch (c) {
4877                 case 'r':
4878                         perm |= user  ? 0400 : 0;
4879                         perm |= group ? 0040 : 0;
4880                         perm |= other ? 0004 : 0;
4881                         /* set read permission for uog except for umask's
4882                          * permissions
4883                          */
4884                         perm |= who   ? 0 : (0444 & ~usermask);
4885                         break;
4886                 case 'w':
4887                         perm |= user  ? 0200 : 0;
4888                         perm |= group ? 0020 : 0;
4889                         perm |= other ? 0002 : 0;
4890                         /* set write permission for uog except for umask'
4891                          * permissions
4892                          */
4893                         perm |= who   ? 0 : (0222 & ~usermask);
4894                         break;
4895                 case 'x':
4896                         perm |= user  ? 0100 : 0;
4897                         perm |= group ? 0010 : 0;
4898                         perm |= other ? 0001 : 0;
4899                         /* set execute permission for uog except for umask'
4900                          * permissions
4901                          */
4902                         perm |= who   ? 0 : (0111 & ~usermask);
4903                         break;
4904                 case 'X':
4905                         /*
4906                          * Adds execute permission to 'u', 'g' and/or 'g' if
4907                          * specified and either 'u', 'g' or 'o' already has
4908                          * execute permissions.
4909                          */
4910                         if ((*outmode & 0111) != 0) {
4911                                 perm |= user  ? 0100 : 0;
4912                                 perm |= group ? 0010 : 0;
4913                                 perm |= other ? 0001 : 0;
4914                                 perm |= !who  ? 0111 : 0;
4915                         }
4916                         break;
4917                 case 's':
4918                         /* s is ignored if o is given, but it's not an error */
4919                         if (other && !group && !user)
4920                                 break;
4921                         perm |= user  ? S_ISUID : 0;
4922                         perm |= group ? S_ISGID : 0;
4923                         break;
4924                 case 't':
4925                         /* 't' should be used when 'a' is given
4926                          * or who is empty
4927                          */
4928                         perm |= (!who || all) ? S_ISVTX : 0;
4929                         /* using ugo with t is not an error */
4930                         break;
4931                 default:
4932                         loop = 0;
4933                         break;
4934                 }
4935                 if (loop)
4936                         input++;
4937         }
4938
4939 write_perm:
4940         /* uog flags should be only one character long */
4941         if (previous_flags && (*input != '\0' && *input != ','))
4942                 return -1;
4943
4944         switch (op) {
4945         case '-':
4946                 /* remove the flags from outmode */
4947                 *outmode &= ~perm;
4948                 break;
4949         case '+':
4950                 /* add the flags to outmode */
4951                 *outmode |= perm;
4952                 break;
4953         case '=':
4954                 /* set the flags of outmode to perm */
4955                 if (perm != 0)
4956                         *outmode = perm;
4957                 break;
4958         }
4959
4960         *end = input;
4961         return 0;
4962 }
4963
4964 static int str2mode_t(const char *input, mode_t *outmode)
4965 {
4966         int ret;
4967         const char *iter;
4968
4969         ret = 0;
4970
4971         if (*input >= '0' && *input <= '7') {
4972                 /* parse octal representation */
4973                 char *end;
4974
4975                 iter = input;
4976
4977                 /* look for invalid digits in octal representation */
4978                 while (isdigit(*iter))
4979                         if (*iter++ > '7')
4980                                 return -1;
4981
4982                 errno = 0;
4983                 *outmode = strtoul(input, &end, 8);
4984
4985                 if (errno != 0 || *outmode > 07777) {
4986                         *outmode = 0;
4987                         ret = -1;
4988                 }
4989
4990         } else if (*input == '8' || *input == '9') {
4991                 /* error: invalid octal number */
4992                 ret = -1;
4993         } else {
4994                 /* parse coma seperated list of symbolic representation */
4995                 int rc;
4996                 const char *end;
4997
4998                 *outmode = 0;
4999                 rc = 0;
5000                 end = NULL;
5001
5002                 do {
5003                         rc = parse_symbolic(input, outmode, &end);
5004                         if (rc)
5005                                 return -1;
5006
5007                         input = end+1;
5008                 } while (*end == ',');
5009
5010                 if (*end != '\0')
5011                         ret = -1;
5012         }
5013         return ret;
5014 }
5015
5016 static int lfs_find(int argc, char **argv)
5017 {
5018         int c, rc;
5019         int ret = 0;
5020         time_t t;
5021         struct find_param param = {
5022                 .fp_max_depth = -1,
5023                 .fp_quiet = 1,
5024                 .fp_time_margin = FP_DEFAULT_TIME_MARGIN,
5025         };
5026         struct option long_opts[] = {
5027         { .val = 'A',   .name = "atime",        .has_arg = required_argument },
5028         { .val = 'b',   .name = "blocks",       .has_arg = required_argument },
5029         { .val = 'B',   .name = "btime",        .has_arg = required_argument },
5030         { .val = 'B',   .name = "Btime",        .has_arg = required_argument },
5031         { .val = LFS_COMP_COUNT_OPT,
5032                         .name = "comp-count",   .has_arg = required_argument },
5033         { .val = LFS_COMP_COUNT_OPT,
5034                         .name = "component-count",
5035                                                 .has_arg = required_argument },
5036         { .val = LFS_COMP_FLAGS_OPT,
5037                         .name = "comp-flags",   .has_arg = required_argument },
5038         { .val = LFS_COMP_FLAGS_OPT,
5039                         .name = "component-flags",
5040                                                 .has_arg = required_argument },
5041         { .val = LFS_COMP_START_OPT,
5042                         .name = "comp-start",   .has_arg = required_argument },
5043         { .val = LFS_COMP_START_OPT,
5044                         .name = "component-start",
5045                                                 .has_arg = required_argument },
5046         { .val = LFS_MIRROR_STATE_OPT,
5047                         .name = "mirror-state", .has_arg = required_argument },
5048         { .val = LFS_NEWERXY_OPT,
5049                         .name = "newer",        .has_arg = required_argument},
5050         { .val = LFS_NEWERXY_OPT,
5051                         .name = "neweraa",      .has_arg = required_argument},
5052         { .val = LFS_NEWERXY_OPT,
5053                         .name = "neweram",      .has_arg = required_argument},
5054         { .val = LFS_NEWERXY_OPT,
5055                         .name = "newerac",      .has_arg = required_argument},
5056         { .val = LFS_NEWERXY_OPT,
5057                         .name = "newerab",      .has_arg = required_argument},
5058         { .val = LFS_NEWERXY_OPT,
5059                         .name = "newerma",      .has_arg = required_argument},
5060         { .val = LFS_NEWERXY_OPT,
5061                         .name = "newermm",      .has_arg = required_argument},
5062         { .val = LFS_NEWERXY_OPT,
5063                         .name = "newermc",      .has_arg = required_argument},
5064         { .val = LFS_NEWERXY_OPT,
5065                         .name = "newermb",      .has_arg = required_argument},
5066         { .val = LFS_NEWERXY_OPT,
5067                         .name = "newerca",      .has_arg = required_argument},
5068         { .val = LFS_NEWERXY_OPT,
5069                         .name = "newercm",      .has_arg = required_argument},
5070         { .val = LFS_NEWERXY_OPT,
5071                         .name = "newercc",      .has_arg = required_argument},
5072         { .val = LFS_NEWERXY_OPT,
5073                         .name = "newercb",      .has_arg = required_argument},
5074         { .val = LFS_NEWERXY_OPT,
5075                         .name = "newerba",      .has_arg = required_argument},
5076         { .val = LFS_NEWERXY_OPT,
5077                         .name = "newerbm",      .has_arg = required_argument},
5078         { .val = LFS_NEWERXY_OPT,
5079                         .name = "newerbc",      .has_arg = required_argument},
5080         { .val = LFS_NEWERXY_OPT,
5081                         .name = "newerbb",      .has_arg = required_argument},
5082         { .val = LFS_NEWERXY_OPT,
5083                         .name = "newerBa",      .has_arg = required_argument},
5084         { .val = LFS_NEWERXY_OPT,
5085                         .name = "newerBm",      .has_arg = required_argument},
5086         { .val = LFS_NEWERXY_OPT,
5087                         .name = "newerBc",      .has_arg = required_argument},
5088         { .val = LFS_NEWERXY_OPT,
5089                         .name = "newerBB",      .has_arg = required_argument},
5090         { .val = LFS_NEWERXY_OPT,
5091                         .name = "newerat",      .has_arg = required_argument},
5092         { .val = LFS_NEWERXY_OPT,
5093                         .name = "newermt",      .has_arg = required_argument},
5094         { .val = LFS_NEWERXY_OPT,
5095                         .name = "newerct",      .has_arg = required_argument},
5096         { .val = LFS_NEWERXY_OPT,
5097                         .name = "newerbt",      .has_arg = required_argument},
5098         { .val = LFS_NEWERXY_OPT,
5099                         .name = "newerBt",      .has_arg = required_argument},
5100         { .val = 'c',   .name = "stripe-count", .has_arg = required_argument },
5101         { .val = 'c',   .name = "stripe_count", .has_arg = required_argument },
5102         { .val = 'C',   .name = "ctime",        .has_arg = required_argument },
5103 /* getstripe { .val = 'd', .name = "directory", .has_arg = no_argument }, */
5104         { .val = 'D',   .name = "maxdepth",     .has_arg = required_argument },
5105         { .val = 'E',   .name = "comp-end",     .has_arg = required_argument },
5106         { .val = 'E',   .name = "component-end",
5107                                                 .has_arg = required_argument },
5108 /* find { .val = 'F',   .name = "fid",          .has_arg = no_argument }, */
5109         { .val = LFS_LAYOUT_FOREIGN_OPT,
5110                         .name = "foreign",      .has_arg = optional_argument},
5111         { .val = 'g',   .name = "gid",          .has_arg = required_argument },
5112         { .val = 'G',   .name = "group",        .has_arg = required_argument },
5113         { .val = 'h',   .name = "help",         .has_arg = no_argument },
5114         { .val = 'H',   .name = "mdt-hash",     .has_arg = required_argument },
5115         { .val = 'i',   .name = "stripe-index", .has_arg = required_argument },
5116         { .val = 'i',   .name = "stripe_index", .has_arg = required_argument },
5117 /* getstripe { .val = 'I', .name = "comp-id",   .has_arg = required_argument }*/
5118         { .val = 'l',   .name = "lazy",         .has_arg = no_argument },
5119         { .val = 'L',   .name = "layout",       .has_arg = required_argument },
5120         { .val = LFS_LINKS_OPT,
5121                         .name = "links",        .has_arg = required_argument },
5122         { .val = 'm',   .name = "mdt",          .has_arg = required_argument },
5123         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument },
5124         { .val = 'm',   .name = "mdt_index",    .has_arg = required_argument },
5125         { .val = 'M',   .name = "mtime",        .has_arg = required_argument },
5126         { .val = 'n',   .name = "name",         .has_arg = required_argument },
5127         { .val = 'N',   .name = "mirror-count", .has_arg = required_argument },
5128 /* find { .val = 'o'    .name = "or", .has_arg = no_argument }, like find(1) */
5129         { .val = 'O',   .name = "obd",          .has_arg = required_argument },
5130         { .val = 'O',   .name = "ost",          .has_arg = required_argument },
5131         { .val = LFS_FIND_PERM,
5132                         .name = "perm",         .has_arg = required_argument },
5133         /* no short option for pool yet, can be 'p' after 2.18 */
5134         { .val = LFS_POOL_OPT,
5135                         .name = "pool",         .has_arg = required_argument },
5136         { .val = '0',   .name = "print0",       .has_arg = no_argument },
5137         { .val = 'P',   .name = "print",        .has_arg = no_argument },
5138         { .val = LFS_PRINTF_OPT,
5139                         .name = "printf",       .has_arg = required_argument },
5140         { .val = LFS_PROJID_OPT,
5141                         .name = "projid",       .has_arg = required_argument },
5142 /* getstripe { .val = 'q', .name = "quiet",     .has_arg = no_argument }, */
5143 /* getstripe { .val = 'r', .name = "recursive", .has_arg = no_argument }, */
5144 /* getstripe { .val = 'R', .name = "raw",       .has_arg = no_argument }, */
5145         { .val = 's',   .name = "size",         .has_arg = required_argument },
5146         { .val = 'S',   .name = "stripe-size",  .has_arg = required_argument },
5147         { .val = 'S',   .name = "stripe_size",  .has_arg = required_argument },
5148         { .val = 't',   .name = "type",         .has_arg = required_argument },
5149         { .val = 'T',   .name = "mdt-count",    .has_arg = required_argument },
5150         { .val = 'u',   .name = "uid",          .has_arg = required_argument },
5151         { .val = 'U',   .name = "user",         .has_arg = required_argument },
5152 /* getstripe { .val = 'v', .name = "verbose",   .has_arg = no_argument }, */
5153 /* setstripe { .val = 'W', .name = "bandwidth", .has_arg = required_argument }, */
5154         { .val = 'z',   .name = "extension-size",
5155                                                 .has_arg = required_argument },
5156         { .val = 'z',   .name = "ext-size",     .has_arg = required_argument },
5157         { .name = NULL } };
5158         int optidx = 0;
5159         int pathstart = -1;
5160         int pathend = -1;
5161         int pathbad = -1;
5162         int neg_opt = 0;
5163         time_t *xtime;
5164         int *xsign;
5165         int isoption;
5166         char *endptr;
5167
5168         time(&t);
5169
5170         /* when getopt_long_only() hits '!' it returns 1, puts "!" in optarg */
5171         while ((c = getopt_long_only(argc, argv,
5172                 "-0A:b:B:c:C:D:E:g:G:hH:i:lL:m:M:n:N:O:Ppqrs:S:t:T:u:U:z:",
5173                 long_opts, &optidx)) >= 0) {
5174                 xtime = NULL;
5175                 xsign = NULL;
5176                 if (neg_opt)
5177                         --neg_opt;
5178                 /* '!' is part of option */
5179                 /*
5180                  * when getopt_long_only() finds a string which is not
5181                  * an option nor a known option argument it returns 1
5182                  * in that case if we already have found pathstart and pathend
5183                  * (i.e. we have the list of pathnames),
5184                  * the only supported value is "!"
5185                  */
5186                 isoption = (c != 1) || (strcmp(optarg, "!") == 0);
5187                 if (!isoption && pathend != -1) {
5188                         fprintf(stderr,
5189                                 "err: %s: filename|dirname must either precede options or follow options\n",
5190                                 argv[0]);
5191                         ret = CMD_HELP;
5192                         goto err;
5193                 }
5194                 if (!isoption && pathstart == -1)
5195                         pathstart = optind - 1;
5196                 if (isoption && pathstart != -1 && pathend == -1)
5197                         pathend = optind - 2;
5198                 switch (c) {
5199                 case 0:
5200                         /* Long options. */
5201                         break;
5202                 case 1:
5203                         /*
5204                          * unknown; opt is "!" or path component,
5205                          * checking done above.
5206                          */
5207                         if (strcmp(optarg, "!") == 0)
5208                                 neg_opt = 2;
5209                         break;
5210                 case 'A':
5211                         xtime = &param.fp_atime;
5212                         xsign = &param.fp_asign;
5213                         param.fp_exclude_atime = !!neg_opt;
5214                         /* no break, this falls through to 'B' for btime */
5215                         fallthrough;
5216                 case 'B':
5217                         if (c == 'B') {
5218                                 xtime = &param.fp_btime;
5219                                 xsign = &param.fp_bsign;
5220                                 param.fp_exclude_btime = !!neg_opt;
5221                         }
5222                         /* no break, this falls through to 'C' for ctime */
5223                         fallthrough;
5224                 case 'C':
5225                         if (c == 'C') {
5226                                 xtime = &param.fp_ctime;
5227                                 xsign = &param.fp_csign;
5228                                 param.fp_exclude_ctime = !!neg_opt;
5229                         }
5230                         /* no break, this falls through to 'M' for mtime */
5231                         fallthrough;
5232                 case 'M':
5233                         if (c == 'M') {
5234                                 xtime = &param.fp_mtime;
5235                                 xsign = &param.fp_msign;
5236                                 param.fp_exclude_mtime = !!neg_opt;
5237                         }
5238                         rc = set_time(&param, &t, xtime, optarg);
5239                         if (rc == INT_MAX) {
5240                                 ret = -1;
5241                                 goto err;
5242                         }
5243                         if (rc)
5244                                 *xsign = rc;
5245                         break;
5246                 case 'b':
5247                         if (optarg[0] == '+') {
5248                                 param.fp_blocks_sign = -1;
5249                                 optarg++;
5250                         } else if (optarg[0] == '-') {
5251                                 param.fp_blocks_sign =  1;
5252                                 optarg++;
5253                         }
5254
5255                         param.fp_blocks_units = 1024;
5256                         ret = llapi_parse_size(optarg, &param.fp_blocks,
5257                                                &param.fp_blocks_units, 0);
5258                         if (ret) {
5259                                 fprintf(stderr, "error: bad blocks '%s'\n",
5260                                         optarg);
5261                                 goto err;
5262                         }
5263                         param.fp_check_blocks = 1;
5264                         param.fp_exclude_blocks = !!neg_opt;
5265                         break;
5266                 case LFS_COMP_COUNT_OPT:
5267                         if (optarg[0] == '+') {
5268                                 param.fp_comp_count_sign = -1;
5269                                 optarg++;
5270                         } else if (optarg[0] == '-') {
5271                                 param.fp_comp_count_sign =  1;
5272                                 optarg++;
5273                         }
5274
5275                         errno = 0;
5276                         param.fp_comp_count = strtoul(optarg, &endptr, 0);
5277                         if (errno != 0 || *endptr != '\0' ||
5278                             param.fp_comp_count > UINT32_MAX) {
5279                                 fprintf(stderr,
5280                                         "error: bad component count '%s'\n",
5281                                         optarg);
5282                                 goto err;
5283                         }
5284                         param.fp_check_comp_count = 1;
5285                         param.fp_exclude_comp_count = !!neg_opt;
5286                         break;
5287                 case LFS_COMP_FLAGS_OPT:
5288                         rc = comp_str2flags(optarg, &param.fp_comp_flags,
5289                                             &param.fp_comp_neg_flags);
5290                         if (rc) {
5291                                 fprintf(stderr,
5292                                         "error: bad component flags '%s'\n",
5293                                         optarg);
5294                                 goto err;
5295                         }
5296                         param.fp_check_comp_flags = 1;
5297                         if (neg_opt) {
5298                                 __u32 flags = param.fp_comp_neg_flags;
5299
5300                                 param.fp_comp_neg_flags = param.fp_comp_flags;
5301                                 param.fp_comp_flags = flags;
5302                         }
5303                         break;
5304                 case LFS_COMP_START_OPT:
5305                         if (optarg[0] == '+') {
5306                                 param.fp_comp_start_sign = -1;
5307                                 optarg++;
5308                         } else if (optarg[0] == '-') {
5309                                 param.fp_comp_start_sign =  1;
5310                                 optarg++;
5311                         }
5312
5313                         rc = llapi_parse_size(optarg, &param.fp_comp_start,
5314                                               &param.fp_comp_start_units, 0);
5315                         if (rc) {
5316                                 fprintf(stderr,
5317                                         "error: bad component start '%s'\n",
5318                                         optarg);
5319                                 goto err;
5320                         }
5321                         param.fp_check_comp_start = 1;
5322                         param.fp_exclude_comp_start = !!neg_opt;
5323                         break;
5324                 case LFS_MIRROR_STATE_OPT:
5325                         rc = mirror_str2state(optarg, &param.fp_mirror_state,
5326                                               &param.fp_mirror_neg_state);
5327                         if (rc) {
5328                                 fprintf(stderr,
5329                                         "error: bad mirrored file state '%s'\n",
5330                                         optarg);
5331                                 goto err;
5332                         }
5333                         param.fp_check_mirror_state = 1;
5334                         if (neg_opt) {
5335                                 __u16 state = param.fp_mirror_neg_state;
5336
5337                                 param.fp_mirror_neg_state =
5338                                         param.fp_mirror_state;
5339                                 param.fp_mirror_state = state;
5340                         }
5341                         break;
5342                 case 'c':
5343                         if (optarg[0] == '+') {
5344                                 param.fp_stripe_count_sign = -1;
5345                                 optarg++;
5346                         } else if (optarg[0] == '-') {
5347                                 param.fp_stripe_count_sign =  1;
5348                                 optarg++;
5349                         }
5350
5351                         errno = 0;
5352                         param.fp_stripe_count = strtoul(optarg, &endptr, 0);
5353                         if (errno != 0 || *endptr != '\0' ||
5354                             param.fp_stripe_count > LOV_MAX_STRIPE_COUNT) {
5355                                 fprintf(stderr,
5356                                         "error: bad stripe_count '%s'\n",
5357                                         optarg);
5358                                 ret = -1;
5359                                 goto err;
5360                         }
5361                         param.fp_check_stripe_count = 1;
5362                         param.fp_exclude_stripe_count = !!neg_opt;
5363                         break;
5364                 case 'D':
5365                         errno = 0;
5366                         param.fp_max_depth = strtol(optarg, 0, 0);
5367                         if (errno != 0 || param.fp_max_depth < 0) {
5368                                 fprintf(stderr,
5369                                         "error: bad maxdepth '%s'\n",
5370                                         optarg);
5371                                 ret = -1;
5372                                 goto err;
5373                         }
5374                         break;
5375                 case 'E':
5376                         if (optarg[0] == '+') {
5377                                 param.fp_comp_end_sign = -1;
5378                                 optarg++;
5379                         } else if (optarg[0] == '-') {
5380                                 param.fp_comp_end_sign =  1;
5381                                 optarg++;
5382                         }
5383
5384                         if (arg_is_eof(optarg)) {
5385                                 param.fp_comp_end = LUSTRE_EOF;
5386                                 param.fp_comp_end_units = 1;
5387                                 rc = 0;
5388                         } else {
5389                                 rc = llapi_parse_size(optarg,
5390                                                 &param.fp_comp_end,
5391                                                 &param.fp_comp_end_units, 0);
5392                                 /* assume units of KB if too small */
5393                                 if (param.fp_comp_end < 4096)
5394                                         param.fp_comp_end *= 1024;
5395                         }
5396                         if (rc) {
5397                                 fprintf(stderr,
5398                                         "error: bad component end '%s'\n",
5399                                         optarg);
5400                                 goto err;
5401                         }
5402                         param.fp_check_comp_end = 1;
5403                         param.fp_exclude_comp_end = !!neg_opt;
5404                         break;
5405                 case LFS_LAYOUT_FOREIGN_OPT: {
5406                         /* all types by default */
5407                         uint32_t type = LU_FOREIGN_TYPE_UNKNOWN;
5408
5409                         if (optarg) {
5410                                 /* check pure numeric */
5411                                 type = strtoul(optarg, &endptr, 0);
5412                                 if (*endptr) {
5413                                         /* check name */
5414                                         type = check_foreign_type_name(optarg);
5415                                         if (type == LU_FOREIGN_TYPE_UNKNOWN) {
5416                                                 fprintf(stderr,
5417                                                         "%s %s: unknown foreign type '%s'\n",
5418                                                         progname, argv[0],
5419                                                         optarg);
5420                                                 return CMD_HELP;
5421                                         }
5422                                 } else if (type >= UINT32_MAX) {
5423                                         fprintf(stderr,
5424                                                 "%s %s: invalid foreign type '%s'\n",
5425                                                 progname, argv[0], optarg);
5426                                         return CMD_HELP;
5427                                 }
5428                         }
5429                         param.fp_foreign_type = type;
5430                         param.fp_check_foreign = 1;
5431                         param.fp_exclude_foreign = !!neg_opt;
5432                         break;
5433                 }
5434                 case LFS_NEWERXY_OPT: {
5435                         char x = 'm';
5436                         char y = 'm';
5437                         int xidx;
5438                         int negidx;
5439                         time_t *newery;
5440                         time_t ref = time(NULL);
5441
5442                         /* no need to check bad options, they won't get here */
5443                         if (strlen(long_opts[optidx].name) == 7) {
5444                                 x = long_opts[optidx].name[5];
5445                                 y = long_opts[optidx].name[6];
5446                         }
5447
5448                         if (y == 't') {
5449                                 static const char *const fmts[] = {
5450                                         "%Y-%m-%d %H:%M:%S",
5451                                         "%Y-%m-%d %H:%M",
5452                                         "%Y-%m-%d",
5453                                         "%H:%M:%S", /* sometime today */
5454                                         "%H:%M",
5455                                         "@%s",
5456                                         "%s",
5457                                         NULL };
5458                                 struct tm tm;
5459                                 bool found = false;
5460                                 int i;
5461
5462                                 for (i = 0; fmts[i] != NULL; i++) {
5463                                         char *ptr;
5464
5465                                         /* Init for times relative to today */
5466                                         if (strncmp(fmts[i], "%H", 2) == 0) {
5467                                                 localtime_r(&ref, &tm);
5468                                         } else {
5469                                                 memset(&tm, 0, sizeof(tm));
5470                                                 tm.tm_isdst = -1;
5471                                         }
5472                                         ptr = strptime(optarg, fmts[i], &tm);
5473                                         /* Skip spaces */
5474                                         while (ptr && isspace(*ptr))
5475                                                 ptr++;
5476                                         if (ptr == optarg + strlen(optarg)) {
5477                                                 found = true;
5478                                                 break;
5479                                         }
5480                                 }
5481
5482                                 if (!found) {
5483                                         fprintf(stderr,
5484                                                 "%s: invalid time '%s'\n",
5485                                                 progname, optarg);
5486                                         fprintf(stderr,
5487                                                 "supported formats are:\n  ");
5488                                         for (i = 0; fmts[i] != NULL; i++)
5489                                                 fprintf(stderr, "'%s', ",
5490                                                         fmts[i]);
5491                                         fprintf(stderr, "\n");
5492                                         ret = -EINVAL;
5493                                         goto err;
5494                                 }
5495
5496                                 ref = mktime(&tm);
5497                         } else if (y == 'b' || y == 'B') {
5498                                 lstatx_t stx;
5499
5500                                 rc = llapi_get_lum_file(optarg, NULL, &stx,
5501                                                         NULL, 0);
5502                                 if (rc || !(stx.stx_mask & STATX_BTIME)) {
5503                                         if (!(stx.stx_mask & STATX_BTIME))
5504                                                 ret = -EOPNOTSUPP;
5505                                         else
5506                                                 ret = -errno;
5507                                         fprintf(stderr,
5508                                                 "%s: get btime failed '%s': %s\n",
5509                                                 progname, optarg,
5510                                                 strerror(-ret));
5511                                         goto err;
5512                                 }
5513
5514                                 ref = stx.stx_btime.tv_sec;
5515                         } else {
5516                                 struct stat statbuf;
5517
5518                                 if (stat(optarg, &statbuf) < 0) {
5519                                         fprintf(stderr,
5520                                                 "%s: cannot stat file '%s': %s\n",
5521                                                 progname, optarg,
5522                                                 strerror(errno));
5523                                         ret = -errno;
5524                                         goto err;
5525                                 }
5526
5527                                 switch (y) {
5528                                 case 'a':
5529                                         ref = statbuf.st_atime;
5530                                         break;
5531                                 case 'm':
5532                                         ref = statbuf.st_mtime;
5533                                         break;
5534                                 case 'c':
5535                                         ref = statbuf.st_ctime;
5536                                         break;
5537                                 default:
5538                                         fprintf(stderr,
5539                                                 "%s: invalid Y argument: '%c'\n",
5540                                                 progname, x);
5541                                         ret = -EINVAL;
5542                                         goto err;
5543                                 }
5544                         }
5545
5546                         switch (x) {
5547                         case 'a':
5548                                 xidx = NEWERXY_ATIME;
5549                                 break;
5550                         case 'm':
5551                                 xidx = NEWERXY_MTIME;
5552                                 break;
5553                         case 'c':
5554                                 xidx = NEWERXY_CTIME;
5555                                 break;
5556                         case 'b':
5557                         case 'B':
5558                                 xidx = NEWERXY_BTIME;
5559                                 break;
5560                         default:
5561                                 fprintf(stderr,
5562                                         "%s: invalid X argument: '%c'\n",
5563                                         progname, x);
5564                                 ret = -EINVAL;
5565                                 goto err;
5566                         }
5567
5568                         negidx = !!neg_opt;
5569                         newery = &param.fp_newery[xidx][negidx];
5570
5571                         if (*newery == 0) {
5572                                 *newery = ref;
5573                         } else {
5574                                 if (negidx)
5575                                         *newery = *newery > ref ? ref : *newery;
5576                                 else
5577                                         *newery = *newery > ref ? *newery : ref;
5578                         }
5579                         param.fp_newerxy = 1;
5580                         break;
5581                 }
5582                 case 'g':
5583                 case 'G':
5584                         rc = name2gid(&param.fp_gid, optarg);
5585                         if (rc) {
5586                                 if (str2quotaid(&param.fp_gid, optarg)) {
5587                                         fprintf(stderr,
5588                                                 "Group/GID: %s cannot be found.\n",
5589                                                 optarg);
5590                                         ret = -1;
5591                                         goto err;
5592                                 }
5593                         }
5594                         param.fp_exclude_gid = !!neg_opt;
5595                         param.fp_check_gid = 1;
5596                         break;
5597                 case 'H':
5598                         rc = mdthash_input(optarg, &param.fp_hash_inflags,
5599                                            &param.fp_hash_exflags,
5600                                            &param.fp_hash_type);
5601                         if (rc) {
5602                                 ret = -1;
5603                                 goto err;
5604                         }
5605                         if (param.fp_hash_inflags || param.fp_hash_exflags)
5606                                 param.fp_check_hash_flag = 1;
5607                         param.fp_exclude_hash_type = !!neg_opt;
5608                         break;
5609                 case 'l':
5610                         param.fp_lazy = 1;
5611                         break;
5612                 case 'L':
5613                         ret = name2layout(&param.fp_layout, optarg);
5614                         if (ret)
5615                                 goto err;
5616                         param.fp_exclude_layout = !!neg_opt;
5617                         param.fp_check_layout = 1;
5618                         break;
5619                 case LFS_LINKS_OPT:
5620                         if (optarg[0] == '+') {
5621                                 param.fp_nlink_sign = -1;
5622                                 optarg++;
5623                         } else if (optarg[0] == '-') {
5624                                 param.fp_nlink_sign =  1;
5625                                 optarg++;
5626                         }
5627                         errno = 0;
5628                         param.fp_nlink = strtoul(optarg, &endptr, 0);
5629                         if (errno != 0 || *endptr != '\0' || !param.fp_nlink) {
5630                                 fprintf(stderr, "error: bad link count '%s'\n",
5631                                         optarg);
5632                                 ret = -1;
5633                                 goto err;
5634                         }
5635                         param.fp_exclude_nlink = !!neg_opt;
5636                         break;
5637                 case 'u':
5638                 case 'U':
5639                         rc = name2uid(&param.fp_uid, optarg);
5640                         if (rc) {
5641                                 if (str2quotaid(&param.fp_uid, optarg)) {
5642                                         fprintf(stderr,
5643                                                 "User/UID: %s cannot be found.\n",
5644                                                 optarg);
5645                                         ret = -1;
5646                                         goto err;
5647                                 }
5648                         }
5649                         param.fp_exclude_uid = !!neg_opt;
5650                         param.fp_check_uid = 1;
5651                         break;
5652                 case 'n':
5653                         param.fp_pattern = (char *)optarg;
5654                         param.fp_exclude_pattern = !!neg_opt;
5655                         break;
5656                 case 'N':
5657                         if (optarg[0] == '+') {
5658                                 param.fp_mirror_count_sign = -1;
5659                                 optarg++;
5660                         } else if (optarg[0] == '-') {
5661                                 param.fp_mirror_count_sign =  1;
5662                                 optarg++;
5663                         }
5664
5665                         errno = 0;
5666                         param.fp_mirror_count = strtoul(optarg, &endptr, 0);
5667                         if (errno != 0 || *endptr != '\0' ||
5668                             param.fp_mirror_count > LUSTRE_MIRROR_COUNT_MAX) {
5669                                 fprintf(stderr,
5670                                         "error: bad mirror count '%s'\n",
5671                                         optarg);
5672                                 goto err;
5673                         }
5674                         param.fp_check_mirror_count = 1;
5675                         param.fp_exclude_mirror_count = !!neg_opt;
5676                         break;
5677                 case 'm':
5678                 case 'i':
5679                 case 'O': {
5680                         char *buf, *token, *next, *p;
5681                         int len = 1;
5682                         void *tmp;
5683
5684                         buf = strdup(optarg);
5685                         if (!buf) {
5686                                 ret = -ENOMEM;
5687                                 goto err;
5688                         }
5689
5690                         param.fp_exclude_obd = !!neg_opt;
5691
5692                         token = buf;
5693                         while (token && *token) {
5694                                 token = strchr(token, ',');
5695                                 if (token) {
5696                                         len++;
5697                                         token++;
5698                                 }
5699                         }
5700                         if (c == 'm') {
5701                                 param.fp_exclude_mdt = !!neg_opt;
5702                                 param.fp_num_alloc_mdts += len;
5703                                 tmp = realloc(param.fp_mdt_uuid,
5704                                               param.fp_num_alloc_mdts *
5705                                               sizeof(*param.fp_mdt_uuid));
5706                                 if (!tmp) {
5707                                         ret = -ENOMEM;
5708                                         goto err_free;
5709                                 }
5710
5711                                 param.fp_mdt_uuid = tmp;
5712                         } else {
5713                                 param.fp_exclude_obd = !!neg_opt;
5714                                 param.fp_num_alloc_obds += len;
5715                                 tmp = realloc(param.fp_obd_uuid,
5716                                               param.fp_num_alloc_obds *
5717                                               sizeof(*param.fp_obd_uuid));
5718                                 if (!tmp) {
5719                                         ret = -ENOMEM;
5720                                         goto err_free;
5721                                 }
5722
5723                                 param.fp_obd_uuid = tmp;
5724                         }
5725                         for (token = buf; token && *token; token = next) {
5726                                 struct obd_uuid *puuid;
5727
5728                                 if (c == 'm') {
5729                                         puuid =
5730                                         &param.fp_mdt_uuid[param.fp_num_mdts++];
5731                                 } else {
5732                                         puuid =
5733                                         &param.fp_obd_uuid[param.fp_num_obds++];
5734                                 }
5735                                 p = strchr(token, ',');
5736                                 next = 0;
5737                                 if (p) {
5738                                         *p = 0;
5739                                         next = p+1;
5740                                 }
5741
5742                                 if (strlen(token) > sizeof(puuid->uuid) - 1) {
5743                                         ret = -E2BIG;
5744                                         goto err_free;
5745                                 }
5746
5747                                 strncpy(puuid->uuid, token,
5748                                         sizeof(puuid->uuid));
5749                         }
5750 err_free:
5751                         if (buf)
5752                                 free(buf);
5753                         break;
5754                 }
5755 #if LUSTRE_VERSION_CODE >= OBD_OCD_VERSION(2, 18, 53, 0)
5756                 case 'p':
5757 #endif
5758                 case LFS_POOL_OPT:
5759                         if (strlen(optarg) > LOV_MAXPOOLNAME) {
5760                                 fprintf(stderr,
5761                                         "Pool name %s is too long (max %d)\n",
5762                                         optarg, LOV_MAXPOOLNAME);
5763                                 ret = -1;
5764                                 goto err;
5765                         }
5766                         /*
5767                          * We do check for empty pool because empty pool
5768                          * is used to find V1 LOV attributes
5769                          */
5770                         strncpy(param.fp_poolname, optarg, LOV_MAXPOOLNAME);
5771                         param.fp_poolname[LOV_MAXPOOLNAME] = '\0';
5772                         param.fp_exclude_pool = !!neg_opt;
5773                         param.fp_check_pool = 1;
5774                         break;
5775                 case '0':
5776                         param.fp_zero_end = 1;
5777                         break;
5778                 case 'P': /* we always print, this option is a no-op */
5779                         break;
5780                 case LFS_PRINTF_OPT:
5781                         param.fp_format_printf_str = strdup(optarg);
5782                         break;
5783                 case LFS_PROJID_OPT:
5784                         rc = name2projid(&param.fp_projid, optarg);
5785                         if (rc) {
5786                                 if (str2quotaid(&param.fp_projid, optarg)) {
5787                                         fprintf(stderr,
5788                                                 "Invalid project ID: %s\n",
5789                                                 optarg);
5790                                         ret = -1;
5791                                         goto err;
5792                                 }
5793                         }
5794                         param.fp_exclude_projid = !!neg_opt;
5795                         param.fp_check_projid = 1;
5796                         break;
5797                 case 's':
5798                         if (optarg[0] == '+') {
5799                                 param.fp_size_sign = -1;
5800                                 optarg++;
5801                         } else if (optarg[0] == '-') {
5802                                 param.fp_size_sign =  1;
5803                                 optarg++;
5804                         }
5805
5806                         ret = llapi_parse_size(optarg, &param.fp_size,
5807                                                &param.fp_size_units, 0);
5808                         if (ret) {
5809                                 fprintf(stderr, "error: bad file size '%s'\n",
5810                                         optarg);
5811                                 goto err;
5812                         }
5813                         param.fp_check_size = 1;
5814                         param.fp_exclude_size = !!neg_opt;
5815                         break;
5816                 case 'S':
5817                         if (optarg[0] == '+') {
5818                                 param.fp_stripe_size_sign = -1;
5819                                 optarg++;
5820                         } else if (optarg[0] == '-') {
5821                                 param.fp_stripe_size_sign =  1;
5822                                 optarg++;
5823                         }
5824
5825                         ret = llapi_parse_size(optarg, &param.fp_stripe_size,
5826                                                &param.fp_stripe_size_units, 0);
5827                         /* assume units of KB if too small to be valid */
5828                         if (param.fp_stripe_size < 4096)
5829                                 param.fp_stripe_size *= 1024;
5830                         if (ret) {
5831                                 fprintf(stderr, "error: bad stripe_size '%s'\n",
5832                                         optarg);
5833                                 goto err;
5834                         }
5835                         param.fp_check_stripe_size = 1;
5836                         param.fp_exclude_stripe_size = !!neg_opt;
5837                         break;
5838                 case 't':
5839                         param.fp_exclude_type = !!neg_opt;
5840                         switch (optarg[0]) {
5841                         case 'b':
5842                                 param.fp_type = S_IFBLK;
5843                                 break;
5844                         case 'c':
5845                                 param.fp_type = S_IFCHR;
5846                                 break;
5847                         case 'd':
5848                                 param.fp_type = S_IFDIR;
5849                                 break;
5850                         case 'f':
5851                                 param.fp_type = S_IFREG;
5852                                 break;
5853                         case 'l':
5854                                 param.fp_type = S_IFLNK;
5855                                 break;
5856                         case 'p':
5857                                 param.fp_type = S_IFIFO;
5858                                 break;
5859                         case 's':
5860                                 param.fp_type = S_IFSOCK;
5861                                 break;
5862                         default:
5863                                 fprintf(stderr, "%s: bad type '%s'\n",
5864                                         progname, optarg);
5865                                 ret = CMD_HELP;
5866                                 goto err;
5867                         }
5868                         break;
5869                 case LFS_FIND_PERM:
5870                         param.fp_exclude_perm = !!neg_opt;
5871                         param.fp_perm_sign = LFS_FIND_PERM_EXACT;
5872                         if (*optarg == '/') {
5873                                 param.fp_perm_sign = LFS_FIND_PERM_ANY;
5874                                 optarg++;
5875                         } else if (*optarg == '-') {
5876                                 param.fp_perm_sign = LFS_FIND_PERM_ALL;
5877                                 optarg++;
5878                         }
5879
5880                         if (str2mode_t(optarg, &param.fp_perm)) {
5881                                 fprintf(stderr, "error: invalid mode '%s'\n",
5882                                         optarg);
5883                                 ret = -1;
5884                                 goto err;
5885                         }
5886                         break;
5887                 case 'T':
5888                         if (optarg[0] == '+') {
5889                                 param.fp_mdt_count_sign = -1;
5890                                 optarg++;
5891                         } else if (optarg[0] == '-') {
5892                                 param.fp_mdt_count_sign =  1;
5893                                 optarg++;
5894                         }
5895
5896                         errno = 0;
5897                         param.fp_mdt_count = strtoul(optarg, &endptr, 0);
5898                         if (errno != 0 || *endptr != '\0' ||
5899                             param.fp_mdt_count >= UINT32_MAX) {
5900                                 fprintf(stderr, "error: bad mdt_count '%s'\n",
5901                                         optarg);
5902                                 ret = -1;
5903                                 goto err;
5904                         }
5905                         param.fp_check_mdt_count = 1;
5906                         param.fp_exclude_mdt_count = !!neg_opt;
5907                         break;
5908                 case 'z':
5909                         if (optarg[0] == '+') {
5910                                 param.fp_ext_size_sign = -1;
5911                                 optarg++;
5912                         } else if (optarg[0] == '-') {
5913                                 param.fp_ext_size_sign =  1;
5914                                 optarg++;
5915                         }
5916
5917                         ret = llapi_parse_size(optarg, &param.fp_ext_size,
5918                                                &param.fp_ext_size_units, 0);
5919                         if (ret) {
5920                                 fprintf(stderr, "error: bad ext-size '%s'\n",
5921                                         optarg);
5922                                 goto err;
5923                         }
5924                         param.fp_ext_size /= SEL_UNIT_SIZE;
5925                         param.fp_ext_size_units /= SEL_UNIT_SIZE;
5926                         param.fp_check_ext_size = 1;
5927                         param.fp_exclude_ext_size = !!neg_opt;
5928                         break;
5929                 default:
5930                         fprintf(stderr, "%s: unrecognized option '%s'\n",
5931                                 progname, argv[optind - 1]);
5932                 case 'h':
5933                         ret = CMD_HELP;
5934                         goto err;
5935                 }
5936         }
5937         if (!param.fp_verbose)
5938                 param.fp_verbose = VERBOSE_DEFAULT;
5939
5940         if (pathstart == -1) {
5941                 fprintf(stderr, "error: %s: no filename|pathname\n",
5942                         argv[0]);
5943                 ret = CMD_HELP;
5944                 goto err;
5945         } else if (pathend == -1) {
5946                 /* no options */
5947                 pathend = argc;
5948         }
5949
5950         do {
5951                 rc = llapi_find(argv[pathstart], &param);
5952                 if (rc && !ret) {
5953                         ret = rc;
5954                         pathbad = pathstart;
5955                 }
5956         } while (++pathstart < pathend);
5957
5958         if (ret)
5959                 fprintf(stderr, "%s: failed for '%s': %s\n",
5960                         progname, argv[pathbad], strerror(-rc));
5961
5962 err:
5963         if (param.fp_obd_uuid && param.fp_num_alloc_obds)
5964                 free(param.fp_obd_uuid);
5965
5966         if (param.fp_mdt_uuid && param.fp_num_alloc_mdts)
5967                 free(param.fp_mdt_uuid);
5968
5969         if (param.fp_format_printf_str)
5970                 free(param.fp_format_printf_str);
5971
5972         return ret;
5973 }
5974
5975 static int lfs_getstripe_internal(int argc, char **argv,
5976                                   struct find_param *param)
5977 {
5978         struct option long_opts[] = {
5979 /* find { .val = 'A',   .name = "atime",        .has_arg = required_argument }*/
5980 /* find { .val = 'b',   .name = "blocks",       .has_arg = required_argument }*/
5981 /* find { .val = 'B',   .name = "btime",        .has_arg = required_argument }*/
5982 /* find { .val = 'B',   .name = "Btime",        .has_arg = required_argument }*/
5983         { .val = LFS_COMP_COUNT_OPT,
5984                         .name = "comp-count",   .has_arg = no_argument },
5985         { .val = LFS_COMP_COUNT_OPT,
5986                 .name = "component-count",      .has_arg = no_argument },
5987         { .val = LFS_COMP_FLAGS_OPT,
5988                         .name = "comp-flags",   .has_arg = optional_argument },
5989         { .val = LFS_COMP_FLAGS_OPT,
5990                 .name = "component-flags",      .has_arg = optional_argument },
5991         { .val = LFS_COMP_START_OPT,
5992                         .name = "comp-start",   .has_arg = optional_argument },
5993         { .val = LFS_COMP_START_OPT,
5994                 .name = "component-start",      .has_arg = optional_argument },
5995         { .val = 'c',   .name = "stripe-count", .has_arg = no_argument },
5996         { .val = 'c',   .name = "stripe_count", .has_arg = no_argument },
5997 /* find { .val = 'C',   .name = "ctime",        .has_arg = required_argument }*/
5998         { .val = 'd',   .name = "directory",    .has_arg = no_argument },
5999         { .val = 'D',   .name = "default",      .has_arg = no_argument },
6000         { .val = 'E',   .name = "comp-end",     .has_arg = optional_argument },
6001         { .val = 'E',   .name = "component-end", .has_arg = optional_argument },
6002         { .val = 'F',   .name = "fid",          .has_arg = no_argument },
6003         { .val = 'g',   .name = "generation",   .has_arg = no_argument },
6004 /* find { .val = 'G',   .name = "group",        .has_arg = required_argument }*/
6005         { .val = 'h',   .name = "help",         .has_arg = no_argument },
6006         { .val = LFS_HEX_IDX_OPT,
6007                         .name = "hex-idx",      .has_arg = no_argument },
6008 /* dirstripe { .val = 'H', .name = "mdt-hash",  .has_arg = required_argument }*/
6009         { .val = 'i',   .name = "stripe-index", .has_arg = no_argument },
6010         { .val = 'i',   .name = "stripe_index", .has_arg = no_argument },
6011         { .val = 'I',   .name = "comp-id",      .has_arg = optional_argument },
6012         { .val = 'I',   .name = "component-id", .has_arg = optional_argument },
6013 /* find { .val = 'l',   .name = "lazy",         .has_arg = no_argument }, */
6014         { .val = 'L',   .name = "layout",       .has_arg = no_argument },
6015         { .val = 'm',   .name = "mdt",          .has_arg = no_argument },
6016         { .val = 'm',   .name = "mdt-index",    .has_arg = no_argument },
6017         { .val = 'm',   .name = "mdt_index",    .has_arg = no_argument },
6018 /* find { .val = 'M',   .name = "mtime",        .has_arg = required_argument }*/
6019 /* find { .val = 'n',   .name = "name",         .has_arg = required_argument }*/
6020         { .val = 'N',   .name = "mirror-count", .has_arg = no_argument },
6021         { .val = LFS_MIRROR_INDEX_OPT,
6022                         .name = "mirror-index", .has_arg = required_argument },
6023         { .val = LFS_MIRROR_ID_OPT,
6024                         .name = "mirror-id",    .has_arg = required_argument },
6025         { .val = LFS_NO_FOLLOW_OPT,
6026                         .name = "no-follow",    .has_arg = no_argument },
6027         { .val = 'O',   .name = "obd",          .has_arg = required_argument },
6028         { .val = 'O',   .name = "ost",          .has_arg = required_argument },
6029         { .val = 'p',   .name = "pool",         .has_arg = no_argument },
6030 /* find { .val = 'P',   .name = "print",        .has_arg = no_argument }, */
6031         { .val = 'q',   .name = "quiet",        .has_arg = no_argument },
6032         { .val = 'r',   .name = "recursive",    .has_arg = no_argument },
6033         { .val = 'R',   .name = "raw",          .has_arg = no_argument },
6034         { .val = 'S',   .name = "stripe-size",  .has_arg = no_argument },
6035         { .val = 'S',   .name = "stripe_size",  .has_arg = no_argument },
6036 /* find { .val = 't',   .name = "type",         .has_arg = required_argument }*/
6037 /* dirstripe { .val = 'T', .name = "mdt-count", .has_arg = required_argument }*/
6038 /* find { .val = 'u',   .name = "uid",          .has_arg = required_argument }*/
6039 /* find { .val = 'U',   .name = "user",         .has_arg = required_argument }*/
6040         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
6041 /* dirstripe { .val = 'X',.name = "max-inherit",.has_arg = required_argument }*/
6042 /* setstripe { .val = 'W', .name = "bandwidth", .has_arg = required_argument }*/
6043         { .val = 'y',   .name = "yaml",         .has_arg = no_argument },
6044         { .val = 'z',   .name = "extension-size", .has_arg = no_argument },
6045         { .val = 'z',   .name = "ext-size",     .has_arg = no_argument },
6046         { .name = NULL } };
6047         int c, rc = 0;
6048         int neg_opt = 0;
6049         int pathstart = -1, pathend = -1;
6050         int isoption;
6051         char *end, *tmp;
6052
6053         while ((c = getopt_long(argc, argv,
6054                         "-cdDE::FghiI::LmMNoO:pqrRsSvyz",
6055                         long_opts, NULL)) != -1) {
6056                 if (neg_opt)
6057                         --neg_opt;
6058
6059                 /* '!' is part of option */
6060                 isoption = (c != 1) || (strcmp(optarg, "!") == 0);
6061                 if (!isoption && pathend != -1) {
6062                         fprintf(stderr,
6063                                 "error: %s: filename|dirname must either precede options or follow options\n",
6064                                 argv[0]);
6065                         return CMD_HELP;
6066                 }
6067                 if (!isoption && pathstart == -1)
6068                         pathstart = optind - 1;
6069                 if (isoption && pathstart != -1 && pathend == -1)
6070                         pathend = optind - 2;
6071
6072                 switch (c) {
6073                 case 1:
6074                         /* unknown: opt is "!" */
6075                         if (strcmp(optarg, "!") == 0)
6076                                 neg_opt = 2;
6077                         break;
6078                 case 'c':
6079                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6080                                 param->fp_verbose |= VERBOSE_COUNT;
6081                                 param->fp_max_depth = 0;
6082                         }
6083                         break;
6084                 case LFS_COMP_COUNT_OPT:
6085                         param->fp_verbose |= VERBOSE_COMP_COUNT;
6086                         param->fp_max_depth = 0;
6087                         break;
6088                 case LFS_COMP_FLAGS_OPT:
6089                         if (optarg) {
6090                                 rc = comp_str2flags(optarg,
6091                                                     &param->fp_comp_flags,
6092                                                     &param->fp_comp_neg_flags);
6093                                 if (rc != 0) {
6094                                         fprintf(stderr,
6095                                                 "error: %s bad component flags '%s'.\n",
6096                                                 argv[0], optarg);
6097                                         return CMD_HELP;
6098                                 }
6099                                 param->fp_check_comp_flags = 1;
6100                         } else {
6101                                 param->fp_verbose |= VERBOSE_COMP_FLAGS;
6102                                 param->fp_max_depth = 0;
6103                         }
6104                         break;
6105                 case LFS_COMP_START_OPT:
6106                         if (optarg) {
6107                                 tmp = optarg;
6108                                 if (tmp[0] == '+') {
6109                                         param->fp_comp_start_sign = -1;
6110                                         tmp++;
6111                                 } else if (tmp[0] == '-') {
6112                                         param->fp_comp_start_sign = 1;
6113                                         tmp++;
6114                                 }
6115                                 rc = llapi_parse_size(tmp,
6116                                                 &param->fp_comp_start,
6117                                                 &param->fp_comp_start_units, 0);
6118                                 if (rc != 0) {
6119                                         fprintf(stderr,
6120                                                 "error: %s bad component start '%s'.\n",
6121                                                 argv[0], tmp);
6122                                         return CMD_HELP;
6123                                 }
6124                                 param->fp_check_comp_start = 1;
6125                         } else {
6126                                 param->fp_verbose |= VERBOSE_COMP_START;
6127                                 param->fp_max_depth = 0;
6128                         }
6129                         break;
6130                 case LFS_MIRROR_INDEX_OPT: {
6131                         unsigned long int mirror_index;
6132
6133                         if (optarg[0] == '+') {
6134                                 param->fp_mirror_index_sign = -1;
6135                                 optarg++;
6136                         } else if (optarg[0] == '-') {
6137                                 param->fp_mirror_index_sign = 1;
6138                                 optarg++;
6139                         }
6140
6141                         errno = 0;
6142                         mirror_index = strtoul(optarg, &end, 0);
6143                         if (errno != 0 || *end != '\0' ||
6144                             mirror_index > UINT16_MAX || (mirror_index == 0 &&
6145                             param->fp_mirror_index_sign == 0 && neg_opt == 0)) {
6146                                 fprintf(stderr,
6147                                         "%s %s: invalid mirror index '%s'\n",
6148                                         progname, argv[0], optarg);
6149                                 return CMD_HELP;
6150                         }
6151
6152                         param->fp_mirror_index = (__u16)mirror_index;
6153
6154                         if (param->fp_mirror_id != 0) {
6155                                 fprintf(stderr,
6156                                         "%s %s: can't specify both mirror index and mirror ID\n",
6157                                         progname, argv[0]);
6158                                 return CMD_HELP;
6159                         }
6160                         param->fp_check_mirror_index = 1;
6161                         param->fp_exclude_mirror_index = !!neg_opt;
6162                         break;
6163                 }
6164                 case LFS_MIRROR_ID_OPT: {
6165                         unsigned long int mirror_id;
6166
6167                         if (optarg[0] == '+') {
6168                                 param->fp_mirror_id_sign = -1;
6169                                 optarg++;
6170                         } else if (optarg[0] == '-') {
6171                                 param->fp_mirror_id_sign = 1;
6172                                 optarg++;
6173                         }
6174
6175                         errno = 0;
6176                         mirror_id = strtoul(optarg, &end, 0);
6177                         if (errno != 0 || *end != '\0' ||
6178                             mirror_id > UINT16_MAX || (mirror_id == 0 &&
6179                             param->fp_mirror_id_sign == 0 && neg_opt == 0)) {
6180                                 fprintf(stderr,
6181                                         "%s %s: invalid mirror ID '%s'\n",
6182                                         progname, argv[0], optarg);
6183                                 return CMD_HELP;
6184                         }
6185
6186                         param->fp_mirror_id = (__u16)mirror_id;
6187
6188                         if (param->fp_mirror_index != 0) {
6189                                 fprintf(stderr,
6190                                         "%s %s: can't specify both mirror index and mirror ID\n",
6191                                         progname, argv[0]);
6192                                 return CMD_HELP;
6193                         }
6194                         param->fp_check_mirror_id = 1;
6195                         param->fp_exclude_mirror_id = !!neg_opt;
6196                         break;
6197                 }
6198                 case LFS_NO_FOLLOW_OPT:
6199                         param->fp_no_follow = true;
6200                         break;
6201                 case LFS_HEX_IDX_OPT:
6202                         param->fp_hex_idx = true;
6203                         break;
6204                 case 'd':
6205                         param->fp_max_depth = 0;
6206                         break;
6207                 case 'D':
6208                         param->fp_get_default_lmv = 1;
6209                         break;
6210                 case 'E':
6211                         if (optarg) {
6212                                 tmp = optarg;
6213                                 if (tmp[0] == '+') {
6214                                         param->fp_comp_end_sign = -1;
6215                                         tmp++;
6216                                 } else if (tmp[0] == '-') {
6217                                         param->fp_comp_end_sign = 1;
6218                                         tmp++;
6219                                 }
6220
6221                                 if (arg_is_eof(tmp)) {
6222                                         param->fp_comp_end = LUSTRE_EOF;
6223                                         param->fp_comp_end_units = 1;
6224                                         rc = 0;
6225                                 } else {
6226                                         rc = llapi_parse_size(tmp,
6227                                                 &param->fp_comp_end,
6228                                                 &param->fp_comp_end_units, 0);
6229                                         /* assume units of KB if too small */
6230                                         if (param->fp_comp_end < 4096)
6231                                                 param->fp_comp_end *= 1024;
6232                                 }
6233                                 if (rc != 0) {
6234                                         fprintf(stderr,
6235                                                 "error: %s bad component end '%s'.\n",
6236                                                 argv[0], tmp);
6237                                         return CMD_HELP;
6238                                 }
6239                                 param->fp_check_comp_end = 1;
6240                         } else {
6241                                 param->fp_verbose |= VERBOSE_COMP_END;
6242                                 param->fp_max_depth = 0;
6243                         }
6244                         break;
6245                 case 'F':
6246                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6247                                 param->fp_verbose |= VERBOSE_DFID;
6248                                 param->fp_max_depth = 0;
6249                         }
6250                         break;
6251                 case 'g':
6252                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6253                                 param->fp_verbose |= VERBOSE_GENERATION;
6254                                 param->fp_max_depth = 0;
6255                         }
6256                         break;
6257                 case 'i':
6258                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6259                                 param->fp_verbose |= VERBOSE_STRIPE_OFFSET;
6260                                 param->fp_max_depth = 0;
6261                         }
6262                         break;
6263                 case 'I':
6264                         if (optarg) {
6265                                 param->fp_comp_id = strtoul(optarg, &end, 0);
6266                                 if (*end != '\0' || param->fp_comp_id == 0 ||
6267                                     param->fp_comp_id > LCME_ID_MAX) {
6268                                         fprintf(stderr,
6269                                                 "error: %s bad component id '%s'\n",
6270                                                 argv[0], optarg);
6271                                         return CMD_HELP;
6272                                 }
6273                                 param->fp_check_comp_id = 1;
6274                         } else {
6275                                 param->fp_max_depth = 0;
6276                                 param->fp_verbose |= VERBOSE_COMP_ID;
6277                         }
6278                         break;
6279                 case 'L':
6280                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6281                                 param->fp_verbose |= VERBOSE_PATTERN;
6282                                 param->fp_max_depth = 0;
6283                         }
6284                         break;
6285 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
6286                 case 'M':
6287                         fprintf(stderr,
6288                                 "warning: '-M' deprecated, use '--mdt-index' or '-m' instead\n");
6289 #endif
6290                 case 'm':
6291                         if (!(param->fp_verbose & VERBOSE_DETAIL))
6292                                 param->fp_max_depth = 0;
6293                         param->fp_verbose |= VERBOSE_MDTINDEX;
6294                         break;
6295                 case 'N':
6296                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6297                                 param->fp_verbose |= VERBOSE_MIRROR_COUNT;
6298                                 param->fp_max_depth = 0;
6299                         }
6300                         break;
6301                 case 'O':
6302                         if (param->fp_obd_uuid) {
6303                                 fprintf(stderr,
6304                                         "error: %s: only one obduuid allowed",
6305                                         argv[0]);
6306                                 return CMD_HELP;
6307                         }
6308                         param->fp_obd_uuid = (struct obd_uuid *)optarg;
6309                         break;
6310                 case 'p':
6311                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6312                                 param->fp_verbose |= VERBOSE_POOL;
6313                                 param->fp_max_depth = 0;
6314                         }
6315                         break;
6316                 case 'q':
6317                         param->fp_quiet++;
6318                         break;
6319                 case 'r':
6320                         param->fp_recursive = 1;
6321                         break;
6322                 case 'R':
6323                         param->fp_raw = 1;
6324                         break;
6325                 case 'S':
6326                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6327                                 param->fp_verbose |= VERBOSE_STRIPE_SIZE;
6328                                 param->fp_max_depth = 0;
6329                         }
6330                         break;
6331                 case 'v':
6332                         param->fp_verbose = VERBOSE_DEFAULT | VERBOSE_DETAIL;
6333                         break;
6334                 case 'y':
6335                         param->fp_yaml = 1;
6336                         break;
6337                 case 'z':
6338                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6339                                 param->fp_verbose |= VERBOSE_EXT_SIZE;
6340                                 param->fp_max_depth = 0;
6341                         }
6342                         break;
6343                 default:
6344                         fprintf(stderr, "%s: unrecognized option '%s'\n",
6345                                 progname, argv[optind - 1]);
6346                 case 'h':
6347                         return CMD_HELP;
6348                 }
6349         }
6350
6351         if (pathstart == -1) {
6352                 fprintf(stderr, "error: %s: no filename|pathname\n",
6353                                 argv[0]);
6354                 return CMD_HELP;
6355         } else if (pathend == -1) {
6356                 /* no options */
6357                 pathend = argc;
6358         }
6359
6360         if (pathend > argc)
6361                 return CMD_HELP;
6362
6363         if (param->fp_recursive)
6364                 param->fp_max_depth = -1;
6365         else if (param->fp_verbose & VERBOSE_DETAIL)
6366                 param->fp_max_depth = 1;
6367
6368         if (!param->fp_verbose)
6369                 param->fp_verbose = VERBOSE_DEFAULT;
6370         if (param->fp_quiet)
6371                 param->fp_verbose = VERBOSE_OBJID;
6372
6373         do {
6374                 int rc2;
6375
6376                 rc2 = llapi_getstripe(argv[pathstart], param);
6377                 if (rc2) {
6378                         fprintf(stderr, "%s: %s for '%s' failed: %s\n",
6379                                 progname, argv[0], argv[optind - 1],
6380                                 strerror(-rc2));
6381                         if (!rc)
6382                                 rc = rc2;
6383                 }
6384         } while (++pathstart < pathend);
6385
6386         return rc;
6387 }
6388
6389 static int lfs_tgts(int argc, char **argv)
6390 {
6391         char mntdir[PATH_MAX] = {'\0'}, path[PATH_MAX] = {'\0'};
6392         struct find_param param;
6393         int index = 0, rc = 0;
6394
6395         if (argc > 2)
6396                 return CMD_HELP;
6397
6398         if (argc == 2 && !realpath(argv[1], path)) {
6399                 rc = -errno;
6400                 fprintf(stderr, "error: invalid path '%s': %s\n",
6401                         argv[1], strerror(-rc));
6402                 return rc;
6403         }
6404
6405         while (!llapi_search_mounts(path, index++, mntdir, NULL)) {
6406                 /* Check if we have a mount point */
6407                 if (mntdir[0] == '\0')
6408                         continue;
6409
6410                 memset(&param, 0, sizeof(param));
6411                 if (!strcmp(argv[0], "mdts"))
6412                         param.fp_get_lmv = 1;
6413
6414                 rc = llapi_ostlist(mntdir, &param);
6415                 if (rc) {
6416                         fprintf(stderr, "error: %s: failed on %s\n",
6417                                 argv[0], mntdir);
6418                 }
6419                 if (path[0] != '\0')
6420                         break;
6421                 memset(mntdir, 0, PATH_MAX);
6422         }
6423
6424         return rc;
6425 }
6426
6427 static int lfs_getstripe(int argc, char **argv)
6428 {
6429         struct find_param param = { 0 };
6430
6431         param.fp_max_depth = 1;
6432         return lfs_getstripe_internal(argc, argv, &param);
6433 }
6434
6435 /* functions */
6436 static int lfs_getdirstripe(int argc, char **argv)
6437 {
6438         struct find_param param = { 0 };
6439         struct option long_opts[] = {
6440         { .val = 'c',   .name = "mdt-count",     .has_arg = no_argument },
6441         { .val = 'D',   .name = "default",       .has_arg = no_argument },
6442         { .val = 'h',   .name = "help",         .has_arg = no_argument },
6443         { .val = 'H',   .name = "mdt-hash",      .has_arg = no_argument },
6444         { .val = LFS_HEX_IDX_OPT,
6445                         .name = "hex-idx",       .has_arg = no_argument },
6446         { .val = 'i',   .name = "mdt-index",     .has_arg = no_argument },
6447         { .val = 'm',   .name = "mdt-index",     .has_arg = no_argument },
6448         { .val = 'O',   .name = "obd",           .has_arg = required_argument },
6449         { .val = 'r',   .name = "recursive",     .has_arg = no_argument },
6450         { .val = 'R',   .name = "raw",          .has_arg = no_argument },
6451         { .val = 'T',   .name = "mdt-count",     .has_arg = no_argument },
6452         { .val = 'v',   .name = "verbose",       .has_arg = no_argument },
6453         { .val = 'X',   .name = "max-inherit",   .has_arg = no_argument },
6454         { .val = LFS_INHERIT_RR_OPT,
6455                         .name = "max-inherit-rr", .has_arg = no_argument },
6456         { .val = 'y',   .name = "yaml",          .has_arg = no_argument },
6457         { .name = NULL } };
6458         int c, rc = 0;
6459
6460         param.fp_get_lmv = 1;
6461
6462         while ((c = getopt_long(argc, argv,
6463                                 "cDhHimO:rRtTvXy", long_opts, NULL)) != -1) {
6464                 switch (c) {
6465                 case 'c':
6466                 case 'T':
6467                         param.fp_verbose |= VERBOSE_COUNT;
6468                         break;
6469                 case 'D':
6470                         param.fp_get_default_lmv = 1;
6471                         break;
6472 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
6473                 case 't':
6474                         fprintf(stderr,
6475                                 "warning: '-t' deprecated, use '--mdt-hash' or '-H' instead\n");
6476                         fallthrough;
6477 #endif
6478                 case 'H':
6479                         param.fp_verbose |= VERBOSE_HASH_TYPE;
6480                         break;
6481                 case LFS_HEX_IDX_OPT:
6482                         param.fp_hex_idx = 1;
6483                         break;
6484                 case 'i':
6485                         fallthrough;
6486                 case 'm':
6487                         param.fp_verbose |= VERBOSE_STRIPE_OFFSET;
6488                         break;
6489                 case 'O':
6490                         if (param.fp_obd_uuid) {
6491                                 fprintf(stderr,
6492                                         "%s: only one obduuid allowed",
6493                                         progname);
6494                                 return CMD_HELP;
6495                         }
6496                         param.fp_obd_uuid = (struct obd_uuid *)optarg;
6497                         break;
6498                 case 'r':
6499                         param.fp_recursive = 1;
6500                         break;
6501                 case 'R':
6502                         param.fp_raw = 1;
6503                         break;
6504                 case 'v':
6505                         param.fp_verbose |= VERBOSE_DEFAULT;
6506                         param.fp_verbose |= VERBOSE_DETAIL;
6507                         break;
6508                 case 'X':
6509                         param.fp_verbose |= VERBOSE_INHERIT;
6510                         break;
6511                 case LFS_INHERIT_RR_OPT:
6512                         param.fp_verbose |= VERBOSE_INHERIT_RR;
6513                         break;
6514                 case 'y':
6515                         param.fp_yaml = 1;
6516                         break;
6517                 default:
6518                         fprintf(stderr, "%s: unrecognized option '%s'\n",
6519                                 progname, argv[optind - 1]);
6520                         fallthrough;
6521                 case 'h':
6522                         return CMD_HELP;
6523                 }
6524         }
6525
6526         if (optind >= argc)
6527                 return CMD_HELP;
6528
6529         if (param.fp_recursive)
6530                 param.fp_max_depth = -1;
6531
6532         if (!param.fp_verbose)
6533                 param.fp_verbose = VERBOSE_DEFAULT;
6534
6535         do {
6536                 int rc2;
6537
6538                 rc2 = llapi_getstripe(argv[optind], &param);
6539                 if (rc2) {
6540                         fprintf(stderr, "%s: %s for '%s' failed: %s\n",
6541                                 progname, argv[0], argv[optind],
6542                                 strerror(-rc2));
6543                         if (!rc)
6544                                 rc = rc2;
6545                 }
6546         } while (++optind < argc);
6547
6548         return rc;
6549 }
6550
6551 enum mntdf_flags {
6552         MNTDF_INODES    = 0x0001,
6553         MNTDF_COOKED    = 0x0002,
6554         MNTDF_LAZY      = 0x0004,
6555         MNTDF_VERBOSE   = 0x0008,
6556         MNTDF_SHOW      = 0x0010,
6557         MNTDF_DECIMAL   = 0x0020,
6558 };
6559
6560 #define COOK(value, base)                                       \
6561 ({                                                              \
6562         int radix = 0;                                          \
6563         while (value > base) {                                  \
6564                 value /= base;                                  \
6565                 radix++;                                        \
6566         }                                                       \
6567         radix;                                                  \
6568 })
6569 #define UUF     "%-20s"
6570 #define CSF     "%11s"
6571 #define CDF     "%11llu"
6572 #define HDF     "%8.1f%c"
6573 #define RSF     "%4s"
6574 #define RDF     "%3d%%"
6575
6576 static inline int obd_statfs_ratio(const struct obd_statfs *st, bool inodes)
6577 {
6578         double avail, used, ratio = 0;
6579
6580         if (inodes) {
6581                 avail = st->os_ffree;
6582                 used = st->os_files - st->os_ffree;
6583         } else {
6584                 avail = st->os_bavail;
6585                 used = st->os_blocks - st->os_bfree;
6586         }
6587         if (avail + used > 0)
6588                 ratio = used / (used + avail) * 100;
6589
6590         /* Round up to match df(1) usage percentage */
6591         return (ratio - (int)ratio) > 0 ? (int)(ratio + 1) : (int)ratio;
6592 }
6593
6594 /*
6595  * This is to identify various problem states for "lfs df" if .osn_err = true,
6596  * so only show flags reflecting those states by default. Informational states
6597  * are only shown with "-v" and use lower-case names to distinguish them.
6598  * UNUSED[12] were for "EROFS = 30" until 1.6 but are now available for use.
6599  */
6600 static struct obd_statfs_state_names {
6601         enum obd_statfs_state   osn_state;
6602         const char              osn_name;
6603         bool                    osn_err;
6604 } oss_names[] = {
6605         { .osn_state = OS_STATFS_DEGRADED,   .osn_name = 'D', .osn_err = true },
6606         { .osn_state = OS_STATFS_READONLY,   .osn_name = 'R', .osn_err = true },
6607         { .osn_state = OS_STATFS_NOPRECREATE,.osn_name = 'N', .osn_err = true },
6608         { .osn_state = OS_STATFS_UNUSED1,    .osn_name = '?', .osn_err = true },
6609         { .osn_state = OS_STATFS_UNUSED2,    .osn_name = '?', .osn_err = true },
6610         { .osn_state = OS_STATFS_ENOSPC,     .osn_name = 'S', .osn_err = true },
6611         { .osn_state = OS_STATFS_ENOINO,     .osn_name = 'I', .osn_err = true },
6612         { .osn_state = OS_STATFS_SUM,        .osn_name = 'a', /* aggregate */ },
6613         { .osn_state = OS_STATFS_NONROT,     .osn_name = 'f', /* flash */     },
6614 };
6615
6616 static int showdf(char *mntdir, struct obd_statfs *stat,
6617                   char *uuid, enum mntdf_flags flags,
6618                   char *type, int index, int rc)
6619 {
6620         long long avail, used, total;
6621         int ratio = 0;
6622         char *suffix = flags & MNTDF_DECIMAL ? "kMGTPEZY" : "KMGTPEZY";
6623         /* Note if we have >2^64 bytes/fs these buffers will need to be grown */
6624         char tbuf[3 * sizeof(__u64)];
6625         char ubuf[3 * sizeof(__u64)];
6626         char abuf[3 * sizeof(__u64)];
6627         char rbuf[3 * sizeof(__u64)];
6628
6629         if (!uuid || !stat)
6630                 return -EINVAL;
6631
6632         switch (rc) {
6633         case 0:
6634                 if (flags & MNTDF_INODES) {
6635                         avail = stat->os_ffree;
6636                         used = stat->os_files - stat->os_ffree;
6637                         total = stat->os_files;
6638                 } else {
6639                         int shift = flags & MNTDF_COOKED ? 0 : 10;
6640
6641                         avail = (stat->os_bavail * stat->os_bsize) >> shift;
6642                         used  = ((stat->os_blocks - stat->os_bfree) *
6643                                  stat->os_bsize) >> shift;
6644                         total = (stat->os_blocks * stat->os_bsize) >> shift;
6645                 }
6646
6647                 ratio = obd_statfs_ratio(stat, flags & MNTDF_INODES);
6648
6649                 if (flags & MNTDF_COOKED) {
6650                         int base = flags & MNTDF_DECIMAL ? 1000 : 1024;
6651                         double cook_val;
6652                         int i;
6653
6654                         cook_val = (double)total;
6655                         i = COOK(cook_val, base);
6656                         if (i > 0)
6657                                 snprintf(tbuf, sizeof(tbuf), HDF, cook_val,
6658                                          suffix[i - 1]);
6659                         else
6660                                 snprintf(tbuf, sizeof(tbuf), CDF, total);
6661
6662                         cook_val = (double)used;
6663                         i = COOK(cook_val, base);
6664                         if (i > 0)
6665                                 snprintf(ubuf, sizeof(ubuf), HDF, cook_val,
6666                                          suffix[i - 1]);
6667                         else
6668                                 snprintf(ubuf, sizeof(ubuf), CDF, used);
6669
6670                         cook_val = (double)avail;
6671                         i = COOK(cook_val, base);
6672                         if (i > 0)
6673                                 snprintf(abuf, sizeof(abuf), HDF, cook_val,
6674                                          suffix[i - 1]);
6675                         else
6676                                 snprintf(abuf, sizeof(abuf), CDF, avail);
6677                 } else {
6678                         snprintf(tbuf, sizeof(tbuf), CDF, total);
6679                         snprintf(ubuf, sizeof(tbuf), CDF, used);
6680                         snprintf(abuf, sizeof(tbuf), CDF, avail);
6681                 }
6682
6683                 sprintf(rbuf, RDF, ratio);
6684                 printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s",
6685                        uuid, tbuf, ubuf, abuf, rbuf, mntdir);
6686                 if (type)
6687                         printf("[%s:%d]", type, index);
6688
6689                 if (stat->os_state) {
6690                         uint32_t i;
6691
6692                         printf(" ");
6693                         for (i = 0; i < ARRAY_SIZE(oss_names); i++) {
6694                                 if (oss_names[i].osn_state & stat->os_state &&
6695                                     (oss_names[i].osn_err ||
6696                                      flags & MNTDF_VERBOSE))
6697                                         printf("%c", oss_names[i].osn_name);
6698                         }
6699                 }
6700
6701                 printf("\n");
6702                 break;
6703         case -ENODATA:
6704                 printf(UUF": inactive device\n", uuid);
6705                 break;
6706         default:
6707                 printf(UUF": %s\n", uuid, strerror(-rc));
6708                 break;
6709         }
6710
6711         return 0;
6712 }
6713
6714 struct ll_stat_type {
6715         int   st_op;
6716         char *st_name;
6717 };
6718
6719 #define LL_STATFS_MAX   LOV_MAX_STRIPE_COUNT
6720
6721 struct ll_statfs_data {
6722         int                     sd_index;
6723         struct obd_statfs       sd_st;
6724 };
6725
6726 struct ll_statfs_buf {
6727         int                     sb_count;
6728         struct ll_statfs_data   sb_buf[LL_STATFS_MAX];
6729 };
6730
6731 static int mntdf(char *mntdir, char *fsname, char *pool, enum mntdf_flags flags,
6732                  int ops, struct ll_statfs_buf *lsb)
6733 {
6734         struct obd_statfs stat_buf, sum = { .os_bsize = 1 };
6735         struct obd_uuid uuid_buf;
6736         char *poolname = NULL;
6737         struct ll_stat_type types[] = {
6738                 { .st_op = LL_STATFS_LMV,       .st_name = "MDT" },
6739                 { .st_op = LL_STATFS_LOV,       .st_name = "OST" },
6740                 { .st_name = NULL } };
6741         struct ll_stat_type *tp;
6742         __u64 ost_files = 0;
6743         __u64 ost_ffree = 0;
6744         __u32 index;
6745         __u32 type;
6746         int fd;
6747         int rc = 0;
6748         int rc2;
6749
6750         if (pool) {
6751                 poolname = strchr(pool, '.');
6752                 if (poolname) {
6753                         if (strncmp(fsname, pool, strlen(fsname))) {
6754                                 fprintf(stderr, "filesystem name incorrect\n");
6755                                 return -ENODEV;
6756                         }
6757                         poolname++;
6758                 } else
6759                         poolname = pool;
6760         }
6761
6762         fd = open(mntdir, O_RDONLY);
6763         if (fd < 0) {
6764                 rc = -errno;
6765                 fprintf(stderr, "%s: cannot open '%s': %s\n", progname, mntdir,
6766                         strerror(errno));
6767                 return rc;
6768         }
6769
6770         if (flags & MNTDF_SHOW) {
6771                 if (flags & MNTDF_INODES)
6772                         printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s\n",
6773                                "UUID", "Inodes", "IUsed", "IFree",
6774                                "IUse%", "Mounted on");
6775                 else
6776                         printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s\n",
6777                                "UUID",
6778                                flags & MNTDF_COOKED ? "bytes" : "1K-blocks",
6779                                "Used", "Available", "Use%", "Mounted on");
6780         }
6781
6782         for (tp = types; tp->st_name != NULL; tp++) {
6783                 bool have_ost = false;
6784
6785                 if (!(tp->st_op & ops))
6786                         continue;
6787
6788                 for (index = 0; index < LOV_ALL_STRIPES &&
6789                      (!lsb || lsb->sb_count < LL_STATFS_MAX); index++) {
6790                         memset(&stat_buf, 0, sizeof(struct obd_statfs));
6791                         memset(&uuid_buf, 0, sizeof(struct obd_uuid));
6792                         type = flags & MNTDF_LAZY ?
6793                                 tp->st_op | LL_STATFS_NODELAY : tp->st_op;
6794                         rc2 = llapi_obd_fstatfs(fd, type, index,
6795                                                 &stat_buf, &uuid_buf);
6796                         if (rc2 == -ENODEV)
6797                                 break;
6798                         if (rc2 == -EAGAIN)
6799                                 continue;
6800                         if (rc2 == -ENODATA) { /* Inactive device, OK. */
6801                                 if (!(flags & MNTDF_VERBOSE))
6802                                         continue;
6803                         } else if (rc2 < 0 && rc == 0) {
6804                                 rc = rc2;
6805                         }
6806
6807                         /*
6808                          * If we have OSTs then don't report MDT block counts.
6809                          * For MDT-only filesystems the expectation is that all
6810                          * layouts have a DoM component.  For filesystems with
6811                          * OSTs, files are not necessarily going to store data
6812                          * on MDTs, and MDT space is limited to a fraction of
6813                          * OST space, so don't include it in the summary.
6814                          */
6815                         if (tp->st_op == LL_STATFS_LOV && !have_ost) {
6816                                 have_ost = true;
6817                                 sum.os_blocks = 0;
6818                                 sum.os_bfree = 0;
6819                                 sum.os_bavail = 0;
6820                         }
6821
6822                         if (poolname && tp->st_op == LL_STATFS_LOV &&
6823                             llapi_search_ost(fsname, poolname,
6824                                              obd_uuid2str(&uuid_buf)) != 1)
6825                                 continue;
6826
6827                         /*
6828                          * the llapi_obd_fstatfs() call may have returned with
6829                          * an error, but if it filled in uuid_buf we will at
6830                          * lease use that to print out a message for that OBD.
6831                          * If we didn't get anything in the uuid_buf, then fill
6832                          * it in so that we can print an error message.
6833                          */
6834                         if (uuid_buf.uuid[0] == '\0')
6835                                 snprintf(uuid_buf.uuid, sizeof(uuid_buf.uuid),
6836                                          "%s%04x", tp->st_name, index);
6837                         if (!rc && lsb) {
6838                                 lsb->sb_buf[lsb->sb_count].sd_index = index;
6839                                 lsb->sb_buf[lsb->sb_count].sd_st = stat_buf;
6840                                 lsb->sb_count++;
6841                         }
6842                         if (flags & MNTDF_SHOW)
6843                                 showdf(mntdir, &stat_buf,
6844                                        obd_uuid2str(&uuid_buf), flags,
6845                                        tp->st_name, index, rc2);
6846
6847                         if (rc2)
6848                                 continue;
6849
6850                         if (tp->st_op == LL_STATFS_LMV) {
6851                                 sum.os_ffree += stat_buf.os_ffree;
6852                                 sum.os_files += stat_buf.os_files;
6853                         } else /* if (tp->st_op == LL_STATFS_LOV) */ {
6854                                 ost_files += stat_buf.os_files;
6855                                 ost_ffree += stat_buf.os_ffree;
6856                         }
6857                         sum.os_blocks += stat_buf.os_blocks *
6858                                          stat_buf.os_bsize;
6859                         sum.os_bfree  += stat_buf.os_bfree *
6860                                          stat_buf.os_bsize;
6861                         sum.os_bavail += stat_buf.os_bavail *
6862                                          stat_buf.os_bsize;
6863                 }
6864         }
6865
6866         close(fd);
6867
6868         /*
6869          * If we have _some_ OSTs, but don't have as many free objects on the
6870          * OST as inodes on the MDTs, reduce the reported number of inodes
6871          * to compensate, so that the "inodes in use" number is correct.
6872          * This should be kept in sync with ll_statfs_internal().
6873          */
6874         if (ost_files && ost_ffree < sum.os_ffree) {
6875                 sum.os_files = (sum.os_files - sum.os_ffree) + ost_ffree;
6876                 sum.os_ffree = ost_ffree;
6877         }
6878         if (flags & MNTDF_SHOW) {
6879                 printf("\n");
6880                 showdf(mntdir, &sum, "filesystem_summary:", flags, NULL, 0, 0);
6881                 printf("\n");
6882         }
6883
6884         return rc;
6885 }
6886
6887 enum {
6888         LAYOUT_INHERIT_UNSET    = -2,
6889 };
6890
6891 /* functions */
6892 static int lfs_setdirstripe(int argc, char **argv)
6893 {
6894         char *dname;
6895         struct lfs_setstripe_args lsa = { 0 };
6896         struct llapi_stripe_param *param = NULL;
6897         __u32 mdts[LMV_MAX_STRIPE_COUNT] = { 0 };
6898         char *end;
6899         int c;
6900         char *mode_opt = NULL;
6901         bool default_stripe = false;
6902         bool delete = false;
6903         bool foreign_mode = false;
6904         bool mdt_count_set = false;
6905         mode_t mode = S_IRWXU | S_IRWXG | S_IRWXO;
6906         mode_t previous_mode = 0;
6907         char *xattr = NULL;
6908         __u32 type = LU_FOREIGN_TYPE_SYMLINK, flags = 0;
6909         int max_inherit = LAYOUT_INHERIT_UNSET;
6910         int max_inherit_rr = LAYOUT_INHERIT_UNSET;
6911         struct option long_opts[] = {
6912         { .val = 'c',   .name = "count",        .has_arg = required_argument },
6913         { .val = 'c',   .name = "mdt-count",    .has_arg = required_argument },
6914         { .val = 'd',   .name = "delete",       .has_arg = no_argument },
6915         { .val = 'D',   .name = "default",      .has_arg = no_argument },
6916         { .val = 'D',   .name = "default_stripe", .has_arg = no_argument },
6917         { .val = LFS_LAYOUT_FLAGS_OPT,
6918                         .name = "flags",        .has_arg = required_argument },
6919         { .val = LFS_LAYOUT_FOREIGN_OPT,
6920                         .name = "foreign",      .has_arg = optional_argument},
6921         { .val = 'h',   .name = "help",         .has_arg = no_argument },
6922         { .val = 'H',   .name = "mdt-hash",     .has_arg = required_argument },
6923 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 17, 53, 0)
6924         { .val = 'i',   .name = "mdt-index",    .has_arg = required_argument },
6925         { .val = 'i',   .name = "mdt",          .has_arg = required_argument },
6926 #else
6927 /* find { .val = 'l',   .name = "lazy",         .has_arg = no_argument }, */
6928         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument },
6929         { .val = 'm',   .name = "mdt",          .has_arg = required_argument },
6930 #endif
6931 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
6932         { .val = 'i',   .name = "index",        .has_arg = required_argument },
6933 #endif
6934         { .val = 'o',   .name = "mode",         .has_arg = required_argument },
6935 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
6936         { .val = 't',   .name = "hash-type",    .has_arg = required_argument },
6937 #endif
6938         { .val = 'T',   .name = "mdt-count",    .has_arg = required_argument },
6939         { .val = 'x',   .name = "xattr",        .has_arg = required_argument },
6940         { .val = 'X',   .name = "max-inherit",  .has_arg = required_argument },
6941         { .val = LFS_INHERIT_RR_OPT,
6942                         .name = "max-inherit-rr", .has_arg = required_argument},
6943 /* setstripe { .val = 'y', .name = "yaml",      .has_arg = no_argument }, */
6944 /* setstripe { .val = 'W', .name = "bandwidth", .has_arg = required_argument }, */
6945         { .name = NULL } };
6946         int result = 0;
6947
6948         setstripe_args_init(&lsa);
6949
6950         while ((c = getopt_long(argc, argv, "c:dDi:hH:m:o:t:T:x:X:",
6951                                 long_opts, NULL)) >= 0) {
6952                 switch (c) {
6953                 case 0:
6954                         /* Long options. */
6955                         break;
6956                 case 'c':
6957                 case 'T':
6958                         errno = 0;
6959                         lsa.lsa_stripe_count = strtoul(optarg, &end, 0);
6960                         if (errno != 0 || *end != '\0' ||
6961                             lsa.lsa_stripe_count < -1 ||
6962                             lsa.lsa_stripe_count > LOV_MAX_STRIPE_COUNT) {
6963                                 fprintf(stderr,
6964                                         "%s: invalid stripe count '%s'\n",
6965                                         progname, optarg);
6966                                 return CMD_HELP;
6967                         }
6968                         mdt_count_set = true;
6969                         break;
6970                 case 'd':
6971                         delete = true;
6972                         default_stripe = true;
6973                         break;
6974                 case 'D':
6975                         default_stripe = true;
6976                         break;
6977                 case LFS_LAYOUT_FOREIGN_OPT:
6978                         if (optarg) {
6979                                 /* check pure numeric */
6980                                 type = strtoul(optarg, &end, 0);
6981                                 if (*end) {
6982                                         /* check name */
6983                                         type = check_foreign_type_name(optarg);
6984                                         if (type == LU_FOREIGN_TYPE_UNKNOWN) {
6985                                                 fprintf(stderr,
6986                                                         "%s %s: unknown foreign type '%s'\n",
6987                                                         progname, argv[0],
6988                                                         optarg);
6989                                                 return CMD_HELP;
6990                                         }
6991                                 } else if (type >= UINT32_MAX) {
6992                                         fprintf(stderr,
6993                                                 "%s %s: invalid foreign type '%s'\n",
6994                                                 progname, argv[0], optarg);
6995                                         return CMD_HELP;
6996                                 }
6997                         }
6998                         foreign_mode = true;
6999                         break;
7000                 case LFS_LAYOUT_FLAGS_OPT:
7001                         errno = 0;
7002                         flags = strtoul(optarg, &end, 16);
7003                         if (errno != 0 || *end != '\0' ||
7004                             flags >= UINT32_MAX) {
7005                                 fprintf(stderr,
7006                                         "%s %s: invalid hex flags '%s'\n",
7007                                         progname, argv[0], optarg);
7008                                 return CMD_HELP;
7009                         }
7010                         if (!foreign_mode) {
7011                                 fprintf(stderr,
7012                                         "%s %s: hex flags must be specified with --foreign option\n",
7013                                         progname, argv[0]);
7014                                 return CMD_HELP;
7015                         }
7016                         break;
7017 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
7018                 case 't':
7019                         fprintf(stderr,
7020                                 "warning: '--hash-type' and '-t' deprecated, use '--mdt-hash' or '-H' instead\n");
7021                         fallthrough;
7022 #endif
7023                 case 'H':
7024                         lsa.lsa_pattern = check_hashtype(optarg);
7025                         if (lsa.lsa_pattern == 0) {
7026                                 fprintf(stderr,
7027                                         "%s %s: bad directory hash type '%s'\n",
7028                                         progname, argv[0], optarg);
7029                                 return CMD_HELP;
7030                         }
7031                         break;
7032                 case 'i':
7033 #if LUSTRE_VERSION_CODE >= OBD_OCD_VERSION(2, 17, 53, 0)
7034                 case 'm':
7035 #endif
7036 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
7037                         if (strcmp(argv[optind - 1], "--index") == 0)
7038                                 fprintf(stderr,
7039                                         "%s %s: warning: '--index' deprecated, use '--mdt-index' instead\n",
7040                                         progname, argv[0]);
7041 #endif
7042                         lsa.lsa_nr_tgts = parse_targets(mdts,
7043                                                 sizeof(mdts) / sizeof(__u32),
7044                                                 lsa.lsa_nr_tgts, optarg, NULL);
7045                         if (lsa.lsa_nr_tgts < 0) {
7046                                 fprintf(stderr,
7047                                         "%s %s: invalid MDT target(s) '%s'\n",
7048                                         progname, argv[0], optarg);
7049                                 return CMD_HELP;
7050                         }
7051
7052                         lsa.lsa_tgts = mdts;
7053                         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
7054                                 lsa.lsa_stripe_off = mdts[0];
7055                         break;
7056                 case 'o':
7057                         mode_opt = optarg;
7058                         break;
7059                 case 'x':
7060                         xattr = optarg;
7061                         break;
7062                 case 'X':
7063                         errno = 0;
7064                         max_inherit = strtol(optarg, &end, 10);
7065                         if (errno != 0 || *end != '\0' || max_inherit < -2) {
7066                                 fprintf(stderr,
7067                                         "%s %s: invalid max-inherit '%s'\n",
7068                                         progname, argv[0], optarg);
7069                                 return CMD_HELP;
7070                         }
7071                         if (max_inherit == 0) {
7072                                 max_inherit = LMV_INHERIT_NONE;
7073                         } else if (max_inherit == -1) {
7074                                 max_inherit = LMV_INHERIT_UNLIMITED;
7075                         } else if (max_inherit > LMV_INHERIT_MAX) {
7076                                 fprintf(stderr,
7077                                         "%s %s: max-inherit %d exceeds maximum %u\n",
7078                                         progname, argv[0], max_inherit,
7079                                         LMV_INHERIT_MAX);
7080                                 return CMD_HELP;
7081                         }
7082                         break;
7083                 case LFS_INHERIT_RR_OPT:
7084                         if (!default_stripe) {
7085                                 fprintf(stderr,
7086                                         "%s %s: '--max-inherit-rr' must be specified with '-D'\n",
7087                                         progname, argv[0]);
7088                                 return CMD_HELP;
7089                         }
7090                         errno = 0;
7091                         max_inherit_rr = strtol(optarg, &end, 10);
7092                         if (errno != 0 || *end != '\0' || max_inherit_rr < -2) {
7093                                 fprintf(stderr,
7094                                         "%s %s: invalid max-inherit-rr '%s'\n",
7095                                         progname, argv[0], optarg);
7096                                 return CMD_HELP;
7097                         }
7098                         if (max_inherit_rr == 0) {
7099                                 max_inherit_rr = LMV_INHERIT_RR_NONE;
7100                         } else if (max_inherit_rr == -1) {
7101                                 max_inherit_rr = LMV_INHERIT_RR_UNLIMITED;
7102                         } else if (max_inherit_rr > LMV_INHERIT_RR_MAX) {
7103                                 fprintf(stderr,
7104                                         "%s %s: max-inherit-rr %d exceeds maximum %u\n",
7105                                         progname, argv[0], max_inherit_rr,
7106                                         LMV_INHERIT_RR_MAX);
7107                                 return CMD_HELP;
7108                         }
7109                         break;
7110                 default:
7111                         fprintf(stderr, "%s: unrecognized option '%s'\n",
7112                                 progname, argv[optind - 1]);
7113                         fallthrough;
7114                 case 'h':
7115                         return CMD_HELP;
7116                 }
7117         }
7118
7119         if (optind == argc) {
7120                 fprintf(stderr, "%s %s: DIR must be specified\n",
7121                         progname, argv[0]);
7122                 return CMD_HELP;
7123         }
7124
7125         if (xattr && !foreign_mode) {
7126                 /*
7127                  * only print a warning as this is armless and will be
7128                  * ignored
7129                  */
7130                 fprintf(stderr,
7131                         "%s %s: xattr has been specified for non-foreign layout\n",
7132                         progname, argv[0]);
7133         } else if (foreign_mode && !xattr) {
7134                 fprintf(stderr,
7135                         "%s %s: xattr must be provided in foreign mode\n",
7136                         progname, argv[0]);
7137                 return CMD_HELP;
7138         }
7139
7140         if (foreign_mode && (delete || default_stripe || lsa.lsa_nr_tgts ||
7141             lsa.lsa_tgts || setstripe_args_specified(&lsa))) {
7142                 fprintf(stderr,
7143                         "%s %s: only --xattr/--flags/--mode options are valid with --foreign\n",
7144                         progname, argv[0]);
7145                 return CMD_HELP;
7146         }
7147
7148         if (!delete && lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT &&
7149             lsa.lsa_stripe_count == LLAPI_LAYOUT_DEFAULT && !foreign_mode) {
7150                 /* if no parameters set, create directory on least-used MDTs */
7151                 lsa.lsa_stripe_off = LMV_OFFSET_DEFAULT;
7152                 lsa.lsa_stripe_count = 1;
7153         }
7154
7155         if (delete &&
7156             (lsa.lsa_stripe_off != LLAPI_LAYOUT_DEFAULT ||
7157              lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT)) {
7158                 fprintf(stderr,
7159                         "%s %s: cannot specify -d with -c or -i options\n",
7160                         progname, argv[0]);
7161                 return CMD_HELP;
7162         }
7163
7164         if (mode_opt) {
7165                 mode = strtoul(mode_opt, &end, 8);
7166                 if (*end != '\0') {
7167                         fprintf(stderr,
7168                                 "%s %s: bad MODE '%s'\n",
7169                                 progname, argv[0], mode_opt);
7170                         return CMD_HELP;
7171                 }
7172                 previous_mode = umask(0);
7173         }
7174
7175         /* check max-inherit and warn user in some cases */
7176         if (default_stripe &&
7177             (lsa.lsa_stripe_count < 0 || lsa.lsa_stripe_count > 1)) {
7178                 if (max_inherit == LMV_INHERIT_UNLIMITED)
7179                         fprintf(stderr,
7180                         "%s %s: unrecommended max-inherit=-1 when default stripe-count=%lld\n",
7181                         progname, argv[0], lsa.lsa_stripe_count);
7182                 else if (max_inherit > LMV_INHERIT_DEFAULT_STRIPED + 2 &&
7183                          max_inherit != LMV_INHERIT_NONE)
7184                         fprintf(stderr,
7185                                 "%s %s: unrecommended max-inherit=%d when default stripe-count=%lld\n",
7186                                 progname, argv[0], max_inherit,
7187                                 lsa.lsa_stripe_count);
7188         }
7189
7190         if (default_stripe && lsa.lsa_nr_tgts > 1 && !mdt_count_set) {
7191                 fprintf(stderr,
7192                         "%s %s: trying to create unrecommended default striped directory layout,\n"
7193                         "       '-D -i x,y,z' will stripe every new directory across all MDTs,\n"
7194                         "       add -c with the number of MDTs to do this anyway\n",
7195                         progname, argv[0]);
7196                 return CMD_HELP;
7197         }
7198
7199         if (max_inherit_rr != LAYOUT_INHERIT_UNSET &&
7200             lsa.lsa_stripe_off != LLAPI_LAYOUT_DEFAULT &&
7201             lsa.lsa_stripe_off != LMV_OFFSET_DEFAULT) {
7202                 fprintf(stderr,
7203                         "%s %s: max-inherit-rr needs mdt-index=-1, not %lld\n",
7204                         progname, argv[0], lsa.lsa_stripe_off);
7205                 return CMD_HELP;
7206         }
7207
7208         /* foreign LMV/dir case */
7209         if (foreign_mode) {
7210                 if (argc > optind + 1) {
7211                         fprintf(stderr,
7212                                 "%s %s: cannot specify multiple foreign dirs\n",
7213                                 progname, argv[0]);
7214                         return CMD_HELP;
7215                 }
7216
7217                 dname = argv[optind];
7218                 result = llapi_dir_create_foreign(dname, mode, type, flags,
7219                                                   xattr);
7220                 if (result != 0)
7221                         fprintf(stderr,
7222                                 "%s mkdir: can't create foreign dir '%s': %s\n",
7223                                 progname, dname, strerror(-result));
7224                 return result;
7225         }
7226
7227         /*
7228          * initialize stripe parameters, in case param is converted to specific,
7229          * i.e, 'lfs mkdir -i -1 -c N', always allocate space for lsp_tgts.
7230          */
7231         param = calloc(1, offsetof(typeof(*param),
7232                        lsp_tgts[lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT ?
7233                                 lsa.lsa_stripe_count : lsa.lsa_nr_tgts]));
7234         if (!param) {
7235                 fprintf(stderr,
7236                         "%s %s: cannot allocate memory for parameters: %s\n",
7237                         progname, argv[0], strerror(ENOMEM));
7238                 return CMD_HELP;
7239         }
7240
7241         /* if "lfs setdirstripe -D -i -1" is used, assume 1-stripe directory */
7242         if (default_stripe && lsa.lsa_stripe_off == LMV_OFFSET_DEFAULT &&
7243             (lsa.lsa_stripe_count == LLAPI_LAYOUT_DEFAULT ||
7244              lsa.lsa_stripe_count == 0))
7245                 lsa.lsa_stripe_count = 1;
7246         if (lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT)
7247                 param->lsp_stripe_count = lsa.lsa_stripe_count;
7248         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
7249                 param->lsp_stripe_offset = LMV_OFFSET_DEFAULT;
7250         else
7251                 param->lsp_stripe_offset = lsa.lsa_stripe_off;
7252         if (lsa.lsa_pattern != LLAPI_LAYOUT_RAID0)
7253                 param->lsp_stripe_pattern = lsa.lsa_pattern;
7254         else
7255                 param->lsp_stripe_pattern = LMV_HASH_TYPE_UNKNOWN;
7256         param->lsp_pool = lsa.lsa_pool_name;
7257         param->lsp_is_specific = false;
7258
7259         if (max_inherit == LAYOUT_INHERIT_UNSET) {
7260                 if (lsa.lsa_stripe_count == 0 || lsa.lsa_stripe_count == 1 ||
7261                     lsa.lsa_stripe_count == LLAPI_LAYOUT_DEFAULT)
7262                         max_inherit = LMV_INHERIT_DEFAULT_PLAIN;
7263                 else
7264                         max_inherit = LMV_INHERIT_DEFAULT_STRIPED;
7265         }
7266         param->lsp_max_inherit = max_inherit;
7267         if (default_stripe) {
7268
7269                 if (max_inherit_rr == LAYOUT_INHERIT_UNSET)
7270                         max_inherit_rr = LMV_INHERIT_RR_DEFAULT;
7271                 param->lsp_max_inherit_rr = max_inherit_rr;
7272         }
7273         if (strcmp(argv[0], "mkdir") == 0)
7274                 param->lsp_is_create = true;
7275         if (lsa.lsa_nr_tgts > 1) {
7276                 if (lsa.lsa_stripe_count > 0 &&
7277                     lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT &&
7278                     lsa.lsa_stripe_count != lsa.lsa_nr_tgts) {
7279                         fprintf(stderr,
7280                                 "error: %s: stripe count %lld doesn't match the number of MDTs: %d\n",
7281                                 argv[0], lsa.lsa_stripe_count,
7282                                 lsa.lsa_nr_tgts);
7283                         free(param);
7284                         return CMD_HELP;
7285                 }
7286
7287                 param->lsp_is_specific = true;
7288                 param->lsp_stripe_count = lsa.lsa_nr_tgts;
7289                 memcpy(param->lsp_tgts, mdts, sizeof(*mdts) * lsa.lsa_nr_tgts);
7290         }
7291
7292         dname = argv[optind];
7293         do {
7294                 if (default_stripe) {
7295                         result = llapi_dir_set_default_lmv(dname, param);
7296                         if (result)
7297                                 fprintf(stderr,
7298                                         "%s setdirstripe: cannot set default stripe on dir '%s': %s\n",
7299                                         progname, dname, strerror(-result));
7300                         continue;
7301                 }
7302
7303                 result = llapi_dir_create(dname, mode, param);
7304                 if (result)
7305                         fprintf(stderr,
7306                                 "%s setdirstripe: cannot create dir '%s': %s\n",
7307                                 progname, dname, strerror(-result));
7308         } while (!result && (dname = argv[++optind]));
7309
7310         if (mode_opt)
7311                 umask(previous_mode);
7312
7313         free(param);
7314         return result;
7315 }
7316
7317 static int lfs_rmentry(int argc, char **argv)
7318 {
7319         char *dname;
7320         int index;
7321         int result = 0;
7322
7323         if (argc <= 1) {
7324                 fprintf(stderr, "error: %s: missing dirname\n",
7325                         argv[0]);
7326                 return CMD_HELP;
7327         }
7328
7329         index = 1;
7330         dname = argv[index];
7331         while (dname) {
7332                 int rc2;
7333
7334                 rc2 = llapi_direntry_remove(dname);
7335                 if (rc2) {
7336                         fprintf(stderr,
7337                                 "%s %s: remove dir entry '%s' failed: %s\n",
7338                                 progname, argv[0], dname, strerror(-rc2));
7339                         if (!result)
7340                                 result = rc2;
7341                 }
7342                 dname = argv[++index];
7343         }
7344         return result;
7345 }
7346
7347 static int lfs_unlink_foreign(int argc, char **argv)
7348 {
7349         char *name;
7350         int   index;
7351         int   result = 0;
7352
7353         if (argc <= 1) {
7354                 fprintf(stderr, "error: %s: missing pathname\n",
7355                         argv[0]);
7356                 return CMD_HELP;
7357         }
7358
7359         index = 1;
7360         name = argv[index];
7361         while (name != NULL) {
7362                 result = llapi_unlink_foreign(name);
7363                 if (result) {
7364                         fprintf(stderr,
7365                                 "error: %s: unlink foreign entry '%s' failed\n",
7366                                 argv[0], name);
7367                         break;
7368                 }
7369                 name = argv[++index];
7370         }
7371         return result;
7372 }
7373
7374 static int lfs_mv(int argc, char **argv)
7375 {
7376         struct lmv_user_md lmu = { LMV_USER_MAGIC };
7377         struct find_param param = {
7378                 .fp_max_depth = -1,
7379                 .fp_mdt_index = -1,
7380         };
7381         char *end;
7382         int c;
7383         int rc = 0;
7384         struct option long_opts[] = {
7385         { .val = 'm',   .name = "mdt",          .has_arg = required_argument },
7386         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument },
7387         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
7388         { .name = NULL } };
7389
7390         while ((c = getopt_long(argc, argv, "m:M:v", long_opts, NULL)) != -1) {
7391                 switch (c) {
7392 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
7393                 case 'M':
7394                         fprintf(stderr,
7395                                 "warning: '-M' deprecated, use '--mdt-index' or '-m' instead\n");
7396 #endif
7397                 case 'm':
7398                         errno = 0;
7399                         lmu.lum_stripe_offset = strtoul(optarg, &end, 0);
7400                         if (errno != 0 || *end != '\0' ||
7401                             lmu.lum_stripe_offset >= UINT32_MAX) {
7402                                 fprintf(stderr, "%s mv: bad MDT index '%s'\n",
7403                                         progname, optarg);
7404                                 return CMD_HELP;
7405                         }
7406                         break;
7407                 case 'v':
7408                         param.fp_verbose = VERBOSE_DETAIL;
7409                         break;
7410                 default:
7411                         fprintf(stderr, "%s mv: unrecognized option '%s'\n",
7412                                 progname, argv[optind - 1]);
7413                         return CMD_HELP;
7414                 }
7415         }
7416
7417         if (lmu.lum_stripe_offset == LMV_OFFSET_DEFAULT) {
7418                 fprintf(stderr, "%s mv: MDT index must be specified\n",
7419                         progname);
7420                 return CMD_HELP;
7421         }
7422
7423         if (optind >= argc) {
7424                 fprintf(stderr, "%s mv: DIR must be specified\n", progname);
7425                 return CMD_HELP;
7426         }
7427
7428         lmu.lum_hash_type = LMV_HASH_TYPE_UNKNOWN;
7429
7430         /* initialize migrate mdt parameters */
7431         param.fp_lmv_md = &lmu;
7432         param.fp_migrate = 1;
7433         rc = llapi_migrate_mdt(argv[optind], &param);
7434         if (rc != 0)
7435                 fprintf(stderr, "%s mv: cannot migrate '%s' to MDT%04x: %s\n",
7436                         progname, argv[optind], lmu.lum_stripe_offset,
7437                         strerror(-rc));
7438         return rc;
7439 }
7440
7441 static int lfs_osts(int argc, char **argv)
7442 {
7443         return lfs_tgts(argc, argv);
7444 }
7445
7446 static int lfs_mdts(int argc, char **argv)
7447 {
7448         return lfs_tgts(argc, argv);
7449 }
7450
7451 static int lfs_df(int argc, char **argv)
7452 {
7453         char mntdir[PATH_MAX] = {'\0'}, path[PATH_MAX] = {'\0'};
7454         enum mntdf_flags flags = MNTDF_SHOW;
7455         int ops = LL_STATFS_LMV | LL_STATFS_LOV;
7456         int c, rc = 0, rc1 = 0, index = 0, arg_idx = 0;
7457         char fsname[PATH_MAX] = "", *pool_name = NULL;
7458         struct option long_opts[] = {
7459         { .val = 'h',   .name = "human-readable", .has_arg = no_argument },
7460         { .val = 'H',   .name = "si",           .has_arg = no_argument },
7461         { .val = 'i',   .name = "inodes",       .has_arg = no_argument },
7462         { .val = 'l',   .name = "lazy",         .has_arg = no_argument },
7463         { .val = 'p',   .name = "pool",         .has_arg = required_argument },
7464         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
7465         { .name = NULL} };
7466
7467         while ((c = getopt_long(argc, argv, "hHilp:v", long_opts, NULL)) != -1) {
7468                 switch (c) {
7469                 case 'h':
7470                         flags = (flags & ~MNTDF_DECIMAL) | MNTDF_COOKED;
7471                         break;
7472                 case 'H':
7473                         flags |= MNTDF_COOKED | MNTDF_DECIMAL;
7474                         break;
7475                 case 'i':
7476                         flags |= MNTDF_INODES;
7477                         break;
7478                 case 'l':
7479                         flags |= MNTDF_LAZY;
7480                         break;
7481                 case 'p':
7482                         pool_name = optarg;
7483                         break;
7484                 case 'v':
7485                         flags |= MNTDF_VERBOSE;
7486                         break;
7487                 default:
7488                         fprintf(stderr, "%s: unrecognized option '%s'\n",
7489                                 progname, argv[optind - 1]);
7490                         return CMD_HELP;
7491                 }
7492         }
7493
7494         /* Handle case where path is not specified */
7495         if (optind == argc) {
7496                 while (!llapi_search_mounts(path, index++, mntdir, fsname)) {
7497                         /* Check if we have a mount point */
7498                         if (mntdir[0] == '\0')
7499                                 continue;
7500
7501                         rc = mntdf(mntdir, fsname, pool_name, flags, ops, NULL);
7502                         if (rc || path[0] != '\0')
7503                                 break;
7504
7505                         fsname[0] = '\0'; /* avoid matching in next loop */
7506                         mntdir[0] = '\0'; /* avoid matching in next loop */
7507                         path[0] = '\0'; /* clean for next loop */
7508                 }
7509                 return rc;
7510         }
7511
7512         /* Loop through all the remaining arguments. These are Lustre FS
7513          * paths.
7514          */
7515         for (arg_idx = optind; arg_idx <= argc - 1; arg_idx++) {
7516                 bool valid = false;
7517
7518                 fsname[0] = '\0'; /* start clean */
7519                 mntdir[0] = '\0'; /* start clean */
7520                 path[0] = '\0';   /* start clean */
7521
7522                 /* path does not exists at all */
7523                 if (!realpath(argv[arg_idx], path)) {
7524                         rc = -errno;
7525                         fprintf(stderr, "error: invalid path '%s': %s\n",
7526                                 argv[arg_idx], strerror(-rc));
7527                         /* save first seen error */
7528                         if (!rc1)
7529                                 rc1 = rc;
7530
7531                         continue;
7532                 }
7533
7534                 /* path exists but may not be a Lustre filesystem */
7535                 while (!llapi_search_mounts(path, index++, mntdir, fsname)) {
7536                         /* Check if we have a mount point */
7537                         if (mntdir[0] == '\0')
7538                                 continue;
7539
7540                         rc = mntdf(mntdir, fsname, pool_name, flags, ops, NULL);
7541                         if (rc || path[0] != '\0') {
7542                                 valid = true;
7543
7544                                 /* save first seen error */
7545                                 if (!rc1)
7546                                         rc1 = rc;
7547                                 break;
7548                         }
7549                 }
7550
7551                 if (!valid) {
7552                         llapi_printf(LLAPI_MSG_ERROR,
7553                                      "%s:%s Not a Lustre filesystem\n",
7554                                      argv[0], argv[arg_idx]);
7555                         /* save first seen error */
7556                         if (!rc1)
7557                                 rc1 = -EOPNOTSUPP;
7558                 }
7559         }
7560
7561         return rc1;
7562 }
7563
7564 static int print_instance(const char *mntdir, char *buf, size_t buflen,
7565                           bool opt_instance, bool opt_fsname, bool opt_mntdir)
7566 {
7567         int rc = 0;
7568
7569         if (opt_fsname == opt_instance) { /* both true or both false */
7570                 rc = llapi_getname(mntdir, buf, buflen);
7571         } else if (opt_fsname) {
7572                 /*
7573                  * llapi_search_mounts() fills @buf with fsname, but that is not
7574                  * called if explicit paths are specified on the command-line
7575                  */
7576                 if (buf[0] == '\0')
7577                         rc = llapi_get_fsname(mntdir, buf, buflen);
7578         } else /* if (opt_instance) */ {
7579                 rc = llapi_get_instance(mntdir, buf, buflen);
7580         }
7581
7582         if (rc < 0) {
7583                 fprintf(stderr, "cannot get instance for '%s': %s\n",
7584                         mntdir, strerror(-rc));
7585                 return rc;
7586         }
7587
7588         if (opt_mntdir)
7589                 printf("%s %s\n", buf, mntdir);
7590         else
7591                 printf("%s\n", buf);
7592
7593         return 0;
7594 }
7595
7596 static int lfs_getname(int argc, char **argv)
7597 {
7598         struct option long_opts[] = {
7599         { .val = 'h',   .name = "help",         .has_arg = no_argument },
7600         { .val = 'i',   .name = "instance",     .has_arg = no_argument },
7601         { .val = 'n',   .name = "fsname",       .has_arg = no_argument },
7602         { .name = NULL} };
7603         bool opt_instance = false, opt_fsname = false;
7604         char fsname[PATH_MAX] = "";
7605         int rc = 0, rc2, c;
7606
7607         while ((c = getopt_long(argc, argv, "hin", long_opts, NULL)) != -1) {
7608                 switch (c) {
7609                 case 'i':
7610                         opt_instance = true;
7611                         break;
7612                 case 'n':
7613                         opt_fsname = true;
7614                         break;
7615                 default:
7616                         fprintf(stderr, "%s: unrecognized option '%s'\n",
7617                                 progname, argv[optind - 1]);
7618                         fallthrough;
7619                 case 'h':
7620                         return CMD_HELP;
7621                 }
7622         }
7623
7624         if (optind == argc) { /* no paths specified, get all paths. */
7625                 char mntdir[PATH_MAX] = "", path[PATH_MAX] = "";
7626                 int index = 0;
7627
7628                 while (!llapi_search_mounts(path, index++, mntdir, fsname)) {
7629                         rc2 = print_instance(mntdir, fsname, sizeof(fsname),
7630                                              opt_instance, opt_fsname, true);
7631                         if (!rc)
7632                                 rc = rc2;
7633                         path[0] = fsname[0] = mntdir[0] = '\0';
7634                 }
7635         } else { /* paths specified, only attempt to search these. */
7636                 bool opt_mntdir;
7637
7638                 /* if only one path is given, print only requested info */
7639                 opt_mntdir = argc - optind > 1 || (opt_instance == opt_fsname);
7640
7641                 for (; optind < argc; optind++) {
7642                         rc2 = print_instance(argv[optind], fsname,
7643                                              sizeof(fsname), opt_instance,
7644                                              opt_fsname, opt_mntdir);
7645                         if (!rc)
7646                                 rc = rc2;
7647                         fsname[0] = '\0';
7648                 }
7649         }
7650
7651         return rc;
7652 }
7653
7654 static int lfs_check(int argc, char **argv)
7655 {
7656         char mntdir[PATH_MAX] = {'\0'}, path[PATH_MAX] = {'\0'};
7657         int num_types = 1;
7658         char *obd_types[3];
7659         char obd_type1[4];
7660         char obd_type2[4];
7661         char obd_type3[4];
7662         int rc;
7663
7664         if (argc < 2 || argc > 3) {
7665                 fprintf(stderr, "%s check: server type must be specified\n",
7666                         progname);
7667                 return CMD_HELP;
7668         }
7669
7670         obd_types[0] = obd_type1;
7671         obd_types[1] = obd_type2;
7672         obd_types[2] = obd_type3;
7673
7674         if (strcmp(argv[1], "osts") == 0) {
7675                 strcpy(obd_types[0], "osc");
7676         } else if (strcmp(argv[1], "mdts") == 0 ||
7677                    strcmp(argv[1], "mds") == 0) {
7678                 strcpy(obd_types[0], "mdc");
7679         } else if (strcmp(argv[1], "mgts") == 0) {
7680                 strcpy(obd_types[0], "mgc");
7681         } else if (strcmp(argv[1], "all") == 0 ||
7682                    strcmp(argv[1], "servers") == 0) {
7683                 num_types = 3;
7684                 strcpy(obd_types[0], "osc");
7685                 strcpy(obd_types[1], "mdc");
7686                 strcpy(obd_types[2], "mgc");
7687         } else {
7688                 fprintf(stderr, "%s check: unrecognized option '%s'\n",
7689                         progname, argv[1]);
7690                 return CMD_HELP;
7691         }
7692
7693         if (argc >= 3 && !realpath(argv[2], path)) {
7694                 rc = -errno;
7695                 fprintf(stderr, "error: invalid path '%s': %s\n",
7696                         argv[2], strerror(-rc));
7697                 return rc;
7698         }
7699
7700         rc = llapi_search_mounts(path, 0, mntdir, NULL);
7701         if (rc < 0 || mntdir[0] == '\0') {
7702                 fprintf(stderr,
7703                         "%s %s: cannot find mounted Lustre filesystem: %s\n",
7704                         progname, argv[0],
7705                         (rc < 0) ? strerror(-rc) : strerror(ENODEV));
7706                 return rc;
7707         }
7708
7709         rc = llapi_target_check(num_types, obd_types, path);
7710         if (rc)
7711                 fprintf(stderr, "%s %s: cannot check target '%s': %s\n",
7712                         progname, argv[0], argv[1], strerror(-rc));
7713
7714         return rc;
7715 }
7716
7717 #ifdef HAVE_SYS_QUOTA_H
7718 #define ADD_OVERFLOW(a, b) \
7719                      ((((a) + (b)) < (a)) ? \
7720                       ((a) = ULONG_MAX) : ((a) = (a) + (b)))
7721
7722 /* Convert format time string "XXwXXdXXhXXmXXs" into seconds value
7723  * returns the value or ULONG_MAX on integer overflow or incorrect format
7724  * Notes:
7725  *        1. the order of specifiers is arbitrary (may be: 5w3s or 3s5w)
7726  *        2. specifiers may be encountered multiple times (2s3s is 5 seconds)
7727  *        3. empty integer value is interpreted as 0
7728  */
7729 static unsigned long str2sec(const char *timestr)
7730 {
7731         const char spec[] = "smhdw";
7732         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
7733         unsigned long val = 0;
7734         char *tail;
7735
7736         if (strpbrk(timestr, spec) == NULL) {
7737                 /*
7738                  * no specifiers inside the time string,
7739                  * should treat it as an integer value
7740                  */
7741                 val = strtoul(timestr, &tail, 10);
7742                 return *tail ? ULONG_MAX : val;
7743         }
7744
7745         /* format string is XXwXXdXXhXXmXXs */
7746         while (*timestr) {
7747                 unsigned long v;
7748                 int ind;
7749                 char *ptr;
7750
7751                 v = strtoul(timestr, &tail, 10);
7752                 if (v == ULONG_MAX || *tail == '\0')
7753                         /*
7754                          * value too large (ULONG_MAX or more)
7755                          * or missing specifier
7756                          */
7757                         goto error;
7758
7759                 ptr = strchr(spec, *tail);
7760                 if (!ptr)
7761                         /* unknown specifier */
7762                         goto error;
7763
7764                 ind = ptr - spec;
7765
7766                 /* check if product will overflow the type */
7767                 if (!(v < ULONG_MAX / mult[ind]))
7768                         goto error;
7769
7770                 ADD_OVERFLOW(val, mult[ind] * v);
7771                 if (val == ULONG_MAX)
7772                         goto error;
7773
7774                 timestr = tail + 1;
7775         }
7776
7777         return val;
7778
7779 error:
7780         return ULONG_MAX;
7781 }
7782
7783 #define ARG2ULL(nr, str, def_units)                                     \
7784 do {                                                                    \
7785         unsigned long long limit, units = def_units;                    \
7786         int rc;                                                         \
7787                                                                         \
7788         rc = llapi_parse_size(str, &limit, &units, 1);                  \
7789         if (rc < 0) {                                                   \
7790                 fprintf(stderr, "%s: invalid limit '%s'\n",             \
7791                         progname, str);                                 \
7792                 return CMD_HELP;                                        \
7793         }                                                               \
7794         nr = limit;                                                     \
7795 } while (0)
7796
7797 static inline int has_times_option(int argc, char **argv)
7798 {
7799         int i;
7800
7801         for (i = 1; i < argc; i++)
7802                 if (!strcmp(argv[i], "-t"))
7803                         return 1;
7804
7805         return 0;
7806 }
7807
7808 static inline int lfs_verify_poolarg(char *pool)
7809 {
7810         if (strnlen(optarg, LOV_MAXPOOLNAME + 1) > LOV_MAXPOOLNAME) {
7811                 fprintf(stderr,
7812                         "Pool name '%.*s' is longer than %d\n",
7813                         LOV_MAXPOOLNAME, pool, LOV_MAXPOOLNAME);
7814                 return 1;
7815         }
7816         return 0;
7817 }
7818
7819 /* special grace time, only notify the user when its quota is over soft limit
7820  * but doesn't block new writes until the hard limit is reached.
7821  */
7822 #define NOTIFY_GRACE            "notify"
7823 #define NOTIFY_GRACE_TIME       LQUOTA_GRACE_MASK
7824
7825 #ifndef toqb
7826 static inline __u64 lustre_stoqb(size_t space)
7827 {
7828         return (space + QIF_DQBLKSIZE - 1) >> QIF_DQBLKSIZE_BITS;
7829 }
7830 #else
7831 #define lustre_stoqb   toqb
7832 #endif
7833
7834 int lfs_setquota_times(int argc, char **argv, struct if_quotactl *qctl)
7835 {
7836         int c, rc;
7837         char *mnt, *obd_type = (char *)qctl->obd_type;
7838         struct obd_dqblk *dqb = &qctl->qc_dqblk;
7839         struct obd_dqinfo *dqi = &qctl->qc_dqinfo;
7840         struct option long_opts[] = {
7841         { .val = 'b',   .name = "block-grace",  .has_arg = required_argument },
7842         { .val = 'g',   .name = "group",        .has_arg = no_argument },
7843         { .val = 'h',   .name = "help",         .has_arg = no_argument },
7844         { .val = 'i',   .name = "inode-grace",  .has_arg = required_argument },
7845         { .val = 'p',   .name = "projid",       .has_arg = no_argument },
7846         { .val = 't',   .name = "times",        .has_arg = no_argument },
7847         { .val = 'u',   .name = "user",         .has_arg = no_argument },
7848         { .val = LFS_POOL_OPT,
7849                         .name = "pool",         .has_arg = required_argument },
7850         { .name = NULL } };
7851         int qtype;
7852
7853         qctl->qc_cmd  = LUSTRE_Q_SETINFO;
7854         qctl->qc_type = ALLQUOTA;
7855
7856         while ((c = getopt_long(argc, argv, "b:ghi:ptu",
7857                                 long_opts, NULL)) != -1) {
7858                 switch (c) {
7859                 case 'u':
7860                         qtype = USRQUOTA;
7861                         goto quota_type;
7862                 case 'g':
7863                         qtype = GRPQUOTA;
7864                         goto quota_type;
7865                 case 'p':
7866                         qtype = PRJQUOTA;
7867 quota_type:
7868                         if (qctl->qc_type != ALLQUOTA) {
7869                                 fprintf(stderr,
7870                                         "%s: -u/g/p cannot be used more than once\n",
7871                                         progname);
7872                                 return CMD_HELP;
7873                         }
7874                         qctl->qc_type = qtype;
7875                         break;
7876                 case 'b':
7877                         if (strncmp(optarg, NOTIFY_GRACE,
7878                                     strlen(NOTIFY_GRACE)) == 0) {
7879                                 dqi->dqi_bgrace = NOTIFY_GRACE_TIME;
7880                         } else {
7881                                 dqi->dqi_bgrace = str2sec(optarg);
7882                                 if (dqi->dqi_bgrace >= NOTIFY_GRACE_TIME) {
7883                                         fprintf(stderr,
7884                                                 "%s: bad block-grace: %s\n",
7885                                                 progname, optarg);
7886                                         return CMD_HELP;
7887                                 }
7888                         }
7889                         dqb->dqb_valid |= QIF_BTIME;
7890                         break;
7891                 case 'i':
7892                         if (strncmp(optarg, NOTIFY_GRACE,
7893                                     strlen(NOTIFY_GRACE)) == 0) {
7894                                 dqi->dqi_igrace = NOTIFY_GRACE_TIME;
7895                         } else {
7896                                 dqi->dqi_igrace = str2sec(optarg);
7897                                 if (dqi->dqi_igrace >= NOTIFY_GRACE_TIME) {
7898                                         fprintf(stderr,
7899                                                 "%s: bad inode-grace: %s\n",
7900                                                 progname, optarg);
7901                                         return CMD_HELP;
7902                                 }
7903                         }
7904                         dqb->dqb_valid |= QIF_ITIME;
7905                         break;
7906                 case 't': /* Yes, of course! */
7907                         break;
7908                 case LFS_POOL_OPT:
7909                         if (lfs_verify_poolarg(optarg))
7910                                 return -1;
7911                         strncpy(qctl->qc_poolname, optarg, LOV_MAXPOOLNAME);
7912                         qctl->qc_cmd  = LUSTRE_Q_SETINFOPOOL;
7913                         break;
7914                 /* getopt prints error message for us when opterr != 0 */
7915                 default:
7916                         fprintf(stderr, "%s: unrecognized option '%s'\n",
7917                                 progname, argv[optind - 1]);
7918                         fallthrough;
7919                 case 'h':
7920                         return CMD_HELP;
7921                 }
7922         }
7923
7924         if (qctl->qc_type == ALLQUOTA) {
7925                 fprintf(stderr, "%s: neither -u, -g nor -p specified\n",
7926                         progname);
7927                 return CMD_HELP;
7928         }
7929
7930         if (optind != argc - 1) {
7931                 fprintf(stderr, "%s: unexpected parameter '%s'\n",
7932                         progname, argv[optind + 1]);
7933                 return CMD_HELP;
7934         }
7935
7936         mnt = argv[optind];
7937         rc = llapi_quotactl(mnt, qctl);
7938         if (rc) {
7939                 if (*obd_type)
7940                         fprintf(stderr, "%s %s ", obd_type,
7941                                 obd_uuid2str(&qctl->obd_uuid));
7942                 fprintf(stderr, "setquota failed: %s\n", strerror(-rc));
7943                 return rc;
7944         }
7945
7946         return 0;
7947 }
7948
7949 static int lfs_reset_quota(char *mnt, struct if_quotactl *qctl)
7950 {
7951         struct if_quotactl tmp_qctl;
7952         int index, md_count, dt_count;
7953         int wait_phase = 0, wait_index = 0, wait_count = 0;
7954         int rc, rc2;
7955
7956         /* reset the quota ID, the existing quota setting will be returned */
7957         rc = llapi_quotactl(mnt, qctl);
7958         if (rc)
7959                 return rc;
7960
7961         /* sanity check */
7962         if ((qctl->qc_dqblk.dqb_valid & QIF_LIMITS) != QIF_LIMITS) {
7963                 fprintf(stderr,
7964                         "the existing quota settings are not returned!\n");
7965                 return -EINVAL;
7966         }
7967
7968         rc = llapi_get_obd_count(mnt, &md_count, 1);
7969         if (rc) {
7970                 fprintf(stderr, "can not get mdt count: %s\n", strerror(-rc));
7971                 return rc;
7972         }
7973
7974         rc = llapi_get_obd_count(mnt, &dt_count, 0);
7975         if (rc) {
7976                 fprintf(stderr, "can not get ost count: %s\n", strerror(-rc));
7977                 return rc;
7978         }
7979
7980         memset(&tmp_qctl, 0, sizeof(tmp_qctl));
7981         tmp_qctl.qc_type = qctl->qc_type;
7982         tmp_qctl.qc_id = qctl->qc_id;
7983         tmp_qctl.qc_cmd = LUSTRE_Q_GETQUOTA;
7984
7985 retry:
7986         if (wait_phase == 0) {
7987                 for (index = wait_index; index < md_count; index++) {
7988                         tmp_qctl.qc_idx = index;
7989                         tmp_qctl.qc_valid = QC_MDTIDX;
7990                         rc = llapi_quotactl(mnt, &tmp_qctl);
7991                         if (rc == -ENODEV || rc == -ENODATA)
7992                                 continue;
7993                         if (rc) {
7994                                 fprintf(stderr, "quotactl mdt%d failed: %s\n",
7995                                         index, strerror(-rc));
7996                                 break;
7997                         }
7998                         /* check whether the md quota grant is reset */
7999                         if (tmp_qctl.qc_dqblk.dqb_valid & QIF_LIMITS &&
8000                             tmp_qctl.qc_dqblk.dqb_ihardlimit != 0)
8001                                 break;
8002                 }
8003
8004                 if (index < md_count) {
8005                         wait_phase = 0;
8006                         wait_index = index;
8007                         goto wait;
8008                 }
8009         } else {
8010                 for (index = wait_index; index < dt_count; index++) {
8011                         tmp_qctl.qc_idx = index;
8012                         tmp_qctl.qc_valid = QC_OSTIDX;
8013                         rc = llapi_quotactl(mnt, &tmp_qctl);
8014                         if (rc == -ENODEV || rc == -ENODATA)
8015                                 continue;
8016                         if (rc) {
8017                                 fprintf(stderr, "quotactl mdt%d failed: %s\n",
8018                                         index, strerror(-rc));
8019                                 break;
8020                         }
8021                         /* check whether the dt quota grant is reset */
8022                         if (tmp_qctl.qc_dqblk.dqb_valid & QIF_LIMITS &&
8023                             tmp_qctl.qc_dqblk.dqb_bhardlimit != 0)
8024                                 break;
8025                 }
8026
8027                 if (index < dt_count) {
8028                         wait_phase = 1;
8029                         wait_index = index;
8030                         goto wait;
8031                 }
8032         }
8033
8034         if (wait_phase == 0) {
8035                 wait_phase = 1;
8036                 goto retry;
8037         }
8038
8039         goto out;
8040
8041 wait:
8042         if (rc || wait_count > 30) {
8043                 fprintf(stderr, "fail to reset the quota ID %d on OBDs\n",
8044                         qctl->qc_id);
8045                 goto out;
8046         }
8047
8048         wait_count++;
8049         sleep(1);
8050         fprintf(stdout, "wait %d seconds for OBDs to reset the quota ID %u\n",
8051                 wait_count, qctl->qc_id);
8052         goto retry;
8053
8054
8055 out:
8056         /* restore the quota setting */
8057         if (qctl->qc_dqblk.dqb_isoftlimit == 0 &&
8058             qctl->qc_dqblk.dqb_ihardlimit == 0 &&
8059             qctl->qc_dqblk.dqb_bsoftlimit == 0 &&
8060             qctl->qc_dqblk.dqb_bhardlimit == 0)
8061                 return rc;
8062
8063         memcpy(&tmp_qctl, qctl, sizeof(tmp_qctl));
8064         tmp_qctl.qc_cmd = LUSTRE_Q_SETQUOTA;
8065         rc2 = llapi_quotactl(mnt, &tmp_qctl);
8066         if (!rc2)
8067                 return rc;
8068
8069         fprintf(stderr,
8070                 "fail to restore the quota setting: %s, please restore it manually by\n  lfs setquota %s %d",
8071                 strerror(-rc2),
8072                 qctl->qc_type == USRQUOTA ? "-u" :
8073                                 (qctl->qc_type == GRPQUOTA ? "-g" : "-p"),
8074                 qctl->qc_id);
8075
8076         if (qctl->qc_dqblk.dqb_isoftlimit != 0)
8077                 fprintf(stderr, " -i %llu",
8078                         (unsigned long long)qctl->qc_dqblk.dqb_isoftlimit);
8079         if (qctl->qc_dqblk.dqb_ihardlimit != 0)
8080                 fprintf(stderr, " -I %llu",
8081                         (unsigned long long)qctl->qc_dqblk.dqb_ihardlimit);
8082         if (qctl->qc_dqblk.dqb_bsoftlimit != 0)
8083                 fprintf(stderr, " -b %llu",
8084                         (unsigned long long)qctl->qc_dqblk.dqb_bsoftlimit);
8085         if (qctl->qc_dqblk.dqb_bhardlimit != 0)
8086                 fprintf(stderr, " -B %llu",
8087                         (unsigned long long)qctl->qc_dqblk.dqb_bhardlimit);
8088
8089         fprintf(stderr, " %s\n", mnt);
8090         if (!rc)
8091                 rc = rc2;
8092
8093         return rc;
8094 }
8095
8096 #define BSLIMIT (1 << 0)
8097 #define BHLIMIT (1 << 1)
8098 #define ISLIMIT (1 << 2)
8099 #define IHLIMIT (1 << 3)
8100
8101 int lfs_setquota(int argc, char **argv)
8102 {
8103         int c, rc = 0;
8104         struct if_quotactl *qctl;
8105         char *mnt, *obd_type;
8106         struct obd_dqblk *dqb;
8107         struct option long_opts[] = {
8108         { .val = 'b',   .name = "block-softlimit",
8109                                                 .has_arg = required_argument },
8110         { .val = 'B',   .name = "block-hardlimit",
8111                                                 .has_arg = required_argument },
8112         { .val = 'd',   .name = "default",      .has_arg = no_argument },
8113         { .val = LFS_SETQUOTA_DELETE,
8114                         .name = "delete",       .has_arg = no_argument },
8115         { .val = 'g',   .name = "group",        .has_arg = required_argument },
8116         { .val = 'G',   .name = "default-grp",  .has_arg = no_argument },
8117         { .val = 'h',   .name = "help",         .has_arg = no_argument },
8118         { .val = 'i',   .name = "inode-softlimit",
8119                                                 .has_arg = required_argument },
8120         { .val = 'I',   .name = "inode-hardlimit",
8121                                                 .has_arg = required_argument },
8122         { .val = 'p',   .name = "projid",       .has_arg = required_argument },
8123         { .val = 'P',   .name = "default-prj",  .has_arg = no_argument },
8124         { .val = 'r',   .name = "reset",        .has_arg = no_argument },
8125         { .val = 'u',   .name = "user",         .has_arg = required_argument },
8126         { .val = 'U',   .name = "default-usr",  .has_arg = no_argument },
8127         { .val = LFS_POOL_OPT,
8128                         .name = "pool",         .has_arg = required_argument },
8129         { .name = NULL } };
8130         unsigned int limit_mask = 0;
8131         bool use_default = false;
8132         int qtype, qctl_len;
8133
8134         qctl_len = sizeof(*qctl) + LOV_MAXPOOLNAME + 1;
8135         qctl = malloc(qctl_len);
8136         if (!qctl)
8137                 return -ENOMEM;
8138
8139         memset(qctl, 0, qctl_len);
8140         obd_type = (char *)qctl->obd_type;
8141         dqb = &qctl->qc_dqblk;
8142
8143         if (has_times_option(argc, argv)) {
8144                 rc = lfs_setquota_times(argc, argv, qctl);
8145                 goto out;
8146         }
8147
8148         qctl->qc_cmd  = LUSTRE_Q_SETQUOTA;
8149         qctl->qc_type = ALLQUOTA; /* ALLQUOTA makes no sense for setquota,
8150                                    * so it can be used as a marker that qc_type
8151                                    * isn't reinitialized from command line
8152                                    */
8153         while ((c = getopt_long(argc, argv, "b:B:dDg:Ghi:I:p:Pru:U",
8154                 long_opts, NULL)) != -1) {
8155                 switch (c) {
8156                 case 'U':
8157                         qctl->qc_cmd = LUSTRE_Q_SETDEFAULT;
8158                         qtype = USRQUOTA;
8159                         qctl->qc_id = 0;
8160                         goto quota_type_def;
8161                 case 'u':
8162                         qtype = USRQUOTA;
8163                         rc = name2uid(&qctl->qc_id, optarg);
8164                         goto quota_type;
8165                 case 'G':
8166                         qctl->qc_cmd = LUSTRE_Q_SETDEFAULT;
8167                         qtype = GRPQUOTA;
8168                         qctl->qc_id = 0;
8169                         goto quota_type_def;
8170                 case 'g':
8171                         qtype = GRPQUOTA;
8172                         rc = name2gid(&qctl->qc_id, optarg);
8173                         goto quota_type;
8174                 case 'P':
8175                         qctl->qc_cmd = LUSTRE_Q_SETDEFAULT;
8176                         qtype = PRJQUOTA;
8177                         qctl->qc_id = 0;
8178                         goto quota_type_def;
8179                 case 'p':
8180                         qtype = PRJQUOTA;
8181                         rc = name2projid(&qctl->qc_id, optarg);
8182 quota_type:
8183                         if (rc) {
8184                                 if (str2quotaid(&qctl->qc_id, optarg)) {
8185                                         fprintf(stderr,
8186                                                 "%s setquota: invalid id '%s'\n",
8187                                                 progname, optarg);
8188                                         rc = -1;
8189                                         goto out;
8190                                 }
8191                         }
8192
8193                         if (qctl->qc_id == 0) {
8194                                 fprintf(stderr,
8195                                         "%s setquota: can't set quota for root usr/group/project.\n",
8196                                         progname);
8197                                 rc = -1;
8198                                 goto out;
8199                         }
8200
8201 quota_type_def:
8202                         if (qctl->qc_type != ALLQUOTA) {
8203                                 fprintf(stderr,
8204                                         "%s setquota: only one of -u, -U, -g, -G, -p or -P may be specified\n",
8205                                         progname);
8206                                 rc = CMD_HELP;
8207                                 goto out;
8208                         }
8209                         qctl->qc_type = qtype;
8210                         break;
8211 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
8212                 case 'd':
8213                         fprintf(stderr,
8214                                 "%s setquota: '-d' deprecated, use '-D' or '--default'\n",
8215                                 progname);
8216                         fallthrough;
8217 #endif
8218                 case 'D':
8219                         use_default = true;
8220                         qctl->qc_cmd = LUSTRE_Q_SETDEFAULT;
8221                         break;
8222                 case LFS_SETQUOTA_DELETE:
8223                         qctl->qc_cmd = LUSTRE_Q_DELETEQID;
8224                         break;
8225                 case 'b':
8226                         ARG2ULL(dqb->dqb_bsoftlimit, optarg, 1024);
8227                         dqb->dqb_bsoftlimit >>= 10;
8228                         limit_mask |= BSLIMIT;
8229                         if (dqb->dqb_bsoftlimit &&
8230                             dqb->dqb_bsoftlimit <= 1024) /* <= 1M? */
8231                                 fprintf(stderr,
8232                                         "%s setquota: warning: block softlimit '%llu' smaller than minimum qunit size\nSee '%s help setquota' or Lustre manual for details\n",
8233                                         progname,
8234                                         (unsigned long long)dqb->dqb_bsoftlimit,
8235                                         progname);
8236                         break;
8237                 case 'B':
8238                         ARG2ULL(dqb->dqb_bhardlimit, optarg, 1024);
8239                         dqb->dqb_bhardlimit >>= 10;
8240                         limit_mask |= BHLIMIT;
8241                         if (dqb->dqb_bhardlimit &&
8242                             dqb->dqb_bhardlimit <= 1024) /* <= 1M? */
8243                                 fprintf(stderr,
8244                                         "%s setquota: warning: block hardlimit '%llu' smaller than minimum qunit size\n"
8245                                         "See '%s help setquota' or Lustre manual for details\n",
8246                                         progname,
8247                                         (unsigned long long)dqb->dqb_bhardlimit,
8248                                         progname);
8249                         break;
8250                 case 'i':
8251                         ARG2ULL(dqb->dqb_isoftlimit, optarg, 1);
8252                         limit_mask |= ISLIMIT;
8253                         if (dqb->dqb_isoftlimit &&
8254                             dqb->dqb_isoftlimit <= 1024) /* <= 1K inodes? */
8255                                 fprintf(stderr,
8256                                         "%s setquota: warning: inode softlimit '%llu' smaller than minimum qunit size\nSee '%s help setquota' or Lustre manual for details\n",
8257                                         progname,
8258                                         (unsigned long long)dqb->dqb_isoftlimit,
8259                                         progname);
8260                         break;
8261                 case 'I':
8262                         ARG2ULL(dqb->dqb_ihardlimit, optarg, 1);
8263                         limit_mask |= IHLIMIT;
8264                         if (dqb->dqb_ihardlimit &&
8265                             dqb->dqb_ihardlimit <= 1024) /* <= 1K inodes? */
8266                                 fprintf(stderr,
8267                                         "%s setquota: warning: inode hardlimit '%llu' smaller than minimum qunit size\nSee '%s help setquota' or Lustre manual for details\n",
8268                                         progname,
8269                                         (unsigned long long)dqb->dqb_ihardlimit,
8270                                         progname);
8271                         break;
8272                 case LFS_POOL_OPT:
8273                         if (lfs_verify_poolarg(optarg)) {
8274                                 rc = -1;
8275                                 goto out;
8276                         }
8277                         strncpy(qctl->qc_poolname, optarg, LOV_MAXPOOLNAME);
8278                         qctl->qc_cmd = qctl->qc_cmd == LUSTRE_Q_SETDEFAULT ?
8279                                                 LUSTRE_Q_SETDEFAULT_POOL :
8280                                                 LUSTRE_Q_SETQUOTAPOOL;
8281                         break;
8282                 case 'r':
8283                         qctl->qc_cmd = LUSTRE_Q_RESETQID;
8284                         break;
8285                 default:
8286                         fprintf(stderr,
8287                                 "%s setquota: unrecognized option '%s'\n",
8288                                 progname, argv[optind - 1]);
8289                         fallthrough;
8290                 case 'h':
8291                         rc = CMD_HELP;
8292                         goto out;
8293                 }
8294         }
8295
8296         if (qctl->qc_type == ALLQUOTA) {
8297                 fprintf(stderr,
8298                         "%s setquota: either -u or -g must be specified\n",
8299                         progname);
8300                 rc = CMD_HELP;
8301                 goto out;
8302         }
8303
8304         if (!use_default && qctl->qc_cmd != LUSTRE_Q_DELETEQID &&
8305             qctl->qc_cmd != LUSTRE_Q_RESETQID && limit_mask == 0) {
8306                 fprintf(stderr,
8307                         "%s setquota: at least one limit must be specified\n",
8308                         progname);
8309                 rc = CMD_HELP;
8310                 goto out;
8311         }
8312
8313         if ((use_default || qctl->qc_cmd == LUSTRE_Q_DELETEQID ||
8314              qctl->qc_cmd == LUSTRE_Q_RESETQID) && limit_mask != 0) {
8315                 fprintf(stderr,
8316                         "%s setquota: limits should not be specified when using default quota, deleting or resetting quota ID\n",
8317                         progname);
8318                 rc = CMD_HELP;
8319                 goto out;
8320         }
8321
8322         if (use_default && qctl->qc_id == 0) {
8323                 fprintf(stderr,
8324                         "%s setquota: can not set default quota for root user/group/project\n",
8325                         progname);
8326                 rc = CMD_HELP;
8327                 goto out;
8328         }
8329
8330         if ((qctl->qc_cmd == LUSTRE_Q_DELETEQID ||
8331              qctl->qc_cmd == LUSTRE_Q_RESETQID)  && qctl->qc_id == 0) {
8332                 fprintf(stderr,
8333                         "%s setquota: can not delete or reset root user/group/project\n",
8334                         progname);
8335                 rc = CMD_HELP;
8336                 goto out;
8337         }
8338
8339         if (optind != argc - 1) {
8340                 fprintf(stderr,
8341                         "%s setquota: filesystem not specified or unexpected argument '%s'\n",
8342                         progname, argv[optind]);
8343                 rc = CMD_HELP;
8344                 goto out;
8345         }
8346
8347         mnt = argv[optind];
8348
8349         if (use_default) {
8350                 dqb->dqb_bhardlimit = 0;
8351                 dqb->dqb_bsoftlimit = 0;
8352                 dqb->dqb_ihardlimit = 0;
8353                 dqb->dqb_isoftlimit = 0;
8354                 dqb->dqb_itime = 0;
8355                 dqb->dqb_btime = 0;
8356                 dqb->dqb_valid |= QIF_LIMITS | QIF_TIMES;
8357                 /* do not set inode limits for Pool Quotas */
8358                 if (qctl->qc_cmd  == LUSTRE_Q_SETDEFAULT_POOL)
8359                         dqb->dqb_valid ^= QIF_ILIMITS | QIF_ITIME;
8360         } else if ((!(limit_mask & BHLIMIT) ^ !(limit_mask & BSLIMIT)) ||
8361                    (!(limit_mask & IHLIMIT) ^ !(limit_mask & ISLIMIT))) {
8362                 /* sigh, we can't just set blimits/ilimits */
8363                 struct if_quotactl *tmp_qctl;
8364
8365                 tmp_qctl = calloc(1, sizeof(*qctl) + LOV_MAXPOOLNAME + 1);
8366                 if (!tmp_qctl)
8367                         goto out;
8368
8369                 if (qctl->qc_cmd == LUSTRE_Q_SETQUOTAPOOL) {
8370                         tmp_qctl->qc_cmd = LUSTRE_Q_GETQUOTAPOOL;
8371                         strncpy(tmp_qctl->qc_poolname, qctl->qc_poolname,
8372                                 LOV_MAXPOOLNAME);
8373                 } else {
8374                         tmp_qctl->qc_cmd  = LUSTRE_Q_GETQUOTA;
8375                 }
8376                 tmp_qctl->qc_type = qctl->qc_type;
8377                 tmp_qctl->qc_id = qctl->qc_id;
8378
8379                 rc = llapi_quotactl(mnt, tmp_qctl);
8380                 if (rc < 0) {
8381                         free(tmp_qctl);
8382                         goto out;
8383                 }
8384
8385                 if (!(limit_mask & BHLIMIT))
8386                         dqb->dqb_bhardlimit = tmp_qctl->qc_dqblk.dqb_bhardlimit;
8387                 if (!(limit_mask & BSLIMIT))
8388                         dqb->dqb_bsoftlimit = tmp_qctl->qc_dqblk.dqb_bsoftlimit;
8389                 if (!(limit_mask & IHLIMIT))
8390                         dqb->dqb_ihardlimit = tmp_qctl->qc_dqblk.dqb_ihardlimit;
8391                 if (!(limit_mask & ISLIMIT))
8392                         dqb->dqb_isoftlimit = tmp_qctl->qc_dqblk.dqb_isoftlimit;
8393
8394                 /* Keep grace times if we have got no softlimit arguments */
8395                 if ((limit_mask & BHLIMIT) && !(limit_mask & BSLIMIT)) {
8396                         dqb->dqb_valid |= QIF_BTIME;
8397                         dqb->dqb_btime = tmp_qctl->qc_dqblk.dqb_btime;
8398                 }
8399
8400                 if ((limit_mask & IHLIMIT) && !(limit_mask & ISLIMIT)) {
8401                         dqb->dqb_valid |= QIF_ITIME;
8402                         dqb->dqb_itime = tmp_qctl->qc_dqblk.dqb_itime;
8403                 }
8404                 free(tmp_qctl);
8405         }
8406
8407         dqb->dqb_valid |= (limit_mask & (BHLIMIT | BSLIMIT)) ? QIF_BLIMITS : 0;
8408         dqb->dqb_valid |= (limit_mask & (IHLIMIT | ISLIMIT)) ? QIF_ILIMITS : 0;
8409
8410         if (qctl->qc_cmd == LUSTRE_Q_RESETQID)
8411                 rc = lfs_reset_quota(mnt, qctl);
8412         else
8413                 rc = llapi_quotactl(mnt, qctl);
8414
8415         if (rc) {
8416                 if (*obd_type)
8417                         fprintf(stderr,
8418                                 "%s setquota: cannot quotactl '%s' '%s': %s\n",
8419                                 progname, obd_type,
8420                                 obd_uuid2str(&qctl->obd_uuid), strerror(-rc));
8421                 else
8422                         fprintf(stderr,
8423                                 "%s setquota: quotactl failed: %s\n",
8424                                 progname, strerror(-rc));
8425         }
8426 out:
8427         if (rc)
8428                 fprintf(stderr, "setquota failed: %s\n", strerror(-rc));
8429
8430         free(qctl);
8431         return rc;
8432 }
8433
8434 /* Converts seconds value into format string
8435  * result is returned in buf
8436  * Notes:
8437  *        1. result is in descenting order: 1w2d3h4m5s
8438  *        2. zero fields are not filled (except for p. 3): 5d1s
8439  *        3. zero seconds value is presented as "0s"
8440  */
8441 static char *__sec2str(time_t seconds, char *buf)
8442 {
8443         const char spec[] = "smhdw";
8444         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
8445         unsigned long c;
8446         char *tail = buf;
8447         int i;
8448
8449         for (i = ARRAY_SIZE(mult) - 1 ; i >= 0; i--) {
8450                 c = seconds / mult[i];
8451
8452                 if (c > 0 || (i == 0 && buf == tail))
8453                         tail += scnprintf(tail, 40-(tail-buf), "%lu%c", c,
8454                                           spec[i]);
8455
8456                 seconds %= mult[i];
8457         }
8458
8459         return tail;
8460 }
8461
8462 static void sec2str(time_t seconds, char *buf, int rc)
8463 {
8464         char *tail = buf;
8465
8466         if (rc)
8467                 *tail++ = '[';
8468
8469         tail = __sec2str(seconds, tail);
8470
8471         if (rc && tail - buf < 39) {
8472                 *tail++ = ']';
8473                 *tail++ = 0;
8474         }
8475 }
8476
8477 static void diff2str(time_t seconds, char *buf, time_t now)
8478 {
8479         buf[0] = 0;
8480         if (!seconds)
8481                 return;
8482         if (seconds <= now) {
8483                 strcpy(buf, "expired");
8484                 return;
8485         }
8486         __sec2str(seconds - now, buf);
8487 }
8488
8489 static void print_quota_title(char *name, struct if_quotactl *qctl,
8490                               bool human_readable, bool show_default)
8491 {
8492         if (show_default) {
8493                 printf("Disk default %s quota:\n", qtype_name(qctl->qc_type));
8494                 printf("%15s %8s%8s%8s %8s%8s%8s\n",
8495                        "Filesystem", "bquota", "blimit", "bgrace",
8496                        "iquota", "ilimit", "igrace");
8497         } else {
8498                 printf("Disk quotas for %s %s (%cid %u):\n",
8499                        qtype_name(qctl->qc_type), name,
8500                        *qtype_name(qctl->qc_type), qctl->qc_id);
8501                 printf("%15s%8s %7s%8s%8s%8s %7s%8s%8s\n",
8502                        "Filesystem", human_readable ? "used" : "kbytes",
8503                        "quota", "limit", "grace",
8504                        "files", "quota", "limit", "grace");
8505         }
8506 }
8507
8508 static void kbytes2str(__u64 num, char *buf, int buflen, bool h)
8509 {
8510         if (!h) {
8511                 snprintf(buf, buflen, "%ju", (uintmax_t)num);
8512         } else {
8513                 if (num >> 40)
8514                         snprintf(buf, buflen, "%5.4gP",
8515                                  (double)num / ((__u64)1 << 40));
8516                 else if (num >> 30)
8517                         snprintf(buf, buflen, "%5.4gT",
8518                                  (double)num / (1 << 30));
8519                 else if (num >> 20)
8520                         snprintf(buf, buflen, "%5.4gG",
8521                                  (double)num / (1 << 20));
8522                 else if (num >> 10)
8523                         snprintf(buf, buflen, "%5.4gM",
8524                                  (double)num / (1 << 10));
8525                 else
8526                         snprintf(buf, buflen, "%ju%s", (uintmax_t)num, "k");
8527         }
8528 }
8529
8530 #ifdef HAVE_NATIVE_CLIENT
8531 /* In the current Lustre implementation, the grace time is either the time
8532  * or the timestamp to be used after some quota ID exceeds the soft limt,
8533  * 48 bits should be enough, its high 16 bits can be used as quota flags.
8534  */
8535 #define LQUOTA_GRACE_BITS       48
8536 #define LQUOTA_GRACE_MASK       ((1ULL << LQUOTA_GRACE_BITS) - 1)
8537 #define LQUOTA_GRACE_MAX        LQUOTA_GRACE_MASK
8538 #define LQUOTA_GRACE(t)         (t & LQUOTA_GRACE_MASK)
8539 #define LQUOTA_FLAG(t)          (t >> LQUOTA_GRACE_BITS)
8540 #define LQUOTA_GRACE_FLAG(t, f) ((__u64)t | (__u64)f << LQUOTA_GRACE_BITS)
8541 #endif
8542
8543 #define STRBUF_LEN      24
8544 static void print_quota(char *mnt, struct if_quotactl *qctl, int type,
8545                         int rc, bool h, bool show_default)
8546 {
8547         time_t now;
8548
8549         time(&now);
8550
8551         if (qctl->qc_cmd == LUSTRE_Q_GETQUOTA || qctl->qc_cmd == Q_GETOQUOTA ||
8552             qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL ||
8553             qctl->qc_cmd == LUSTRE_Q_GETDEFAULT ||
8554             qctl->qc_cmd == LUSTRE_Q_GETDEFAULT_POOL) {
8555                 int bover = 0, iover = 0;
8556                 struct obd_dqblk *dqb = &qctl->qc_dqblk;
8557                 char numbuf[3][STRBUF_LEN + 2]; /* 2 for brackets or wildcard */
8558                 char timebuf[40];
8559                 char strbuf[STRBUF_LEN];
8560
8561                 dqb->dqb_btime &= LQUOTA_GRACE_MASK;
8562                 dqb->dqb_itime &= LQUOTA_GRACE_MASK;
8563
8564                 if (dqb->dqb_bhardlimit &&
8565                     lustre_stoqb(dqb->dqb_curspace) >= dqb->dqb_bhardlimit) {
8566                         bover = 1;
8567                 } else if (dqb->dqb_bsoftlimit && dqb->dqb_btime) {
8568                         if (dqb->dqb_btime > now)
8569                                 bover = 2;
8570                         else
8571                                 bover = 3;
8572                 }
8573
8574                 if (dqb->dqb_ihardlimit &&
8575                     dqb->dqb_curinodes >= dqb->dqb_ihardlimit) {
8576                         iover = 1;
8577                 } else if (dqb->dqb_isoftlimit && dqb->dqb_itime) {
8578                         if (dqb->dqb_itime > now)
8579                                 iover = 2;
8580                         else
8581                                 iover = 3;
8582                 }
8583
8584                 if (strlen(mnt) > 15)
8585                         printf("%s\n%15s", mnt, "");
8586                 else
8587                         printf("%15s", mnt);
8588
8589                 if (show_default)
8590                         snprintf(timebuf, sizeof(timebuf), "%llu",
8591                                  (unsigned long long)dqb->dqb_btime);
8592                 else if (bover)
8593                         diff2str(dqb->dqb_btime, timebuf, now);
8594
8595                 kbytes2str(lustre_stoqb(dqb->dqb_curspace),
8596                            strbuf, sizeof(strbuf), h);
8597                 if (rc == -EREMOTEIO)
8598                         sprintf(numbuf[0], "%s*", strbuf);
8599                 else
8600                         sprintf(numbuf[0], (dqb->dqb_valid & QIF_SPACE) ?
8601                                 "%s" : "[%s]", strbuf);
8602
8603                 kbytes2str(dqb->dqb_bsoftlimit, strbuf, sizeof(strbuf), h);
8604                 if (type == QC_GENERAL)
8605                         sprintf(numbuf[1], (dqb->dqb_valid & QIF_BLIMITS) ?
8606                                 "%s" : "[%s]", strbuf);
8607                 else
8608                         sprintf(numbuf[1], "%s", "-");
8609
8610                 kbytes2str(dqb->dqb_bhardlimit, strbuf, sizeof(strbuf), h);
8611                 sprintf(numbuf[2], (dqb->dqb_valid & QIF_BLIMITS) ?
8612                         "%s" : "[%s]", strbuf);
8613
8614                 if (show_default)
8615                         printf(" %6s %7s %7s", numbuf[1], numbuf[2], timebuf);
8616                 else
8617                         printf(" %7s%c %6s %7s %7s",
8618                                numbuf[0], bover ? '*' : ' ', numbuf[1],
8619                                numbuf[2], bover > 1 ? timebuf : "-");
8620
8621                 if (show_default)
8622                         snprintf(timebuf, sizeof(timebuf), "%llu",
8623                                  (unsigned long long)dqb->dqb_itime);
8624                 else if (iover)
8625                         diff2str(dqb->dqb_itime, timebuf, now);
8626
8627                 snprintf(numbuf[0], sizeof(numbuf),
8628                          (dqb->dqb_valid & QIF_INODES) ? "%ju" : "[%ju]",
8629                          (uintmax_t)dqb->dqb_curinodes);
8630
8631                 if (type == QC_GENERAL)
8632                         sprintf(numbuf[1], (dqb->dqb_valid & QIF_ILIMITS) ?
8633                                 "%ju" : "[%ju]",
8634                                 (uintmax_t)dqb->dqb_isoftlimit);
8635                 else
8636                         sprintf(numbuf[1], "%s", "-");
8637
8638                 sprintf(numbuf[2], (dqb->dqb_valid & QIF_ILIMITS) ?
8639                         "%ju" : "[%ju]", (uintmax_t)dqb->dqb_ihardlimit);
8640
8641                 if (show_default)
8642                         printf(" %6s %7s %7s", numbuf[1], numbuf[2], timebuf);
8643                 else if (type != QC_OSTIDX)
8644                         printf(" %7s%c %6s %7s %7s",
8645                                numbuf[0], iover ? '*' : ' ', numbuf[1],
8646                                numbuf[2], iover > 1 ? timebuf : "-");
8647                 else
8648                         printf(" %7s %7s %7s %7s", "-", "-", "-", "-");
8649                 printf("\n");
8650         } else if (qctl->qc_cmd == LUSTRE_Q_GETINFO ||
8651                    qctl->qc_cmd == LUSTRE_Q_GETINFOPOOL ||
8652                    qctl->qc_cmd == Q_GETOINFO) {
8653                 char bgtimebuf[40];
8654                 char igtimebuf[40];
8655
8656                 if (qctl->qc_dqinfo.dqi_bgrace == NOTIFY_GRACE_TIME)
8657                         strncpy(bgtimebuf, NOTIFY_GRACE, 40);
8658                 else
8659                         sec2str(qctl->qc_dqinfo.dqi_bgrace, bgtimebuf, rc);
8660                 if (qctl->qc_dqinfo.dqi_igrace == NOTIFY_GRACE_TIME)
8661                         strncpy(igtimebuf, NOTIFY_GRACE, 40);
8662                 else
8663                         sec2str(qctl->qc_dqinfo.dqi_igrace, igtimebuf, rc);
8664
8665                 printf("Block grace time: %s; Inode grace time: %s\n",
8666                        bgtimebuf, igtimebuf);
8667         }
8668 }
8669
8670 static int tgt_name2index(const char *tgtname, unsigned int *idx)
8671 {
8672         char *dash, *endp;
8673
8674         /* format is "lustre-OST0001" */
8675         dash = memchr(tgtname, '-', LUSTRE_MAXFSNAME + 1);
8676         if (!dash) {
8677                 fprintf(stderr, "wrong tgtname format '%s'\n", tgtname);
8678                 return -EINVAL;
8679         }
8680         dash += 4;
8681
8682         *idx = strtoul(dash, &endp, 16);
8683         if (*idx > 0xffff) {
8684                 fprintf(stderr, "wrong index %s\n", tgtname);
8685                 return -ERANGE;
8686         }
8687
8688         return 0;
8689 }
8690
8691 static int print_obd_quota(char *mnt, struct if_quotactl *qctl, int is_mdt,
8692                            bool h, __u64 *total)
8693 {
8694         int rc = 0, rc1 = 0, count = 0, i = 0;
8695         char **list = NULL, *buffer = NULL;
8696         __u32 valid = qctl->qc_valid;
8697
8698         if (qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL && is_mdt)
8699                 return 0;
8700
8701         /* Is it correct for the case OST0000, OST0002, OST0003 -
8702          * we will ask OST0001 that is absent and won't ask OST0003? */
8703         rc = llapi_get_obd_count(mnt, &count, is_mdt);
8704         if (rc) {
8705                 fprintf(stderr, "can not get %s count: %s\n",
8706                         is_mdt ? "mdt" : "ost", strerror(-rc));
8707                 return rc;
8708         }
8709
8710         if (qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL) {
8711                 char fname[PATH_MAX];
8712                 char fsname[LUSTRE_MAXFSNAME + 1];
8713                 int bufsize = sizeof(struct obd_uuid) * count;
8714
8715                 rc = llapi_search_fsname(mnt, fsname);
8716                 if (rc) {
8717                         fprintf(stderr, "cannot get fsname for mountpoint %s\n",
8718                                 mnt);
8719                         goto out;
8720                 }
8721                 buffer = malloc(bufsize + sizeof(*list) * count);
8722                 if (!buffer)
8723                         return -ENOMEM;
8724                 list = (char **)(buffer + bufsize);
8725                 snprintf(fname, PATH_MAX, "%s.%s", fsname, qctl->qc_poolname);
8726                 count = llapi_get_poolmembers(fname, list, count,
8727                                               buffer, bufsize);
8728                 if (count <= 0)
8729                         goto out;
8730         }
8731
8732         for (i = 0; i < count; i++) {
8733                 if (qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL) {
8734                         unsigned int index;
8735
8736                         if (tgt_name2index(list[i], &index))
8737                                 continue;
8738                         qctl->qc_idx = index;
8739                 } else {
8740                         qctl->qc_idx = i;
8741                 }
8742
8743                 qctl->qc_valid = is_mdt ? QC_MDTIDX : QC_OSTIDX;
8744                 rc = llapi_quotactl(mnt, qctl);
8745                 if (rc) {
8746                         /* It is remote client case. */
8747                         if (rc == -EOPNOTSUPP) {
8748                                 rc = 0;
8749                                 goto out;
8750                         }
8751
8752                         /* no target for this index yet */
8753                         if (rc == -ENODEV) {
8754                                 rc = 0;
8755                                 continue;
8756                         }
8757
8758                         /* inactive target */
8759                         if (rc == -ENODATA) {
8760                                 char name[UUID_MAX+8];
8761
8762                                 snprintf(name, sizeof(name), "%s[inact]",
8763                                         obd_uuid2str(&qctl->obd_uuid));
8764                                 memset(&qctl->qc_dqinfo, 0,
8765                                        sizeof(qctl->qc_dqinfo));
8766                                 memset(&qctl->qc_dqblk, 0,
8767                                        sizeof(qctl->qc_dqblk));
8768                                 print_quota(name, qctl, qctl->qc_valid, 0, h,
8769                                             false);
8770                                 rc = 0;
8771                                 continue;
8772                         }
8773
8774                         if (!rc1)
8775                                 rc1 = rc;
8776                         fprintf(stderr, "quotactl %s%d failed.\n",
8777                                 is_mdt ? "mdt" : "ost", qctl->qc_idx);
8778                         continue;
8779                 }
8780
8781                 print_quota(obd_uuid2str(&qctl->obd_uuid), qctl,
8782                             qctl->qc_valid, 0, h, false);
8783                 *total += is_mdt ? qctl->qc_dqblk.dqb_ihardlimit :
8784                                    qctl->qc_dqblk.dqb_bhardlimit;
8785         }
8786 out:
8787         if (buffer)
8788                 free(buffer);
8789         qctl->qc_valid = valid;
8790         return rc ? : rc1;
8791 }
8792
8793 static int get_print_quota(char *mnt, char *name, struct if_quotactl *qctl,
8794                            int verbose, int quiet, bool human_readable,
8795                            bool show_default)
8796 {
8797         int rc1 = 0, rc2 = 0, rc3 = 0;
8798         char *obd_type = (char *)qctl->obd_type;
8799         char *obd_uuid = (char *)qctl->obd_uuid.uuid;
8800         __u64 total_ialloc = 0, total_balloc = 0;
8801         bool use_default_for_blk = false;
8802         bool use_default_for_file = false;
8803         int inacc;
8804
8805         rc1 = llapi_quotactl(mnt, qctl);
8806         if (rc1 < 0) {
8807                 switch (rc1) {
8808                 case -ESRCH:
8809                         fprintf(stderr, "%s quotas are not enabled.\n",
8810                                 qtype_name(qctl->qc_type));
8811                         goto out;
8812                 case -EPERM:
8813                         fprintf(stderr, "Permission denied.\n");
8814                 case -ENODEV:
8815                 case -ENOENT:
8816                         /* We already got error message. */
8817                         goto out;
8818                 default:
8819                         fprintf(stderr, "Unexpected quotactl error: %s\n",
8820                                 strerror(-rc1));
8821                 }
8822         }
8823
8824         if (!show_default && qctl->qc_id == 0) {
8825                 qctl->qc_dqblk.dqb_bhardlimit = 0;
8826                 qctl->qc_dqblk.dqb_bsoftlimit = 0;
8827                 qctl->qc_dqblk.dqb_ihardlimit = 0;
8828                 qctl->qc_dqblk.dqb_isoftlimit = 0;
8829                 qctl->qc_dqblk.dqb_btime = 0;
8830                 qctl->qc_dqblk.dqb_itime = 0;
8831                 qctl->qc_dqblk.dqb_valid |= QIF_LIMITS | QIF_TIMES;
8832         }
8833
8834         if (qctl->qc_dqblk.dqb_valid & QIF_BTIME &&
8835             LQUOTA_FLAG(qctl->qc_dqblk.dqb_btime) & LQUOTA_FLAG_DEFAULT) {
8836                 use_default_for_blk = true;
8837                 qctl->qc_dqblk.dqb_btime &= LQUOTA_GRACE_MASK;
8838         }
8839
8840         if (qctl->qc_dqblk.dqb_valid & QIF_ITIME &&
8841             LQUOTA_FLAG(qctl->qc_dqblk.dqb_itime) & LQUOTA_FLAG_DEFAULT) {
8842                 use_default_for_file = true;
8843                 qctl->qc_dqblk.dqb_itime &= LQUOTA_GRACE_MASK;
8844         }
8845
8846         if ((qctl->qc_cmd == LUSTRE_Q_GETQUOTA ||
8847              qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL ||
8848              qctl->qc_cmd == LUSTRE_Q_GETDEFAULT_POOL ||
8849              qctl->qc_cmd == LUSTRE_Q_GETDEFAULT) && !quiet)
8850                 print_quota_title(name, qctl, human_readable, show_default);
8851
8852         if (rc1 && *obd_type)
8853                 fprintf(stderr, "%s %s ", obd_type, obd_uuid);
8854
8855         if (qctl->qc_valid != QC_GENERAL)
8856                 mnt = "";
8857
8858         inacc = (qctl->qc_cmd == LUSTRE_Q_GETQUOTA ||
8859                  qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL) &&
8860                 ((qctl->qc_dqblk.dqb_valid & (QIF_LIMITS|QIF_USAGE)) !=
8861                  (QIF_LIMITS|QIF_USAGE));
8862
8863         print_quota(mnt, qctl, QC_GENERAL, rc1, human_readable, show_default);
8864
8865         if (!show_default && verbose &&
8866             qctl->qc_valid == QC_GENERAL && qctl->qc_cmd != LUSTRE_Q_GETINFO &&
8867             qctl->qc_cmd != LUSTRE_Q_GETINFOPOOL) {
8868                 char strbuf[STRBUF_LEN];
8869
8870                 rc2 = print_obd_quota(mnt, qctl, 1, human_readable,
8871                                       &total_ialloc);
8872                 rc3 = print_obd_quota(mnt, qctl, 0, human_readable,
8873                                       &total_balloc);
8874                 kbytes2str(total_balloc, strbuf, sizeof(strbuf),
8875                            human_readable);
8876                 printf("Total allocated inode limit: %ju, total allocated block limit: %s\n",
8877                        (uintmax_t)total_ialloc, strbuf);
8878         }
8879
8880         if (use_default_for_blk)
8881                 printf("%cid %u is using default block quota setting\n",
8882                        *qtype_name(qctl->qc_type), qctl->qc_id);
8883
8884         if (use_default_for_file)
8885                 printf("%cid %u is using default file quota setting\n",
8886                        *qtype_name(qctl->qc_type), qctl->qc_id);
8887
8888         if (rc1 || rc2 || rc3 || inacc)
8889                 printf("Some errors happened when getting quota info. Some devices may be not working or deactivated. The data in \"[]\" is inaccurate.\n");
8890 out:
8891         if (rc1)
8892                 return rc1;
8893         if (rc2)
8894                 return rc2;
8895         if (rc3)
8896                 return rc3;
8897         if (inacc)
8898                 return -EIO;
8899
8900         return 0;
8901 }
8902
8903 static int lfs_project(int argc, char **argv)
8904 {
8905         int ret = 0, err = 0, c, i;
8906         struct project_handle_control phc = { 0 };
8907         enum lfs_project_ops_t op;
8908
8909         phc.newline = true;
8910         phc.assign_projid = false;
8911         /* default action */
8912         op = LFS_PROJECT_LIST;
8913
8914         while ((c = getopt(argc, argv, "p:cCsdkr0")) != -1) {
8915                 switch (c) {
8916                 case 'c':
8917                         if (op != LFS_PROJECT_LIST) {
8918                                 fprintf(stderr,
8919                                         "%s: cannot specify '-c' '-C' '-s' together\n",
8920                                         progname);
8921                                 return CMD_HELP;
8922                         }
8923
8924                         op = LFS_PROJECT_CHECK;
8925                         break;
8926                 case 'C':
8927                         if (op != LFS_PROJECT_LIST) {
8928                                 fprintf(stderr,
8929                                         "%s: cannot specify '-c' '-C' '-s' together\n",
8930                                         progname);
8931                                 return CMD_HELP;
8932                         }
8933
8934                         op = LFS_PROJECT_CLEAR;
8935                         break;
8936                 case 's':
8937                         if (op != LFS_PROJECT_LIST) {
8938                                 fprintf(stderr,
8939                                         "%s: cannot specify '-c' '-C' '-s' together\n",
8940                                         progname);
8941                                 return CMD_HELP;
8942                         }
8943
8944                         phc.set_inherit = true;
8945                         op = LFS_PROJECT_SET;
8946                         break;
8947                 case 'd':
8948                         phc.dironly = true;
8949                         break;
8950                 case 'k':
8951                         phc.keep_projid = true;
8952                         break;
8953                 case 'r':
8954                         phc.recursive = true;
8955                         break;
8956                 case 'p':
8957                         if (str2quotaid(&phc.projid, optarg)) {
8958                                 fprintf(stderr,
8959                                         "Invalid project ID: %s\n",
8960                                         optarg);
8961                                 return CMD_HELP;
8962                         }
8963
8964                         phc.assign_projid = true;
8965
8966                         break;
8967                 case '0':
8968                         phc.newline = false;
8969                         break;
8970                 default:
8971                         fprintf(stderr, "%s: invalid option '%c'\n",
8972                                 progname, optopt);
8973                         return CMD_HELP;
8974                 }
8975         }
8976
8977         if (phc.assign_projid && op == LFS_PROJECT_LIST) {
8978                 op = LFS_PROJECT_SET;
8979                 phc.set_projid = true;
8980         } else if (phc.assign_projid && op == LFS_PROJECT_SET) {
8981                 phc.set_projid = true;
8982         }
8983
8984         switch (op) {
8985         case LFS_PROJECT_CHECK:
8986                 if (phc.keep_projid) {
8987                         fprintf(stderr,
8988                                 "%s: '-k' is useless together with '-c'\n",
8989                                 progname);
8990                         return CMD_HELP;
8991                 }
8992                 break;
8993         case LFS_PROJECT_CLEAR:
8994                 if (!phc.newline) {
8995                         fprintf(stderr,
8996                                 "%s: '-0' is useless together with '-C'\n",
8997                                 progname);
8998                         return CMD_HELP;
8999                 }
9000                 if (phc.assign_projid) {
9001                         fprintf(stderr,
9002                                 "%s: '-p' is useless together with '-C'\n",
9003                                 progname);
9004                         return CMD_HELP;
9005                 }
9006                 break;
9007         case LFS_PROJECT_SET:
9008                 if (!phc.newline) {
9009                         fprintf(stderr,
9010                                 "%s: '-0' is useless together with '-s'\n",
9011                                 progname);
9012                         return CMD_HELP;
9013                 }
9014                 if (phc.keep_projid) {
9015                         fprintf(stderr,
9016                                 "%s: '-k' is useless together with '-s'\n",
9017                                 progname);
9018                         return CMD_HELP;
9019                 }
9020                 break;
9021         default:
9022                 if (!phc.newline) {
9023                         fprintf(stderr,
9024                                 "%s: '-0' is useless for list operations\n",
9025                                 progname);
9026                         return CMD_HELP;
9027                 }
9028                 break;
9029         }
9030
9031         argv += optind;
9032         argc -= optind;
9033         if (argc == 0) {
9034                 fprintf(stderr, "%s: missing file or directory target(s)\n",
9035                         progname);
9036                 return CMD_HELP;
9037         }
9038
9039         for (i = 0; i < argc; i++) {
9040                 switch (op) {
9041                 case LFS_PROJECT_CHECK:
9042                         err = lfs_project_check(argv[i], &phc);
9043                         break;
9044                 case LFS_PROJECT_LIST:
9045                         err = lfs_project_list(argv[i], &phc);
9046                         break;
9047                 case LFS_PROJECT_CLEAR:
9048                         err = lfs_project_clear(argv[i], &phc);
9049                         break;
9050                 case LFS_PROJECT_SET:
9051                         err = lfs_project_set(argv[i], &phc);
9052                         break;
9053                 default:
9054                         break;
9055                 }
9056                 if (err && !ret)
9057                         ret = err;
9058         }
9059
9060         return ret;
9061 }
9062
9063 static int lfs_quota(int argc, char **argv)
9064 {
9065         int c;
9066         char *mnt, *name = NULL;
9067         struct if_quotactl *qctl;
9068         char *obd_uuid;
9069         int rc = 0, rc1 = 0, verbose = 0, quiet = 0;
9070         __u32 valid = QC_GENERAL, idx = 0;
9071         bool human_readable = false;
9072         bool show_default = false;
9073         int qtype;
9074         bool show_pools = false;
9075         struct option long_opts[] = {
9076         { .val = LFS_POOL_OPT, .name = "pool", .has_arg = optional_argument },
9077         { .name = NULL } };
9078         char **poollist = NULL;
9079         char *buf = NULL;
9080         int poolcount, i;
9081
9082         qctl = calloc(1, sizeof(*qctl) + LOV_MAXPOOLNAME + 1);
9083         if (!qctl)
9084                 return -ENOMEM;
9085
9086         qctl->qc_cmd = LUSTRE_Q_GETQUOTA;
9087         qctl->qc_type = ALLQUOTA;
9088         obd_uuid = (char *)qctl->obd_uuid.uuid;
9089
9090         while ((c = getopt_long(argc, argv, "gGi:I:o:pPqtuUvh",
9091                 long_opts, NULL)) != -1) {
9092                 switch (c) {
9093                 case 'U':
9094                         show_default = true;
9095                 case 'u':
9096                         qtype = USRQUOTA;
9097                         goto quota_type;
9098                 case 'G':
9099                         show_default = true;
9100                 case 'g':
9101                         qtype = GRPQUOTA;
9102                         goto quota_type;
9103                 case 'P':
9104                         show_default = true;
9105                 case 'p':
9106                         qtype = PRJQUOTA;
9107 quota_type:
9108                         if (qctl->qc_type != ALLQUOTA) {
9109                                 fprintf(stderr,
9110                                         "%s quota: only one of -u, -g, or -p may be specified\n",
9111                                         progname);
9112                                 rc = CMD_HELP;
9113                                 goto out;
9114                         }
9115                         qctl->qc_type = qtype;
9116                         break;
9117                 case 't':
9118                         qctl->qc_cmd = LUSTRE_Q_GETINFO;
9119                         break;
9120                 case 'o':
9121                         valid = qctl->qc_valid = QC_UUID;
9122                         snprintf(obd_uuid, sizeof(*obd_uuid), "%s", optarg);
9123                         break;
9124                 case 'i':
9125                         valid = qctl->qc_valid = QC_MDTIDX;
9126                         idx = qctl->qc_idx = atoi(optarg);
9127                         if (idx == 0 && *optarg != '0') {
9128                                 fprintf(stderr,
9129                                         "%s quota: invalid MDT index '%s'\n",
9130                                         progname, optarg);
9131                                 rc = CMD_HELP;
9132                                 goto out;
9133                         }
9134                         break;
9135                 case 'I':
9136                         valid = qctl->qc_valid = QC_OSTIDX;
9137                         idx = qctl->qc_idx = atoi(optarg);
9138                         if (idx == 0 && *optarg != '0') {
9139                                 fprintf(stderr,
9140                                         "%s quota: invalid OST index '%s'\n",
9141                                         progname, optarg);
9142                                 rc = CMD_HELP;
9143                                 goto out;
9144                         }
9145                         break;
9146                 case 'v':
9147                         verbose = 1;
9148                         break;
9149                 case 'q':
9150                         quiet = 1;
9151                         break;
9152                 case 'h':
9153                         human_readable = true;
9154                         break;
9155                 case LFS_POOL_OPT:
9156                         if ((!optarg) && (argv[optind] != NULL) &&
9157                                 (argv[optind][0] != '-') &&
9158                                 (argv[optind][0] != '/')) {
9159                                 optarg = argv[optind++];
9160                                 if (lfs_verify_poolarg(optarg)) {
9161                                         rc = -EINVAL;
9162                                         goto out;
9163                                 }
9164                                 strncpy(qctl->qc_poolname, optarg,
9165                                         LOV_MAXPOOLNAME);
9166                                 if (qctl->qc_cmd == LUSTRE_Q_GETINFO)
9167                                         qctl->qc_cmd = LUSTRE_Q_GETINFOPOOL;
9168                                 else
9169                                         qctl->qc_cmd = LUSTRE_Q_GETQUOTAPOOL;
9170                                 break;
9171                         }
9172
9173                         /* optarg is NULL */
9174                         show_pools = true;
9175                         qctl->qc_cmd = LUSTRE_Q_GETQUOTAPOOL;
9176                         break;
9177                 default:
9178                         fprintf(stderr, "%s quota: unrecognized option '%s'\n",
9179                                 progname, argv[optind - 1]);
9180                         rc = CMD_HELP;
9181                         goto out;
9182                 }
9183         }
9184
9185         /* current uid/gid info for "lfs quota /path/to/lustre/mount" */
9186         if ((qctl->qc_cmd == LUSTRE_Q_GETQUOTA ||
9187              qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL) &&
9188              qctl->qc_type == ALLQUOTA &&
9189              optind == argc - 1 && !show_default) {
9190                 qctl->qc_idx = idx;
9191
9192                 for (qtype = USRQUOTA; qtype <= GRPQUOTA; qtype++) {
9193                         qctl->qc_type = qtype;
9194                         qctl->qc_valid = valid;
9195                         if (qtype == USRQUOTA) {
9196                                 qctl->qc_id = geteuid();
9197                                 rc = uid2name(&name, qctl->qc_id);
9198                         } else {
9199                                 qctl->qc_id = getegid();
9200                                 rc = gid2name(&name, qctl->qc_id);
9201                                 memset(&qctl->qc_dqblk, 0,
9202                                        sizeof(qctl->qc_dqblk));
9203                         }
9204                         if (rc)
9205                                 name = "<unknown>";
9206                         mnt = argv[optind];
9207                         rc1 = get_print_quota(mnt, name, qctl, verbose, quiet,
9208                                               human_readable, show_default);
9209                         if (rc1 && !rc)
9210                                 rc = rc1;
9211                 }
9212                 goto out;
9213         /* lfs quota -u username /path/to/lustre/mount */
9214         } else if (qctl->qc_cmd == LUSTRE_Q_GETQUOTA ||
9215                    qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL) {
9216                 /* options should be followed by u/g-name and mntpoint */
9217                 if ((!show_default && optind + 2 != argc) ||
9218                     (show_default && optind + 1 != argc) ||
9219                     qctl->qc_type == ALLQUOTA) {
9220                         fprintf(stderr,
9221                                 "%s quota: name and mount point must be specified\n",
9222                                 progname);
9223                         rc = CMD_HELP;
9224                         goto out;
9225                 }
9226
9227                 if (!show_default) {
9228                         name = argv[optind++];
9229                         switch (qctl->qc_type) {
9230                         case USRQUOTA:
9231                                 rc = name2uid(&qctl->qc_id, name);
9232                                 break;
9233                         case GRPQUOTA:
9234                                 rc = name2gid(&qctl->qc_id, name);
9235                                 break;
9236                         case PRJQUOTA:
9237                                 rc = name2projid(&qctl->qc_id, name);
9238                                 break;
9239                         default:
9240                                 rc = -ENOTSUP;
9241                                 break;
9242                         }
9243                 } else {
9244                         qctl->qc_valid = QC_GENERAL;
9245                         qctl->qc_cmd = qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL ?
9246                                         LUSTRE_Q_GETDEFAULT_POOL :
9247                                         LUSTRE_Q_GETDEFAULT;
9248                         qctl->qc_id = 0;
9249                 }
9250
9251                 if (rc) {
9252                         if (str2quotaid(&qctl->qc_id, name)) {
9253                                 fprintf(stderr, "%s quota: invalid id '%s'\n",
9254                                         progname, name);
9255                                 rc = CMD_HELP;
9256                                 goto out;
9257                         }
9258                 }
9259         } else if (optind + 1 != argc || qctl->qc_type == ALLQUOTA) {
9260                 fprintf(stderr, "%s quota: missing quota info argument(s)\n",
9261                         progname);
9262                 rc = CMD_HELP;
9263                 goto out;
9264         }
9265
9266         mnt = argv[optind];
9267         if (show_pools) {
9268                 char *p;
9269
9270                 i = 0;
9271                 rc = llapi_get_poolbuf(mnt, &buf, &poollist, &poolcount);
9272                 if (rc)
9273                         goto out;
9274
9275                 for (i = 0; i < poolcount; i++) {
9276                         p = memchr(poollist[i], '.', MAXNAMLEN);
9277                         if (!p) {
9278                                 fprintf(stderr, "bad string format %.*s\n",
9279                                         MAXNAMLEN, poollist[i]);
9280                                 rc = -EINVAL;
9281                                 goto out;
9282                         }
9283                         p++;
9284                         printf("Quotas for pool: %s\n", p);
9285                         strncpy(qctl->qc_poolname, p, LOV_MAXPOOLNAME);
9286                         rc = get_print_quota(mnt, name, qctl, verbose, quiet,
9287                                              human_readable, show_default);
9288                         if (rc)
9289                                 break;
9290                 }
9291                 goto out;
9292         }
9293
9294         rc = get_print_quota(mnt, name, qctl, verbose, quiet,
9295                              human_readable, show_default);
9296 out:
9297         free(buf);
9298         free(qctl);
9299         return rc;
9300 }
9301 #endif /* HAVE_SYS_QUOTA_H! */
9302
9303 static int flushctx_ioctl(char *mp)
9304 {
9305         int fd, rc;
9306
9307         fd = open(mp, O_RDONLY);
9308         if (fd == -1) {
9309                 fprintf(stderr, "flushctx: error open %s: %s\n",
9310                         mp, strerror(errno));
9311                 return -1;
9312         }
9313
9314         rc = ioctl(fd, LL_IOC_FLUSHCTX);
9315         if (rc == -1)
9316                 fprintf(stderr, "flushctx: error ioctl %s: %s\n",
9317                         mp, strerror(errno));
9318
9319         close(fd);
9320         return rc;
9321 }
9322
9323 static int lfs_flushctx(int argc, char **argv)
9324 {
9325         int     kdestroy = 0, reap = 0, c;
9326         char    mntdir[PATH_MAX] = {'\0'};
9327         int     index = 0;
9328         int     rc = 0;
9329
9330         while ((c = getopt(argc, argv, "kr")) != -1) {
9331                 switch (c) {
9332                 case 'k':
9333                         kdestroy = 1;
9334                         break;
9335                 case 'r':
9336                         reap = 1;
9337                         break;
9338                 default:
9339                         fprintf(stderr,
9340                                 "error: %s: option '-%c' unrecognized\n",
9341                                 argv[0], c);
9342                         return CMD_HELP;
9343                 }
9344         }
9345
9346         if (kdestroy) {
9347                 rc = system("kdestroy > /dev/null");
9348                 if (rc) {
9349                         rc = WEXITSTATUS(rc);
9350                         fprintf(stderr,
9351                                 "error destroying tickets: %d, continuing\n",
9352                                 rc);
9353                 }
9354         }
9355
9356         if (optind >= argc) {
9357                 /* flush for all mounted lustre fs. */
9358                 while (!llapi_search_mounts(NULL, index++, mntdir, NULL)) {
9359                         /* Check if we have a mount point */
9360                         if (mntdir[0] == '\0')
9361                                 continue;
9362
9363                         if (flushctx_ioctl(mntdir))
9364                                 rc = -1;
9365
9366                         mntdir[0] = '\0'; /* avoid matching in next loop */
9367                 }
9368         } else {
9369                 /* flush fs as specified */
9370                 while (optind < argc) {
9371                         if (flushctx_ioctl(argv[optind++]))
9372                                 rc = -1;
9373                 }
9374         }
9375
9376         if (reap) {
9377                 rc = system("keyctl reap > /dev/null");
9378                 if (rc != 0) {
9379                         rc = WEXITSTATUS(rc);
9380                         fprintf(stderr, "error reaping keyring: %d\n", rc);
9381                 }
9382         }
9383
9384         return rc;
9385 }
9386
9387 static int lfs_changelog(int argc, char **argv)
9388 {
9389         void *changelog_priv;
9390         struct changelog_rec *rec;
9391         long long startrec = 0, endrec = 0;
9392         char *mdd;
9393         struct option long_opts[] = {
9394                 { .val = 'f', .name = "follow", .has_arg = no_argument },
9395                 { .name = NULL } };
9396         char short_opts[] = "f";
9397         int rc, follow = 0;
9398
9399         while ((rc = getopt_long(argc, argv, short_opts,
9400                 long_opts, NULL)) != -1) {
9401                 switch (rc) {
9402                 case 'f':
9403                         follow++;
9404                         break;
9405                 default:
9406                         fprintf(stderr,
9407                                 "%s changelog: unrecognized option '%s'\n",
9408                                 progname, argv[optind - 1]);
9409                         return CMD_HELP;
9410                 }
9411         }
9412         if (optind >= argc) {
9413                 fprintf(stderr, "%s changelog: mdtname must be specified\n",
9414                         progname);
9415                 return CMD_HELP;
9416         }
9417
9418         mdd = argv[optind++];
9419         if (argc > optind) {
9420                 errno = 0;
9421                 startrec = strtoll(argv[optind++], NULL, 10);
9422                 if (errno != 0 || startrec < 0) {
9423                         fprintf(stderr,
9424                                 "%s changelog: bad startrec\n",
9425                                 progname);
9426                         return CMD_HELP;
9427                 }
9428         }
9429
9430         if (argc > optind) {
9431                 errno = 0;
9432                 endrec = strtoll(argv[optind++], NULL, 10);
9433                 if (errno != 0 || endrec < 0) {
9434                         fprintf(stderr,
9435                                 "%s changelog: bad endrec\n",
9436                                 progname);
9437                         return CMD_HELP;
9438                 }
9439         }
9440
9441         rc = llapi_changelog_start(&changelog_priv,
9442                                    CHANGELOG_FLAG_BLOCK |
9443                                    CHANGELOG_FLAG_JOBID |
9444                                    CHANGELOG_FLAG_EXTRA_FLAGS |
9445                                    (follow ? CHANGELOG_FLAG_FOLLOW : 0),
9446                                    mdd, startrec);
9447         if (rc < 0) {
9448                 fprintf(stderr, "%s changelog: cannot start changelog: %s\n",
9449                         progname, strerror(errno = -rc));
9450                 return rc;
9451         }
9452
9453         rc = llapi_changelog_set_xflags(changelog_priv,
9454                                         CHANGELOG_EXTRA_FLAG_UIDGID |
9455                                         CHANGELOG_EXTRA_FLAG_NID |
9456                                         CHANGELOG_EXTRA_FLAG_OMODE |
9457                                         CHANGELOG_EXTRA_FLAG_XATTR);
9458         if (rc < 0) {
9459                 fprintf(stderr,
9460                         "%s changelog: cannot set xflags for changelog: %s\n",
9461                         progname, strerror(errno = -rc));
9462                 return rc;
9463         }
9464
9465         while ((rc = llapi_changelog_recv(changelog_priv, &rec)) == 0) {
9466                 time_t secs;
9467                 struct tm ts;
9468
9469                 if (endrec && rec->cr_index > endrec) {
9470                         llapi_changelog_free(&rec);
9471                         break;
9472                 }
9473                 if (rec->cr_index < startrec) {
9474                         llapi_changelog_free(&rec);
9475                         continue;
9476                 }
9477
9478                 secs = rec->cr_time >> 30;
9479                 gmtime_r(&secs, &ts);
9480                 printf("%ju %02d%-5s %02d:%02d:%02d.%09d %04d.%02d.%02d "
9481                        "0x%x t="DFID, (uintmax_t)rec->cr_index, rec->cr_type,
9482                        changelog_type2str(rec->cr_type),
9483                        ts.tm_hour, ts.tm_min, ts.tm_sec,
9484                        (int)(rec->cr_time & ((1 << 30) - 1)),
9485                        ts.tm_year + 1900, ts.tm_mon + 1, ts.tm_mday,
9486                        rec->cr_flags & CLF_FLAGMASK, PFID(&rec->cr_tfid));
9487
9488                 if (rec->cr_flags & CLF_JOBID) {
9489                         struct changelog_ext_jobid *jid =
9490                                 changelog_rec_jobid(rec);
9491
9492                         if (jid->cr_jobid[0] != '\0')
9493                                 printf(" j=%s", jid->cr_jobid);
9494                 }
9495
9496                 if (rec->cr_flags & CLF_EXTRA_FLAGS) {
9497                         struct changelog_ext_extra_flags *ef =
9498                                 changelog_rec_extra_flags(rec);
9499
9500                         printf(" ef=0x%llx",
9501                                (unsigned long long)ef->cr_extra_flags);
9502
9503                         if (ef->cr_extra_flags & CLFE_UIDGID) {
9504                                 struct changelog_ext_uidgid *uidgid =
9505                                         changelog_rec_uidgid(rec);
9506
9507                                 printf(" u=%llu:%llu",
9508                                        (unsigned long long)uidgid->cr_uid,
9509                                        (unsigned long long)uidgid->cr_gid);
9510                         }
9511                         if (ef->cr_extra_flags & CLFE_NID) {
9512                                 struct changelog_ext_nid *nid =
9513                                         changelog_rec_nid(rec);
9514
9515                                 printf(" nid=%s",
9516                                        libcfs_nid2str(nid->cr_nid));
9517                         }
9518
9519                         if (ef->cr_extra_flags & CLFE_OPEN) {
9520                                 struct changelog_ext_openmode *omd =
9521                                         changelog_rec_openmode(rec);
9522                                 char mode[] = "---";
9523
9524                                 /* exec mode must be exclusive */
9525                                 if (omd->cr_openflags & MDS_FMODE_EXEC) {
9526                                         mode[2] = 'x';
9527                                 } else {
9528                                         if (omd->cr_openflags & MDS_FMODE_READ)
9529                                                 mode[0] = 'r';
9530                                         if (omd->cr_openflags &
9531                                             (MDS_FMODE_WRITE |
9532                                              MDS_OPEN_TRUNC |
9533                                              MDS_OPEN_APPEND))
9534                                                 mode[1] = 'w';
9535                                 }
9536
9537                                 if (strcmp(mode, "---") != 0)
9538                                         printf(" m=%s", mode);
9539                         }
9540
9541                         if (ef->cr_extra_flags & CLFE_XATTR) {
9542                                 struct changelog_ext_xattr *xattr =
9543                                         changelog_rec_xattr(rec);
9544
9545                                 if (xattr->cr_xattr[0] != '\0')
9546                                         printf(" x=%s", xattr->cr_xattr);
9547                         }
9548                 }
9549
9550                 if (!fid_is_zero(&rec->cr_pfid))
9551                         printf(" p="DFID, PFID(&rec->cr_pfid));
9552                 if (rec->cr_namelen)
9553                         printf(" %.*s", rec->cr_namelen,
9554                                changelog_rec_name(rec));
9555
9556                 if (rec->cr_flags & CLF_RENAME) {
9557                         struct changelog_ext_rename *rnm =
9558                                 changelog_rec_rename(rec);
9559
9560                         if (!fid_is_zero(&rnm->cr_sfid))
9561                                 printf(" s="DFID" sp="DFID" %.*s",
9562                                        PFID(&rnm->cr_sfid),
9563                                        PFID(&rnm->cr_spfid),
9564                                        (int)changelog_rec_snamelen(rec),
9565                                        changelog_rec_sname(rec));
9566                 }
9567                 printf("\n");
9568
9569                 llapi_changelog_free(&rec);
9570         }
9571
9572         llapi_changelog_fini(&changelog_priv);
9573
9574         if (rc < 0)
9575                 fprintf(stderr, "%s changelog: cannot access changelog: %s\n",
9576                         progname, strerror(errno = -rc));
9577
9578         return (rc == 1 ? 0 : rc);
9579 }
9580
9581 static int lfs_changelog_clear(int argc, char **argv)
9582 {
9583         long long endrec;
9584         int rc;
9585
9586         if (argc != 4)
9587                 return CMD_HELP;
9588
9589         errno = 0;
9590         endrec = strtoll(argv[3], NULL, 10);
9591         if (errno != 0 || endrec < 0) {
9592                 fprintf(stderr,
9593                         "%s: bad endrec '%s'\n",
9594                         argv[0], argv[3]);
9595                 return CMD_HELP;
9596         }
9597
9598         rc = llapi_changelog_clear(argv[1], argv[2], endrec);
9599
9600         if (rc == -EINVAL)
9601                 fprintf(stderr, "%s: record out of range: %llu\n",
9602                         argv[0], endrec);
9603         else if (rc == -ENOENT)
9604                 fprintf(stderr, "%s: no changelog user: %s\n",
9605                         argv[0], argv[2]);
9606         else if (rc)
9607                 fprintf(stderr, "%s error: %s\n", argv[0],
9608                         strerror(-rc));
9609
9610         if (rc)
9611                 errno = -rc;
9612
9613         return rc;
9614 }
9615
9616 static void rstripc(char *str, int c)
9617 {
9618         char *end = str + strlen(str);
9619
9620         for (; str < end && end[-1] == c; --end)
9621                 end[-1] = '\0';
9622 }
9623
9624 static int lfs_fid2path(int argc, char **argv)
9625 {
9626         struct option long_opts[] = {
9627                 { .val = 'c',   .name = "cur",  .has_arg = no_argument },
9628                 { .val = 'c',   .name = "current",      .has_arg = no_argument },
9629                 { .val = 'c',   .name = "print-link",   .has_arg = no_argument },
9630                 { .val = 'f',   .name = "print-fid",    .has_arg = no_argument },
9631                 { .val = 'l',   .name = "link", .has_arg = required_argument },
9632                 { .name = NULL } };
9633         char short_opts[] = "cfl:pr:";
9634         bool print_link = false;
9635         bool print_fid = false;
9636         bool print_mnt_dir;
9637         char mnt_dir[PATH_MAX] = "";
9638         int mnt_fd = -1;
9639         char *path_or_fsname;
9640         long long recno = -1;
9641         int linkno = -1;
9642         char *endptr = NULL;
9643         int rc = 0;
9644         int c;
9645         int i;
9646
9647         while ((c = getopt_long(argc, argv, short_opts, long_opts, NULL)) != -1) {
9648                 switch (c) {
9649                 case 'c':
9650                         print_link = true;
9651                         break;
9652                 case 'f':
9653                         print_fid = true;
9654                         break;
9655                 case 'l':
9656                         errno = 0;
9657                         linkno = strtol(optarg, &endptr, 10);
9658                         if (errno != 0 || *endptr != '\0' || linkno < 0) {
9659                                 fprintf(stderr,
9660                                         "%s fid2path: invalid linkno '%s'\n",
9661                                         progname, optarg);
9662                                 return CMD_HELP;
9663                         }
9664                         break;
9665                 case 'r':
9666                         /* recno is something to do with changelogs
9667                          * that was never implemented. We just pass it
9668                          * through for the MDT to ignore.
9669                          */
9670                         errno = 0;
9671                         recno = strtoll(optarg, &endptr, 10);
9672                         if (errno != 0 || *endptr != '\0' || recno < 0) {
9673                                 fprintf(stderr,
9674                                         "%s fid2path: invalid recno '%s'\n",
9675                                         progname, optarg);
9676                                 return CMD_HELP;
9677                         }
9678                         break;
9679                 default:
9680                         fprintf(stderr,
9681                                 "%s fid2path: unrecognized option '%s'\n",
9682                                 progname, argv[optind - 1]);
9683                         return CMD_HELP;
9684                 }
9685         }
9686
9687         if (argc - optind < 2) {
9688                 fprintf(stderr,
9689                         "Usage: %s fid2path FSNAME|ROOT FID...\n",
9690                         progname);
9691                 return CMD_HELP;
9692         }
9693
9694         path_or_fsname = argv[optind];
9695
9696         if (*path_or_fsname == '/') {
9697                 print_mnt_dir = true;
9698                 rc = llapi_search_mounts(path_or_fsname, 0, mnt_dir, NULL);
9699         } else {
9700                 print_mnt_dir = false;
9701                 rc = llapi_search_rootpath(mnt_dir, path_or_fsname);
9702         }
9703
9704         if (rc < 0) {
9705                 fprintf(stderr,
9706                         "%s fid2path: cannot resolve mount point for '%s': %s\n",
9707                         progname, path_or_fsname, strerror(-rc));
9708                 goto out;
9709         }
9710
9711         mnt_fd = open(mnt_dir, O_RDONLY | O_DIRECTORY);
9712         if (mnt_fd < 0) {
9713                 fprintf(stderr,
9714                         "%s fid2path: cannot open mount point for '%s': %s\n",
9715                         progname, path_or_fsname, strerror(-rc));
9716                 goto out;
9717         }
9718
9719         /* Strip trailing slashes from mnt_dir. */
9720         rstripc(mnt_dir + 1, '/');
9721
9722         for (i = optind + 1; i < argc; i++) {
9723                 const char *fid_str = argv[i];
9724                 struct lu_fid fid;
9725                 int rc2;
9726
9727                 rc2 = llapi_fid_parse(fid_str, &fid, NULL);
9728                 if (rc2 < 0) {
9729                         fprintf(stderr,
9730                                 "%s fid2path: invalid FID '%s'\n",
9731                                 progname, fid_str);
9732                         if (rc == 0)
9733                                 rc = rc2;
9734
9735                         continue;
9736                 }
9737
9738                 int linktmp = (linkno >= 0) ? linkno : 0;
9739                 while (1) {
9740                         int oldtmp = linktmp;
9741                         long long rectmp = recno;
9742                         char path_buf[PATH_MAX];
9743
9744                         rc2 = llapi_fid2path_at(mnt_fd, &fid,
9745                                 path_buf, sizeof(path_buf), &rectmp, &linktmp);
9746                         if (rc2 < 0) {
9747                                 fprintf(stderr,
9748                                         "%s fid2path: cannot find %s %s: %s\n",
9749                                         progname, path_or_fsname, fid_str,
9750                                         strerror(-rc2));
9751                                 if (rc == 0)
9752                                         rc = rc2;
9753                                 break;
9754                         }
9755
9756                         if (print_fid)
9757                                 printf("%s ", fid_str);
9758
9759                         if (print_link)
9760                                 printf("%d ", linktmp);
9761
9762                         /* You may think this looks wrong or weird (and it is!)
9763                          * but we are actually trying to preserve the old quirky
9764                          * behaviors (enforced by our old quirky tests!) that
9765                          * make lfs so much fun to work on:
9766                          *
9767                          *   lustre 0x200000007:0x1:0x0 => "/"
9768                          *   /mnt/lustre 0x200000007:0x1:0x0 => "/mnt/lustre//"
9769                          *
9770                          * Note that llapi_fid2path() returns "" for the root
9771                          * FID. */
9772
9773                         printf("%s%s%s\n",
9774                                print_mnt_dir ? mnt_dir : "",
9775                                (print_mnt_dir || *path_buf == '\0') ? "/" : "",
9776                                path_buf);
9777
9778                         if (linkno >= 0)
9779                                 /* specified linkno */
9780                                 break;
9781
9782                         if (oldtmp == linktmp)
9783                                 /* no more links */
9784                                 break;
9785                 }
9786         }
9787 out:
9788         if (!(mnt_fd < 0))
9789                 close(mnt_fd);
9790
9791         return rc;
9792 }
9793
9794 static int lfs_path2fid(int argc, char **argv)
9795 {
9796         struct option long_opts[] = {
9797                 { .val = 'p', .name = "parents", .has_arg = no_argument },
9798                 { .name = NULL } };
9799         char            **path;
9800         const char        short_opts[] = "p";
9801         const char       *sep = "";
9802         struct lu_fid     fid;
9803         int               rc = 0;
9804         bool              show_parents = false;
9805
9806         while ((rc = getopt_long(argc, argv, short_opts,
9807                                  long_opts, NULL)) != -1) {
9808                 switch (rc) {
9809                 case 'p':
9810                         show_parents = true;
9811                         break;
9812                 default:
9813                         fprintf(stderr,
9814                                 "%s path2fid: unrecognized option '%s'\n",
9815                                 progname, argv[optind - 1]);
9816                         return CMD_HELP;
9817                 }
9818         }
9819
9820         if (optind > argc - 1) {
9821                 fprintf(stderr, "%s path2fid: FILE... must be specified\n",
9822                         progname);
9823                 return CMD_HELP;
9824         } else if (optind < argc - 1) {
9825                 sep = ": ";
9826         }
9827
9828         rc = 0;
9829         for (path = argv + optind; optind < argc; path++, optind++) {
9830                 int err = 0;
9831
9832                 if (!show_parents) {
9833                         err = llapi_path2fid(*path, &fid);
9834                         if (!err)
9835                                 printf("%s%s"DFID"\n",
9836                                        *sep != '\0' ? *path : "", sep,
9837                                        PFID(&fid));
9838                 } else {
9839                         char            name[NAME_MAX + 1];
9840                         unsigned int    linkno = 0;
9841
9842                         while ((err = llapi_path2parent(*path, linkno, &fid,
9843                                                 name, sizeof(name))) == 0) {
9844                                 if (*sep != '\0' && linkno == 0)
9845                                         printf("%s%s", *path, sep);
9846
9847                                 printf("%s"DFID"/%s", linkno != 0 ? "\t" : "",
9848                                        PFID(&fid), name);
9849                                 linkno++;
9850                         }
9851
9852                         /* err == -ENODATA is end-of-loop */
9853                         if (linkno > 0 && err == -ENODATA) {
9854                                 printf("\n");
9855                                 err = 0;
9856                         }
9857                 }
9858
9859                 if (err) {
9860                         fprintf(stderr,
9861                                 "%s path2fid: cannot get %sfid for '%s': %s\n",
9862                                 progname, show_parents ? "parent " : "", *path,
9863                                 strerror(-err));
9864                         if (rc == 0) {
9865                                 rc = err;
9866                                 errno = -err;
9867                         }
9868                 }
9869         }
9870
9871         return rc;
9872 }
9873
9874 #define MAX_ERRNO       4095
9875 #define IS_ERR_VALUE(x) ((unsigned long)(x) >= (unsigned long)-MAX_ERRNO)
9876
9877 static int lfs_rmfid_and_show_errors(int rootfd, struct fid_array *fa)
9878 {
9879         int rc, rc2, k;
9880
9881         rc = llapi_rmfid_at(rootfd, fa);
9882         if (rc < 0) {
9883                 fprintf(stderr, "%s rmfid: cannot remove FIDs: %s\n",
9884                         progname, strerror(-rc));
9885                 return rc;
9886         }
9887
9888         for (k = 0; k < fa->fa_nr; k++) {
9889                 rc2 = (__s32)fa->fa_fids[k].f_ver;
9890                 if (!IS_ERR_VALUE(rc2))
9891                         continue;
9892
9893                 if (rc == 0)
9894                         rc = rc2;
9895
9896                 fa->fa_fids[k].f_ver = 0;
9897                 fprintf(stderr, "%s rmfid: cannot remove "DFID": %s\n",
9898                         progname, PFID(&fa->fa_fids[k]), strerror(-rc2));
9899         }
9900
9901         return rc;
9902 }
9903
9904 static int lfs_rmfid(int argc, char **argv)
9905 {
9906         int rc = 0, rc2, rc3 = 0, nr;
9907         struct fid_array *fa;
9908         const char *device;
9909         char *fidstr;
9910         int rootfd;
9911
9912         /* Interactive mode: Adjust optind */
9913         if (!optind)
9914                 optind++;
9915
9916         device = argv[optind++];
9917
9918         if (optind > argc - 1) {
9919                 fprintf(stderr, "%s rmfid: missing dirname\n", progname);
9920                 return CMD_HELP;
9921         }
9922
9923         nr = argc - optind;
9924
9925         rc = llapi_root_path_open(device, &rootfd);
9926         if (rc < 0) {
9927                 fprintf(stderr,
9928                         "%s rmfid: error opening device/fsname '%s': %s\n",
9929                         progname, device, strerror(-rc));
9930                 return -rc;
9931         }
9932
9933         fa = malloc(offsetof(struct fid_array, fa_fids[nr + 1]));
9934         if (!fa) {
9935                 fprintf(stderr, "%s rmfid: error allocating %zd bytes: %s\n",
9936                         progname, offsetof(struct fid_array, fa_fids[nr + 1]),
9937                         strerror(errno));
9938                 return -ENOMEM;
9939         }
9940
9941         fa->fa_nr = 0;
9942         rc = 0;
9943         while (optind < argc) {
9944                 char *origfidstr;
9945                 int found;
9946
9947                 origfidstr = fidstr = argv[optind++];
9948                 while (*fidstr == '[')
9949                         fidstr++;
9950                 found = sscanf(fidstr, SFID, RFID(&fa->fa_fids[fa->fa_nr]));
9951                 if (found != 3) {
9952                         fprintf(stderr, "lfs rmfid: '%s': Wrong FID format\n",
9953                                 origfidstr);
9954                         if (!rc3)
9955                                 rc3 = -EINVAL; /* Invalid argument */
9956                         continue;
9957                 }
9958                 fa->fa_nr++;
9959                 if (fa->fa_nr == OBD_MAX_FIDS_IN_ARRAY) {
9960                         /* start another batch */
9961                         rc2 = lfs_rmfid_and_show_errors(rootfd, fa);
9962                         if (rc2 && !rc)
9963                                 rc = rc2;
9964                         if (rc3)
9965                                 rc = rc3;
9966                         fa->fa_nr = 0;
9967                 }
9968         }
9969         if (fa->fa_nr) {
9970                 rc2 = lfs_rmfid_and_show_errors(rootfd, fa);
9971                 if (rc2 && !rc)
9972                         rc = rc2;
9973                 if (rc3)
9974                         rc = rc3;
9975         }
9976
9977         if (fa) {
9978                 free(fa);
9979                 fa = NULL;
9980         }
9981
9982         close(rootfd);
9983         return rc;
9984 }
9985
9986 static int lfs_data_version(int argc, char **argv)
9987 {
9988         int data_version_flags = LL_DV_RD_FLUSH; /* Read by default */
9989         __u64 data_version;
9990         char *path;
9991         int fd;
9992         int rc;
9993         int c;
9994
9995         if (argc < 2) {
9996                 fprintf(stderr, "%s: FILE must be specified\n",
9997                         progname);
9998                 return CMD_HELP;
9999         }
10000
10001         while ((c = getopt(argc, argv, "hnrw")) != -1) {
10002                 switch (c) {
10003                 case 'n':
10004                         data_version_flags = 0;
10005                         break;
10006                 case 'r':
10007                         data_version_flags |= LL_DV_RD_FLUSH;
10008                         break;
10009                 case 'w':
10010                         data_version_flags |= LL_DV_WR_FLUSH;
10011                         break;
10012                 default:
10013                         fprintf(stderr,
10014                                 "%s data_version: unrecognized option '%s'\n",
10015                                 progname, argv[optind - 1]);
10016                         fallthrough;
10017                 case 'h':
10018                         return CMD_HELP;
10019                 }
10020         }
10021         if (optind == argc) {
10022                 fprintf(stderr, "%s data_version: FILE must be specified\n",
10023                         progname);
10024                 return CMD_HELP;
10025         }
10026
10027         path = argv[optind];
10028         fd = open(path, O_RDONLY);
10029         if (fd < 0) {
10030                 rc = -errno;
10031                 fprintf(stderr, "%s data_version: cannot open file '%s': %s\n",
10032                         progname, path, strerror(-rc));
10033                 return rc;
10034         }
10035
10036         rc = llapi_get_data_version(fd, &data_version, data_version_flags);
10037         if (rc < 0)
10038                 fprintf(stderr,
10039                         "%s data_version: cannot get version for '%s': %s\n",
10040                         progname, path, strerror(-rc));
10041         else
10042                 printf("%ju" "\n", (uintmax_t)data_version);
10043
10044         close(fd);
10045         return rc;
10046 }
10047
10048 static int lfs_hsm_state(int argc, char **argv)
10049 {
10050         int rc = 0;
10051         int i = 1;
10052         char *path;
10053         struct hsm_user_state hus;
10054
10055         if (argc < 2)
10056                 return CMD_HELP;
10057
10058         do {
10059                 int rc2;
10060                 path = argv[i];
10061
10062                 rc2 = llapi_hsm_state_get(path, &hus);
10063                 if (rc2) {
10064                         fprintf(stderr,
10065                                 "%s %s: get HSM state for '%s' failed: %s\n",
10066                                 progname, argv[0], path, strerror(-rc2));
10067                         if (!rc)
10068                                 rc = rc2;
10069                         continue;
10070                 }
10071
10072                 /* Display path name and status flags */
10073                 printf("%s: (0x%08x)", path, hus.hus_states);
10074
10075                 if (hus.hus_states & HS_RELEASED)
10076                         printf(" released");
10077                 if (hus.hus_states & HS_EXISTS)
10078                         printf(" exists");
10079                 if (hus.hus_states & HS_DIRTY)
10080                         printf(" dirty");
10081                 if (hus.hus_states & HS_ARCHIVED)
10082                         printf(" archived");
10083                 /* Display user-settable flags */
10084                 if (hus.hus_states & HS_NORELEASE)
10085                         printf(" never_release");
10086                 if (hus.hus_states & HS_NOARCHIVE)
10087                         printf(" never_archive");
10088                 if (hus.hus_states & HS_LOST)
10089                         printf(" lost_from_hsm");
10090
10091                 if (hus.hus_archive_id != 0)
10092                         printf(", archive_id:%d", hus.hus_archive_id);
10093                 printf("\n");
10094
10095         } while (++i < argc);
10096
10097         return rc;
10098 }
10099
10100 #define LFS_HSM_SET   0
10101 #define LFS_HSM_CLEAR 1
10102
10103 /**
10104  * Generic function to set or clear HSM flags.
10105  * Used by hsm_set and hsm_clear.
10106  *
10107  * @mode  if LFS_HSM_SET, set the flags, if LFS_HSM_CLEAR, clear the flags.
10108  */
10109 static int lfs_hsm_change_flags(int argc, char **argv, int mode)
10110 {
10111         struct option long_opts[] = {
10112         { .val = 'A',   .name = "archived",     .has_arg = no_argument },
10113         { .val = 'a',   .name = "noarchive",    .has_arg = no_argument },
10114         { .val = 'd',   .name = "dirty",        .has_arg = no_argument },
10115         { .val = 'e',   .name = "exists",       .has_arg = no_argument },
10116         { .val = 'h',   .name = "help",         .has_arg = no_argument },
10117         { .val = 'i',   .name = "archive-id",   .has_arg = required_argument },
10118         { .val = 'l',   .name = "lost",         .has_arg = no_argument },
10119         { .val = 'r',   .name = "norelease",    .has_arg = no_argument },
10120         { .name = NULL } };
10121         __u64 mask = 0;
10122         int c, rc = 0;
10123         char *path;
10124         __u32 archive_id = 0;
10125         char *end = NULL;
10126
10127         if (argc < 3)
10128                 return CMD_HELP;
10129
10130         while ((c = getopt_long(argc, argv, "aAdehi:lr",
10131                                 long_opts, NULL)) != -1) {
10132                 switch (c) {
10133                 case 'l':
10134                         mask |= HS_LOST;
10135                         break;
10136                 case 'a':
10137                         mask |= HS_NOARCHIVE;
10138                         break;
10139                 case 'A':
10140                         mask |= HS_ARCHIVED;
10141                         break;
10142                 case 'r':
10143                         mask |= HS_NORELEASE;
10144                         break;
10145                 case 'd':
10146                         mask |= HS_DIRTY;
10147                         break;
10148                 case 'e':
10149                         mask |= HS_EXISTS;
10150                         break;
10151                 case 'i':
10152                         errno = 0;
10153                         archive_id = strtol(optarg, &end, 10);
10154                         if (errno != 0 || *end != '\0' || archive_id < 0) {
10155                                 fprintf(stderr,
10156                                         "%s: invalid archive_id: '%s'\n",
10157                                         progname, end);
10158                                 return CMD_HELP;
10159                         }
10160                         break;
10161                 default:
10162                         fprintf(stderr, "%s: unrecognized option '%s'\n",
10163                                 progname, argv[optind - 1]);
10164                         fallthrough;
10165                 case 'h':
10166                         return CMD_HELP;
10167                 }
10168         }
10169
10170         /* User should have specified a flag */
10171         if (mask == 0)
10172                 return CMD_HELP;
10173
10174         while (optind < argc) {
10175                 int rc2;
10176                 path = argv[optind];
10177
10178                 /* If mode == 0, this means we apply the mask. */
10179                 if (mode == LFS_HSM_SET)
10180                         rc2 = llapi_hsm_state_set(path, mask, 0, archive_id);
10181                 else
10182                         rc2 = llapi_hsm_state_set(path, 0, mask, 0);
10183
10184                 if (rc2) {
10185                         fprintf(stderr,
10186                                 "%s %s: change hsm flags for '%s' failed: %s\n",
10187                                 progname, argv[0], path, strerror(-rc2));
10188                         if (!rc)
10189                                 rc = rc2;
10190                 }
10191                 optind++;
10192         }
10193
10194         return rc;
10195 }
10196
10197 static int lfs_hsm_action(int argc, char **argv)
10198 {
10199         struct hsm_current_action hca;
10200         struct hsm_extent he;
10201         enum hsm_user_action hua;
10202         enum hsm_progress_states hps;
10203         int rc = 0;
10204         int i = 1;
10205         char *path;
10206
10207         if (argc < 2)
10208                 return CMD_HELP;
10209
10210         do {
10211                 int rc2;
10212                 path = argv[i];
10213
10214                 rc2 = llapi_hsm_current_action(path, &hca);
10215                 if (rc2) {
10216                         fprintf(stderr,
10217                                 "%s %s: get hsm action for '%s' failed: %s\n",
10218                                 progname, argv[0], path, strerror(-rc2));
10219
10220                         if (!rc)
10221                                 rc = rc2;
10222                         continue;
10223                 }
10224                 he = hca.hca_location;
10225                 hua = hca.hca_action;
10226                 hps = hca.hca_state;
10227
10228                 printf("%s: %s", path, hsm_user_action2name(hua));
10229
10230                 /* Skip file without action */
10231                 if (hca.hca_action == HUA_NONE) {
10232                         printf("\n");
10233                         continue;
10234                 }
10235
10236                 printf(" %s ", hsm_progress_state2name(hps));
10237
10238                 if ((hps == HPS_RUNNING) &&
10239                     (hua == HUA_ARCHIVE || hua == HUA_RESTORE))
10240                         printf("(%llu bytes moved)\n",
10241                                (unsigned long long)he.length);
10242                 else if ((he.offset + he.length) == LUSTRE_EOF)
10243                         printf("(from %llu to EOF)\n",
10244                                (unsigned long long)he.offset);
10245                 else
10246                         printf("(from %llu to %llu)\n",
10247                                (unsigned long long)he.offset,
10248                                (unsigned long long)(he.offset + he.length));
10249
10250         } while (++i < argc);
10251
10252         return rc;
10253 }
10254
10255 static int lfs_hsm_set(int argc, char **argv)
10256 {
10257         return lfs_hsm_change_flags(argc, argv, LFS_HSM_SET);
10258 }
10259
10260 static int lfs_hsm_clear(int argc, char **argv)
10261 {
10262         return lfs_hsm_change_flags(argc, argv, LFS_HSM_CLEAR);
10263 }
10264
10265 /**
10266  * Check file state and return its fid, to be used by lfs_hsm_request().
10267  *
10268  * \param[in]     file      Path to file to check
10269  * \param[in,out] fid       Pointer to allocated lu_fid struct.
10270  * \param[in,out] last_dev  Pointer to last device id used.
10271  *
10272  * \return 0 on success.
10273  */
10274 static int lfs_hsm_prepare_file(const char *file, struct lu_fid *fid,
10275                                 dev_t *last_dev)
10276 {
10277         struct stat     st;
10278         int             rc;
10279
10280         rc = lstat(file, &st);
10281         if (rc) {
10282                 fprintf(stderr, "Cannot stat %s: %s\n", file, strerror(errno));
10283                 return -errno;
10284         }
10285         /*
10286          * Checking for regular file as archiving as posix copytool
10287          * rejects archiving files other than regular files
10288          */
10289         if (!S_ISREG(st.st_mode)) {
10290                 fprintf(stderr, "error: \"%s\" is not a regular file\n", file);
10291                 return CMD_HELP;
10292         }
10293         /* A request should be ... */
10294         if (*last_dev != st.st_dev && *last_dev != 0) {
10295                 fprintf(stderr,
10296                         "All files should be on the same filesystem: %s\n",
10297                         file);
10298                 return -EINVAL;
10299         }
10300         *last_dev = st.st_dev;
10301
10302         rc = llapi_path2fid(file, fid);
10303         if (rc) {
10304                 fprintf(stderr, "Cannot read FID of %s: %s\n",
10305                         file, strerror(-rc));
10306                 return rc;
10307         }
10308         return 0;
10309 }
10310
10311 /* Fill an HSM HUR item with a given file name.
10312  *
10313  * If mntpath is set, then the filename is actually a FID, and no
10314  * lookup on the filesystem will be performed.
10315  *
10316  * \param[in]  hur         the user request to fill
10317  * \param[in]  idx         index of the item inside the HUR to fill
10318  * \param[in]  mntpath     mountpoint of Lustre
10319  * \param[in]  fname       filename (if mtnpath is NULL)
10320  *                         or FID (if mntpath is set)
10321  * \param[in]  last_dev    pointer to last device id used
10322  *
10323  * \retval 0 on success
10324  * \retval CMD_HELP or a negative errno on error
10325  */
10326 static int fill_hur_item(struct hsm_user_request *hur, unsigned int idx,
10327                          const char *mntpath, const char *fname,
10328                          dev_t *last_dev)
10329 {
10330         struct hsm_user_item *hui = &hur->hur_user_item[idx];
10331         int rc;
10332
10333         hui->hui_extent.length = -1;
10334
10335         if (mntpath) {
10336                 rc = llapi_fid_parse(fname, &hui->hui_fid, NULL);
10337                 if (rc)
10338                         fprintf(stderr, "hsm: '%s' is not a valid FID\n",
10339                                 fname);
10340         } else {
10341                 rc = lfs_hsm_prepare_file(fname, &hui->hui_fid, last_dev);
10342         }
10343
10344         if (rc == 0)
10345                 hur->hur_request.hr_itemcount++;
10346
10347         return rc;
10348 }
10349
10350 static int lfs_hsm_request(int argc, char **argv, int action)
10351 {
10352         struct option long_opts[] = {
10353         { .val = 'a',   .name = "archive",      .has_arg = required_argument },
10354         { .val = 'D',   .name = "data",         .has_arg = required_argument },
10355         { .val = 'h',   .name = "help",         .has_arg = no_argument },
10356         { .val = 'l',   .name = "filelist",     .has_arg = required_argument },
10357         { .val = 'm',   .name = "mntpath",      .has_arg = required_argument },
10358         { .name = NULL } };
10359         dev_t last_dev = 0;
10360         struct hsm_user_request *hur, *oldhur;
10361         int c, i;
10362         size_t len;
10363         int nbfile;
10364         char *line = NULL;
10365         char *filelist = NULL;
10366         char fullpath[PATH_MAX];
10367         char *opaque = NULL;
10368         int opaque_len = 0;
10369         int archive_id = 0;
10370         FILE *fp;
10371         int nbfile_alloc = 0;
10372         char *some_file = NULL;
10373         char *mntpath = NULL;
10374         int rc;
10375
10376         if (argc < 2)
10377                 return CMD_HELP;
10378
10379         while ((c = getopt_long(argc, argv, "a:D:hl:m:",
10380                                 long_opts, NULL)) != -1) {
10381                 switch (c) {
10382                 case 'l':
10383                         filelist = optarg;
10384                         break;
10385                 case 'D':
10386                         opaque = optarg;
10387                         break;
10388                 case 'a':
10389                         if (action != HUA_ARCHIVE &&
10390                             action != HUA_REMOVE) {
10391                                 fprintf(stderr,
10392                                         "error: -a is supported only when archiving or removing\n");
10393                                 return CMD_HELP;
10394                         }
10395                         archive_id = atoi(optarg);
10396                         break;
10397                 case 'm':
10398                         if (!some_file) {
10399                                 mntpath = optarg;
10400                                 some_file = strdup(optarg);
10401                         }
10402                         break;
10403                 default:
10404                         fprintf(stderr, "%s: unrecognized option '%s'\n",
10405                                 progname, argv[optind - 1]);
10406                         fallthrough;
10407                 case 'h':
10408                         return CMD_HELP;
10409                 }
10410         }
10411
10412         /* All remaining args are files, so we have at least nbfile */
10413         nbfile = argc - optind;
10414
10415         if ((nbfile == 0) && (!filelist))
10416                 return CMD_HELP;
10417
10418         if (opaque)
10419                 opaque_len = strlen(opaque);
10420
10421         /*
10422          * Alloc the request structure with enough place to store all files
10423          * from command line.
10424          */
10425         hur = llapi_hsm_user_request_alloc(nbfile, opaque_len);
10426         if (!hur) {
10427                 fprintf(stderr, "Cannot create the request: %s\n",
10428                         strerror(errno));
10429                 return errno;
10430         }
10431         nbfile_alloc = nbfile;
10432
10433         hur->hur_request.hr_action = action;
10434         hur->hur_request.hr_archive_id = archive_id;
10435         hur->hur_request.hr_flags = 0;
10436
10437         /* All remaining args are files, add them */
10438         if (nbfile != 0 && some_file == NULL)
10439                 some_file = strdup(argv[optind]);
10440
10441         for (i = 0; i < nbfile; i++) {
10442                 rc = fill_hur_item(hur, i, mntpath, argv[optind + i],
10443                                    &last_dev);
10444                 if (rc)
10445                         goto out_free;
10446         }
10447
10448         /* from here stop using nb_file, use hur->hur_request.hr_itemcount */
10449
10450         /* If a filelist was specified, read the filelist from it. */
10451         if (filelist) {
10452                 fp = fopen(filelist, "r");
10453                 if (!fp) {
10454                         fprintf(stderr, "Cannot read the file list %s: %s\n",
10455                                 filelist, strerror(errno));
10456                         rc = -errno;
10457                         goto out_free;
10458                 }
10459
10460                 while ((rc = getline(&line, &len, fp)) != -1) {
10461                         /*
10462                          * If allocated buffer was too small, get something
10463                          * larger
10464                          */
10465                         if (nbfile_alloc <= hur->hur_request.hr_itemcount) {
10466                                 ssize_t size;
10467
10468                                 nbfile_alloc = nbfile_alloc * 2 + 1;
10469                                 oldhur = hur;
10470                                 hur = llapi_hsm_user_request_alloc(nbfile_alloc,
10471                                                                    opaque_len);
10472                                 if (!hur) {
10473                                         fprintf(stderr,
10474                                                 "hsm: cannot allocate the request: %s\n",
10475                                                 strerror(errno));
10476                                         hur = oldhur;
10477                                         rc = -errno;
10478                                         fclose(fp);
10479                                         goto out_free;
10480                                 }
10481                                 size = hur_len(oldhur);
10482                                 if (size < 0) {
10483                                         fprintf(stderr,
10484                                                 "hsm: cannot allocate %u files + %u bytes data\n",
10485                                                 oldhur->hur_request.hr_itemcount,
10486                                                 oldhur->hur_request.hr_data_len);
10487                                         free(hur);
10488                                         hur = oldhur;
10489                                         rc = -E2BIG;
10490                                         fclose(fp);
10491                                         goto out_free;
10492                                 }
10493                                 memcpy(hur, oldhur, size);
10494                                 free(oldhur);
10495                         }
10496
10497                         /* Chop CR */
10498                         if (line[strlen(line) - 1] == '\n')
10499                                 line[strlen(line) - 1] = '\0';
10500
10501                         rc = fill_hur_item(hur, hur->hur_request.hr_itemcount,
10502                                            mntpath, line, &last_dev);
10503                         if (rc) {
10504                                 fclose(fp);
10505                                 goto out_free;
10506                         }
10507
10508                         if (!some_file) {
10509                                 some_file = line;
10510                                 line = NULL;
10511                         }
10512                 }
10513
10514                 rc = fclose(fp);
10515                 free(line);
10516         }
10517
10518         /* If a --data was used, add it to the request */
10519         hur->hur_request.hr_data_len = opaque_len;
10520         if (opaque)
10521                 memcpy(hur_data(hur), opaque, opaque_len);
10522
10523         /* Send the HSM request */
10524         if (realpath(some_file, fullpath) == NULL) {
10525                 fprintf(stderr, "Could not find path '%s': %s\n",
10526                         some_file, strerror(errno));
10527         }
10528         rc = llapi_hsm_request(fullpath, hur);
10529         if (rc) {
10530                 fprintf(stderr, "Cannot send HSM request (use of %s): %s\n",
10531                         some_file, strerror(-rc));
10532                 goto out_free;
10533         }
10534
10535 out_free:
10536         free(some_file);
10537         free(hur);
10538         return rc;
10539 }
10540
10541 static int lfs_hsm_archive(int argc, char **argv)
10542 {
10543         return lfs_hsm_request(argc, argv, HUA_ARCHIVE);
10544 }
10545
10546 static int lfs_hsm_restore(int argc, char **argv)
10547 {
10548         return lfs_hsm_request(argc, argv, HUA_RESTORE);
10549 }
10550
10551 static int lfs_hsm_release(int argc, char **argv)
10552 {
10553         return lfs_hsm_request(argc, argv, HUA_RELEASE);
10554 }
10555
10556 static int lfs_hsm_remove(int argc, char **argv)
10557 {
10558         return lfs_hsm_request(argc, argv, HUA_REMOVE);
10559 }
10560
10561 static int lfs_hsm_cancel(int argc, char **argv)
10562 {
10563         return lfs_hsm_request(argc, argv, HUA_CANCEL);
10564 }
10565
10566 static int lfs_swap_layouts(int argc, char **argv)
10567 {
10568         if (argc != 3)
10569                 return CMD_HELP;
10570
10571         return llapi_swap_layouts(argv[1], argv[2], 0, 0,
10572                                   SWAP_LAYOUTS_KEEP_MTIME |
10573                                   SWAP_LAYOUTS_KEEP_ATIME);
10574 }
10575
10576 static const char *const ladvise_names[] = LU_LADVISE_NAMES;
10577
10578 static const char *const lock_mode_names[] = LOCK_MODE_NAMES;
10579
10580 int lfs_get_mode(const char *string)
10581 {
10582         enum lock_mode_user mode;
10583
10584         for (mode = 0; mode < ARRAY_SIZE(lock_mode_names); mode++) {
10585                 if (lock_mode_names[mode] == NULL)
10586                         continue;
10587                 if (strcasecmp(string, lock_mode_names[mode]) == 0)
10588                         return mode;
10589         }
10590
10591         return -EINVAL;
10592 }
10593
10594 static enum lu_ladvise_type lfs_get_ladvice(const char *string)
10595 {
10596         enum lu_ladvise_type advice;
10597
10598         for (advice = 0;
10599              advice < ARRAY_SIZE(ladvise_names); advice++) {
10600                 if (ladvise_names[advice] == NULL)
10601                         continue;
10602                 if (strcmp(string, ladvise_names[advice]) == 0)
10603                         return advice;
10604         }
10605
10606         return LU_LADVISE_INVALID;
10607 }
10608
10609 static int lfs_ladvise(int argc, char **argv)
10610 {
10611         struct option long_opts[] = {
10612         { .val = 'a',   .name = "advice",       .has_arg = required_argument },
10613         { .val = 'b',   .name = "background",   .has_arg = no_argument },
10614         { .val = 'e',   .name = "end",          .has_arg = required_argument },
10615         { .val = 'h',   .name = "help",         .has_arg = no_argument },
10616         { .val = 'l',   .name = "length",       .has_arg = required_argument },
10617         { .val = 'm',   .name = "mode",         .has_arg = required_argument },
10618         { .val = 's',   .name = "start",        .has_arg = required_argument },
10619         { .val = 'u',   .name = "unset",        .has_arg = no_argument },
10620         { .name = NULL } };
10621         struct llapi_lu_ladvise advice;
10622         enum lu_ladvise_type advice_type = LU_LADVISE_INVALID;
10623         unsigned long long start = 0;
10624         unsigned long long end = LUSTRE_EOF;
10625         unsigned long long length = 0;
10626         unsigned long long size_units;
10627         unsigned long long flags = 0;
10628         int c, fd, rc = 0;
10629         const char *path;
10630         int mode = 0;
10631
10632         optind = 0;
10633         while ((c = getopt_long(argc, argv, "a:be:hl:m:s:u",
10634                                 long_opts, NULL)) != -1) {
10635                 switch (c) {
10636                 case 'a':
10637                         advice_type = lfs_get_ladvice(optarg);
10638                         if (advice_type == LU_LADVISE_INVALID) {
10639                                 fprintf(stderr,
10640                                         "%s: invalid advice type '%s'\n",
10641                                         progname, optarg);
10642                                 fprintf(stderr, "Valid types:");
10643
10644                                 for (advice_type = 0;
10645                                      advice_type < ARRAY_SIZE(ladvise_names);
10646                                      advice_type++) {
10647                                         if (ladvise_names[advice_type] == NULL)
10648                                                 continue;
10649                                         fprintf(stderr, " %s",
10650                                                 ladvise_names[advice_type]);
10651                                 }
10652                                 fprintf(stderr, "\n");
10653
10654                                 return CMD_HELP;
10655                         }
10656                         break;
10657                 case 'b':
10658                         flags |= LF_ASYNC;
10659                         break;
10660                 case 'u':
10661                         flags |= LF_UNSET;
10662                         break;
10663                 case 'e':
10664                         size_units = 1;
10665                         rc = llapi_parse_size(optarg, &end,
10666                                               &size_units, 0);
10667                         if (rc) {
10668                                 fprintf(stderr, "%s: bad end offset '%s'\n",
10669                                         argv[0], optarg);
10670                                 return CMD_HELP;
10671                         }
10672                         break;
10673                 case 's':
10674                         size_units = 1;
10675                         rc = llapi_parse_size(optarg, &start,
10676                                               &size_units, 0);
10677                         if (rc) {
10678                                 fprintf(stderr,
10679                                         "%s: bad start offset '%s'\n",
10680                                         argv[0], optarg);
10681                                 return CMD_HELP;
10682                         }
10683                         break;
10684                 case 'l':
10685                         size_units = 1;
10686                         rc = llapi_parse_size(optarg, &length,
10687                                               &size_units, 0);
10688                         if (rc) {
10689                                 fprintf(stderr, "%s: bad length '%s'\n",
10690                                         argv[0], optarg);
10691                                 return CMD_HELP;
10692                         }
10693                         break;
10694                 case 'm':
10695                         mode = lfs_get_mode(optarg);
10696                         if (mode < 0) {
10697                                 fprintf(stderr,
10698                                         "%s: bad mode '%s', valid modes are READ or WRITE\n",
10699                                         argv[0], optarg);
10700                                 return CMD_HELP;
10701                         }
10702                         break;
10703                 default:
10704                         fprintf(stderr, "%s: unrecognized option '%s'\n",
10705                                 progname, argv[optind - 1]);
10706                         fallthrough;
10707                 case 'h':
10708                         return CMD_HELP;
10709                 }
10710         }
10711
10712         if (advice_type == LU_LADVISE_INVALID) {
10713                 fprintf(stderr, "%s: please give an advice type\n", argv[0]);
10714                 fprintf(stderr, "Valid types:");
10715                 for (advice_type = 0; advice_type < ARRAY_SIZE(ladvise_names);
10716                      advice_type++) {
10717                         if (ladvise_names[advice_type] == NULL)
10718                                 continue;
10719                         fprintf(stderr, " %s", ladvise_names[advice_type]);
10720                 }
10721                 fprintf(stderr, "\n");
10722                 return CMD_HELP;
10723         }
10724
10725         if (advice_type == LU_LADVISE_LOCKNOEXPAND) {
10726                 fprintf(stderr,
10727                         "%s: Lock no expand advice is a per file descriptor advice, so when called from lfs, it does nothing.\n",
10728                         argv[0]);
10729                 return CMD_HELP;
10730         }
10731
10732         if (argc <= optind) {
10733                 fprintf(stderr, "%s: please give one or more file names\n",
10734                         argv[0]);
10735                 return CMD_HELP;
10736         }
10737
10738         if (end != LUSTRE_EOF && length != 0 && end != start + length) {
10739                 fprintf(stderr, "%s: conflicting arguments of -l and -e\n",
10740                         argv[0]);
10741                 return CMD_HELP;
10742         }
10743
10744         if (end == LUSTRE_EOF && length != 0)
10745                 end = start + length;
10746
10747         if (end <= start) {
10748                 fprintf(stderr, "%s: range [%llu, %llu] is invalid\n",
10749                         argv[0], start, end);
10750                 return CMD_HELP;
10751         }
10752
10753         if (advice_type != LU_LADVISE_LOCKAHEAD && mode != 0) {
10754                 fprintf(stderr, "%s: mode is only valid with lockahead\n",
10755                         argv[0]);
10756                 return CMD_HELP;
10757         }
10758
10759         if (advice_type == LU_LADVISE_LOCKAHEAD && mode == 0) {
10760                 fprintf(stderr, "%s: mode is required with lockahead\n",
10761                         argv[0]);
10762                 return CMD_HELP;
10763         }
10764
10765         while (optind < argc) {
10766                 int rc2;
10767
10768                 path = argv[optind++];
10769
10770                 fd = open(path, O_RDONLY);
10771                 if (fd < 0) {
10772                         rc2 = -errno;
10773                         fprintf(stderr, "%s: cannot open file '%s': %s\n",
10774                                 argv[0], path, strerror(-rc2));
10775                         if (!rc)
10776                                 rc = rc2;
10777                         continue;
10778                 }
10779
10780                 advice.lla_start = start;
10781                 advice.lla_end = end;
10782                 advice.lla_advice = advice_type;
10783                 advice.lla_value1 = 0;
10784                 advice.lla_value2 = 0;
10785                 advice.lla_value3 = 0;
10786                 advice.lla_value4 = 0;
10787                 if (advice_type == LU_LADVISE_LOCKAHEAD) {
10788                         advice.lla_lockahead_mode = mode;
10789                         advice.lla_peradvice_flags = flags;
10790                 }
10791
10792                 rc2 = llapi_ladvise(fd, flags, 1, &advice);
10793                 close(fd);
10794                 if (rc2 < 0) {
10795                         fprintf(stderr,
10796                                 "%s: cannot give advice '%s' to file '%s': %s\n",
10797                                 argv[0], ladvise_names[advice_type],
10798                                 path, strerror(errno));
10799
10800                         if (!rc)
10801                                 rc = rc2;
10802                         continue;
10803                 }
10804         }
10805
10806         return rc;
10807 }
10808
10809 static const char *const heat_names[] = LU_HEAT_NAMES;
10810
10811 static int lfs_heat_get(int argc, char **argv)
10812 {
10813         struct lu_heat *heat;
10814         int rc = 0, rc2;
10815         char *path;
10816         int fd;
10817         int i;
10818
10819         if (argc <= 1)
10820                 return CMD_HELP;
10821
10822         heat = calloc(sizeof(*heat) + sizeof(__u64) * OBD_HEAT_COUNT, 1);
10823         if (!heat) {
10824                 fprintf(stderr, "%s: memory allocation failed\n", argv[0]);
10825                 return -ENOMEM;
10826         }
10827
10828         optind = 1;
10829         while (optind < argc) {
10830                 path = argv[optind++];
10831
10832                 fd = open(path, O_RDONLY);
10833                 if (fd < 0) {
10834                         fprintf(stderr, "%s: cannot open file '%s': %s\n",
10835                                 argv[0], path, strerror(errno));
10836                         rc2 = -errno;
10837                         goto next;
10838                 }
10839
10840                 heat->lh_count = OBD_HEAT_COUNT;
10841                 rc2 = llapi_heat_get(fd, heat);
10842                 close(fd);
10843                 if (rc2 < 0) {
10844                         fprintf(stderr,
10845                                 "%s: cannot get heat of file '%s': %s\n",
10846                                 argv[0], path, strerror(errno));
10847                         goto next;
10848                 }
10849
10850                 printf("flags: %x\n", heat->lh_flags);
10851                 for (i = 0; i < heat->lh_count; i++)
10852                         printf("%s: %llu\n", heat_names[i],
10853                                (unsigned long long)heat->lh_heat[i]);
10854 next:
10855                 if (rc == 0 && rc2 < 0)
10856                         rc = rc2;
10857         }
10858
10859         free(heat);
10860         return rc;
10861 }
10862
10863 static int lfs_heat_set(int argc, char **argv)
10864 {
10865         struct option long_opts[] = {
10866         { .val = 'c',   .name = "clear",        .has_arg = no_argument },
10867         { .val = 'h',   .name = "help",         .has_arg = no_argument },
10868         { .val = 'o',   .name = "off",          .has_arg = no_argument },
10869         { .val = 'O',   .name = "on",           .has_arg = no_argument },
10870         { .name = NULL } };
10871         enum lu_heat_flag flags = 0;
10872         int rc = 0, rc2;
10873         char *path;
10874         int fd;
10875         int c;
10876
10877         if (argc <= 1)
10878                 return CMD_HELP;
10879
10880         optind = 0;
10881         while ((c = getopt_long(argc, argv, "choO", long_opts, NULL)) != -1) {
10882                 switch (c) {
10883                 case 'c':
10884                         flags |= LU_HEAT_FLAG_CLEAR;
10885                         break;
10886                 case 'o':
10887                         flags |= LU_HEAT_FLAG_CLEAR;
10888                         flags |= LU_HEAT_FLAG_OFF;
10889                         break;
10890                 case 'O':
10891                         flags &= ~LU_HEAT_FLAG_OFF;
10892                         break;
10893                 default:
10894                         fprintf(stderr, "%s: unrecognized option '%s'\n",
10895                                 progname, argv[optind - 1]);
10896                         fallthrough;
10897                 case 'h':
10898                         return CMD_HELP;
10899                 }
10900         }
10901
10902         if (argc <= optind) {
10903                 fprintf(stderr, "%s: please give one or more file names\n",
10904                         argv[0]);
10905                 return CMD_HELP;
10906         }
10907
10908         while (optind < argc) {
10909                 path = argv[optind++];
10910
10911                 fd = open(path, O_RDONLY);
10912                 if (fd < 0) {
10913                         fprintf(stderr, "%s: cannot open file '%s': %s\n",
10914                                 argv[0], path, strerror(errno));
10915                         rc2 = -errno;
10916                         goto next;
10917                 }
10918
10919                 rc2 = llapi_heat_set(fd, flags);
10920                 close(fd);
10921                 if (rc2 < 0) {
10922                         fprintf(stderr,
10923                                 "%s: cannot setflags heat of file '%s': %s\n",
10924                                 argv[0], path, strerror(errno));
10925                         goto next;
10926                 }
10927 next:
10928                 if (rc == 0 && rc2 < 0)
10929                         rc = rc2;
10930         }
10931         return rc;
10932 }
10933
10934 /**
10935  * The input string contains a comma delimited list of component ids and
10936  * ranges, for example "1,2-4,7".
10937  */
10938 static int parse_mirror_ids(__u16 *ids, int size, char *arg)
10939 {
10940         bool end_of_loop = false;
10941         char *ptr = NULL;
10942         int nr = 0;
10943         int rc;
10944
10945         if (!arg)
10946                 return -EINVAL;
10947
10948         while (!end_of_loop) {
10949                 int start_index;
10950                 int end_index;
10951                 int i;
10952                 char *endptr = NULL;
10953
10954                 rc = -EINVAL;
10955                 ptr = strchrnul(arg, ',');
10956                 end_of_loop = *ptr == '\0';
10957                 *ptr = '\0';
10958
10959                 start_index = strtol(arg, &endptr, 0);
10960                 if (endptr == arg) /* no data at all */
10961                         break;
10962                 if (*endptr != '-' && *endptr != '\0') /* has invalid data */
10963                         break;
10964                 if (start_index < 0)
10965                         break;
10966
10967                 end_index = start_index;
10968                 if (*endptr == '-') {
10969                         end_index = strtol(endptr + 1, &endptr, 0);
10970                         if (*endptr != '\0')
10971                                 break;
10972                         if (end_index < start_index)
10973                                 break;
10974                 }
10975
10976                 for (i = start_index; i <= end_index && size > 0; i++) {
10977                         int j;
10978
10979                         /* remove duplicate */
10980                         for (j = 0; j < nr; j++) {
10981                                 if (ids[j] == i)
10982                                         break;
10983                         }
10984                         if (j == nr) { /* no duplicate */
10985                                 ids[nr++] = i;
10986                                 --size;
10987                         }
10988                 }
10989
10990                 if (size == 0 && i < end_index)
10991                         break;
10992
10993                 *ptr = ',';
10994                 arg = ++ptr;
10995                 rc = 0;
10996         }
10997         if (!end_of_loop && ptr)
10998                 *ptr = ',';
10999
11000         return rc < 0 ? rc : nr;
11001 }
11002
11003 /**
11004  * struct verify_mirror_id - Mirror id to be verified.
11005  * @mirror_id:   A specified mirror id.
11006  * @is_valid_id: @mirror_id is valid or not in the mirrored file.
11007  */
11008 struct verify_mirror_id {
11009         __u16 mirror_id;
11010         bool is_valid_id;
11011 };
11012
11013 /**
11014  * compare_mirror_ids() - Compare mirror ids.
11015  * @layout: Mirror component list.
11016  * @cbdata: Callback data in verify_mirror_id structure.
11017  *
11018  * This is a callback function called by llapi_layout_comp_iterate()
11019  * to compare the specified mirror id with the one in the current
11020  * component of @layout. If they are the same, then the specified
11021  * mirror id is valid.
11022  *
11023  * Return: a negative error code on failure or
11024  *         LLAPI_LAYOUT_ITER_CONT: Proceed iteration
11025  *         LLAPI_LAYOUT_ITER_STOP: Stop iteration
11026  */
11027 static inline
11028 int compare_mirror_ids(struct llapi_layout *layout, void *cbdata)
11029 {
11030         struct verify_mirror_id *mirror_id_cbdata =
11031                                  (struct verify_mirror_id *)cbdata;
11032         uint32_t mirror_id;
11033         int rc = 0;
11034
11035         rc = llapi_layout_mirror_id_get(layout, &mirror_id);
11036         if (rc < 0) {
11037                 rc = -errno;
11038                 fprintf(stderr,
11039                         "%s: llapi_layout_mirror_id_get failed: %s.\n",
11040                         progname, strerror(errno));
11041                 return rc;
11042         }
11043
11044         if (mirror_id_cbdata->mirror_id == mirror_id) {
11045                 mirror_id_cbdata->is_valid_id = true;
11046                 return LLAPI_LAYOUT_ITER_STOP;
11047         }
11048
11049         return LLAPI_LAYOUT_ITER_CONT;
11050 }
11051
11052 /**
11053  * verify_mirror_ids() - Verify specified mirror ids.
11054  * @fname:      Mirrored file name.
11055  * @mirror_ids: Specified mirror ids to be verified.
11056  * @ids_nr:     Number of specified mirror ids.
11057  *
11058  * This function verifies that specified @mirror_ids are valid
11059  * in the mirrored file @fname.
11060  *
11061  * Return: 0 on success or a negative error code on failure.
11062  */
11063 static inline
11064 int verify_mirror_ids(const char *fname, __u16 *mirror_ids, int ids_nr)
11065 {
11066         struct llapi_layout *layout = NULL;
11067         struct verify_mirror_id mirror_id_cbdata = { 0 };
11068         struct stat stbuf;
11069         uint32_t flr_state;
11070         int i;
11071         int fd;
11072         int rc = 0;
11073         int rc2 = 0;
11074
11075         if (ids_nr <= 0)
11076                 return -EINVAL;
11077
11078         if (stat(fname, &stbuf) < 0) {
11079                 fprintf(stderr, "%s: cannot stat file '%s': %s.\n",
11080                         progname, fname, strerror(errno));
11081                 rc = -errno;
11082                 goto error;
11083         }
11084
11085         if (!S_ISREG(stbuf.st_mode)) {
11086                 fprintf(stderr, "%s: '%s' is not a regular file.\n",
11087                         progname, fname);
11088                 rc = -EINVAL;
11089                 goto error;
11090         }
11091
11092         fd = open(fname, O_DIRECT | O_RDONLY);
11093         if (fd < 0) {
11094                 fprintf(stderr, "%s: cannot open '%s': %s.\n",
11095                         progname, fname, strerror(errno));
11096                 rc = -errno;
11097                 goto error;
11098         }
11099
11100         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
11101         if (rc < 0) {
11102                 fprintf(stderr, "%s: '%s' llapi_lease_acquire failed: %s.\n",
11103                         progname, fname, strerror(errno));
11104                 goto close_fd;
11105         }
11106
11107         layout = llapi_layout_get_by_fd(fd, 0);
11108         if (!layout) {
11109                 fprintf(stderr, "%s: '%s' llapi_layout_get_by_fd failed: %s.\n",
11110                         progname, fname, strerror(errno));
11111                 rc = -errno;
11112                 llapi_lease_release(fd);
11113                 goto close_fd;
11114         }
11115
11116         rc = llapi_layout_flags_get(layout, &flr_state);
11117         if (rc < 0) {
11118                 fprintf(stderr, "%s: '%s' llapi_layout_flags_get failed: %s.\n",
11119                         progname, fname, strerror(errno));
11120                 rc = -errno;
11121                 goto free_layout;
11122         }
11123
11124         flr_state &= LCM_FL_FLR_MASK;
11125         switch (flr_state) {
11126         case LCM_FL_NONE:
11127                 rc = -EINVAL;
11128                 fprintf(stderr, "%s: '%s' file state error: %s.\n",
11129                         progname, fname, llapi_layout_flags_string(flr_state));
11130                 goto free_layout;
11131         default:
11132                 break;
11133         }
11134
11135         rc2 = 0;
11136         for (i = 0; i < ids_nr; i++) {
11137                 mirror_id_cbdata.mirror_id = mirror_ids[i];
11138                 mirror_id_cbdata.is_valid_id = false;
11139
11140                 rc = llapi_layout_comp_iterate(layout, compare_mirror_ids,
11141                                                &mirror_id_cbdata);
11142                 if (rc < 0) {
11143                         rc = -errno;
11144                         fprintf(stderr,
11145                                 "%s: '%s' failed to verify mirror id: %u.\n",
11146                                 progname, fname, mirror_ids[i]);
11147                         goto free_layout;
11148                 }
11149
11150                 if (!mirror_id_cbdata.is_valid_id) {
11151                         rc2 = -EINVAL;
11152                         fprintf(stderr,
11153                                 "%s: '%s' invalid specified mirror id: %u.\n",
11154                                 progname, fname, mirror_ids[i]);
11155                 }
11156         }
11157         rc = rc2;
11158
11159 free_layout:
11160         llapi_layout_free(layout);
11161         llapi_lease_release(fd);
11162 close_fd:
11163         close(fd);
11164 error:
11165         return rc;
11166 }
11167
11168 static inline
11169 int lfs_mirror_resync_file(const char *fname, struct ll_ioc_lease *ioc,
11170                            __u16 *mirror_ids, int ids_nr)
11171 {
11172         struct llapi_resync_comp comp_array[1024] = { { 0 } };
11173         struct llapi_layout *layout;
11174         struct stat stbuf;
11175         uint32_t flr_state;
11176         uint64_t start;
11177         uint64_t end;
11178         int comp_size = 0;
11179         int idx;
11180         int fd;
11181         int rc;
11182         int rc2;
11183
11184         if (stat(fname, &stbuf) < 0) {
11185                 fprintf(stderr, "%s: cannot stat file '%s': %s.\n",
11186                         progname, fname, strerror(errno));
11187                 rc = -errno;
11188                 goto error;
11189         }
11190         if (!S_ISREG(stbuf.st_mode)) {
11191                 fprintf(stderr, "%s: '%s' is not a regular file.\n",
11192                         progname, fname);
11193                 rc = -EINVAL;
11194                 goto error;
11195         }
11196
11197         /* Allow mirror resync even without the key on encrypted files */
11198         fd = open(fname, O_DIRECT | O_RDWR | O_FILE_ENC);
11199         if (fd < 0) {
11200                 fprintf(stderr, "%s: cannot open '%s': %s.\n",
11201                         progname, fname, strerror(errno));
11202                 rc = -errno;
11203                 goto error;
11204         }
11205
11206         layout = llapi_layout_get_by_fd(fd, 0);
11207         if (!layout) {
11208                 fprintf(stderr, "%s: '%s' llapi_layout_get_by_fd failed: %s.\n",
11209                         progname, fname, strerror(errno));
11210                 rc = -errno;
11211                 goto close_fd;
11212         }
11213
11214         rc = llapi_layout_flags_get(layout, &flr_state);
11215         if (rc) {
11216                 fprintf(stderr, "%s: '%s' llapi_layout_flags_get failed: %s.\n",
11217                         progname, fname, strerror(errno));
11218                 rc = -errno;
11219                 goto free_layout;
11220         }
11221
11222         flr_state &= LCM_FL_FLR_MASK;
11223         if (flr_state == LCM_FL_NONE) {
11224                 rc = -EINVAL;
11225                 fprintf(stderr, "%s: '%s' is not a FLR file.\n",
11226                         progname, fname);
11227                 goto free_layout;
11228         }
11229
11230         /* get stale component info */
11231         comp_size = llapi_mirror_find_stale(layout, comp_array,
11232                                             ARRAY_SIZE(comp_array),
11233                                             mirror_ids, ids_nr);
11234         if (comp_size <= 0) {
11235                 rc = comp_size;
11236                 goto free_layout;
11237         }
11238
11239         ioc->lil_mode = LL_LEASE_WRLCK;
11240         ioc->lil_flags = LL_LEASE_RESYNC;
11241         rc = llapi_lease_set(fd, ioc);
11242         if (rc < 0) {
11243                 if (rc == -EALREADY)
11244                         rc = 0;
11245                 else
11246                         fprintf(stderr,
11247                             "%s: '%s' llapi_lease_get_ext resync failed: %s.\n",
11248                                 progname, fname, strerror(-rc));
11249                 goto free_layout;
11250         }
11251
11252         /* get the read range [start, end) */
11253         start = comp_array[0].lrc_start;
11254         end = comp_array[0].lrc_end;
11255         for (idx = 1; idx < comp_size; idx++) {
11256                 if (comp_array[idx].lrc_start < start)
11257                         start = comp_array[idx].lrc_start;
11258                 if (end < comp_array[idx].lrc_end)
11259                         end = comp_array[idx].lrc_end;
11260         }
11261
11262         rc = llapi_lease_check(fd);
11263         if (rc != LL_LEASE_WRLCK) {
11264                 fprintf(stderr, "%s: '%s' lost lease lock.\n",
11265                         progname, fname);
11266                 goto free_layout;
11267         }
11268
11269         rc = llapi_mirror_resync_many(fd, layout, comp_array, comp_size,
11270                                       start, end);
11271         if (rc < 0)
11272                 fprintf(stderr, "%s: '%s' llapi_mirror_resync_many: %s.\n",
11273                         progname, fname, strerror(-rc));
11274
11275         rc = migrate_set_timestamps(fd, &stbuf);
11276         if (rc < 0) {
11277                 fprintf(stderr, "%s: '%s' cannot set timestamps: %s\n",
11278                         progname, fname, strerror(-rc));
11279                 goto free_layout;
11280         }
11281
11282         /* need to do the lease unlock even resync fails */
11283         ioc->lil_mode = LL_LEASE_UNLCK;
11284         ioc->lil_flags = LL_LEASE_RESYNC_DONE;
11285         ioc->lil_count = 0;
11286         for (idx = 0; idx < comp_size; idx++) {
11287                 if (comp_array[idx].lrc_synced) {
11288                         ioc->lil_ids[ioc->lil_count] = comp_array[idx].lrc_id;
11289                         ioc->lil_count++;
11290                 }
11291         }
11292
11293         rc2 = llapi_lease_set(fd, ioc);
11294         /**
11295          * llapi_lease_set returns lease mode when it request to unlock
11296          * the lease lock.
11297          */
11298         if (rc2 <= 0) {
11299                 /* rc2 == 0 means lost lease lock */
11300                 if (rc2 == 0 && rc == 0)
11301                         rc = -EBUSY;
11302                 else
11303                         rc = rc2;
11304                 fprintf(stderr, "%s: resync file '%s' failed: %s.\n",
11305                         progname, fname,
11306                         rc2 == 0 ? "lost lease lock" : strerror(-rc2));
11307
11308                 llapi_lease_release(fd);
11309                 goto free_layout;
11310         }
11311
11312 free_layout:
11313         llapi_layout_free(layout);
11314 close_fd:
11315         close(fd);
11316 error:
11317         return rc;
11318 }
11319
11320 static inline int lfs_mirror_resync(int argc, char **argv)
11321 {
11322         struct option long_opts[] = {
11323         { .val = 'h',   .name = "help",         .has_arg = no_argument },
11324         { .val = 'o',   .name = "only",         .has_arg = required_argument },
11325         { .name = NULL } };
11326         struct ll_ioc_lease *ioc = NULL;
11327         __u16 mirror_ids[128] = { 0 };
11328         int ids_nr = 0;
11329         int c;
11330         int rc = 0;
11331
11332         while ((c = getopt_long(argc, argv, "ho:", long_opts, NULL)) >= 0) {
11333                 switch (c) {
11334                 case 'o':
11335                         rc = parse_mirror_ids(mirror_ids,
11336                                         sizeof(mirror_ids) / sizeof(__u16),
11337                                         optarg);
11338                         if (rc < 0) {
11339                                 fprintf(stderr,
11340                                         "%s: bad mirror ids '%s'.\n",
11341                                         argv[0], optarg);
11342                                 goto error;
11343                         }
11344                         ids_nr = rc;
11345                         break;
11346                 default:
11347                         fprintf(stderr, "%s: unrecognized option '%s'\n",
11348                                 progname, argv[optind - 1]);
11349                         fallthrough;
11350                 case 'h':
11351                         rc = CMD_HELP;
11352                         goto error;
11353                 }
11354         }
11355
11356         if (argc == optind) {
11357                 fprintf(stderr, "%s: no file name given.\n", argv[0]);
11358                 rc = CMD_HELP;
11359                 goto error;
11360         }
11361
11362         if (ids_nr > 0 && argc > optind + 1) {
11363                 fprintf(stderr,
11364                     "%s: option '--only' cannot be used upon multiple files.\n",
11365                         argv[0]);
11366                 rc = CMD_HELP;
11367                 goto error;
11368         }
11369
11370         if (ids_nr > 0) {
11371                 rc = verify_mirror_ids(argv[optind], mirror_ids, ids_nr);
11372                 if (rc < 0)
11373                         goto error;
11374         }
11375
11376         /* set the lease on the file */
11377         ioc = calloc(sizeof(*ioc) + sizeof(__u32) * 4096, 1);
11378         if (!ioc) {
11379                 fprintf(stderr, "%s: cannot alloc id array for ioc: %s.\n",
11380                         argv[0], strerror(errno));
11381                 rc = -errno;
11382                 goto error;
11383         }
11384
11385         for (; optind < argc; optind++) {
11386                 rc = lfs_mirror_resync_file(argv[optind], ioc,
11387                                             mirror_ids, ids_nr);
11388                 /* ignore previous file's error, continue with next file */
11389
11390                 /* reset ioc */
11391                 memset(ioc, 0, sizeof(*ioc) + sizeof(__u32) * 4096);
11392         }
11393
11394         free(ioc);
11395 error:
11396         return rc;
11397 }
11398
11399 static inline int verify_mirror_id_by_fd(int fd, __u16 mirror_id)
11400 {
11401         struct llapi_layout *layout;
11402         int rc;
11403
11404         layout = llapi_layout_get_by_fd(fd, 0);
11405         if (!layout) {
11406                 fprintf(stderr, "could not get layout.\n");
11407                 return  -EINVAL;
11408         }
11409
11410         rc = llapi_layout_comp_iterate(layout, find_mirror_id, &mirror_id);
11411         if (rc < 0) {
11412                 fprintf(stderr, "failed to iterate layout\n");
11413                 llapi_layout_free(layout);
11414
11415                 return rc;
11416         } else if (rc == LLAPI_LAYOUT_ITER_CONT) {
11417                 fprintf(stderr, "does not find mirror with ID %u\n", mirror_id);
11418                 llapi_layout_free(layout);
11419
11420                 return -EINVAL;
11421         }
11422         llapi_layout_free(layout);
11423
11424         return 0;
11425 }
11426
11427 /**
11428  * Check whether two files are the same file
11429  * \retval      0  same file
11430  * \retval      1  not the same file
11431  * \retval      <0 error code
11432  */
11433 static inline int check_same_file(int fd, const char *f2)
11434 {
11435         struct stat stbuf1;
11436         struct stat stbuf2;
11437
11438         if (fstat(fd, &stbuf1) < 0)
11439                 return -errno;
11440
11441         if (stat(f2, &stbuf2) < 0)
11442                 return 1;
11443
11444         if (stbuf1.st_rdev == stbuf2.st_rdev &&
11445             stbuf1.st_ino == stbuf2.st_ino)
11446                 return 0;
11447
11448         return 1;
11449 }
11450
11451 static inline int lfs_mirror_read(int argc, char **argv)
11452 {
11453         int rc = CMD_HELP;
11454         __u16 mirror_id = 0;
11455         const char *outfile = NULL;
11456         char *fname;
11457         int fd = 0;
11458         int outfd;
11459         int c;
11460         void *buf;
11461         const size_t buflen = 4 << 20;
11462         off_t pos;
11463         struct option long_opts[] = {
11464         { .val = 'h',   .name = "help",         .has_arg = no_argument },
11465         { .val = 'N',   .name = "mirror-id",    .has_arg = required_argument },
11466         { .val = 'o',   .name = "outfile",      .has_arg = required_argument },
11467         { .name = NULL } };
11468
11469         while ((c = getopt_long(argc, argv, "hN:o:", long_opts, NULL)) >= 0) {
11470                 char *end;
11471
11472                 switch (c) {
11473                 case 'N': {
11474                         unsigned long int id;
11475
11476                         errno = 0;
11477                         id = strtoul(optarg, &end, 0);
11478                         if (errno != 0 || *end != '\0' || id == 0 ||
11479                             id > UINT16_MAX) {
11480                                 fprintf(stderr,
11481                                         "%s %s: invalid mirror ID '%s'\n",
11482                                         progname, argv[0], optarg);
11483                                 return rc;
11484                         }
11485
11486                         mirror_id = (__u16)id;
11487                         break;
11488                 }
11489                 case 'o':
11490                         outfile = optarg;
11491                         break;
11492                 default:
11493                         fprintf(stderr, "%s: unrecognized option '%s'\n",
11494                                 progname, argv[optind - 1]);
11495                         fallthrough;
11496                 case 'h':
11497                         return CMD_HELP;
11498                 }
11499         }
11500
11501         if (argc == optind) {
11502                 fprintf(stderr, "%s %s: no mirrored file provided\n",
11503                         progname, argv[0]);
11504                 return rc;
11505         } else if (argc > optind + 1) {
11506                 fprintf(stderr, "%s %s: too many files\n", progname, argv[0]);
11507                 return rc;
11508         }
11509
11510         if (mirror_id == 0) {
11511                 fprintf(stderr, "%s %s: no valid mirror ID is provided\n",
11512                         progname, argv[0]);
11513                 return rc;
11514         }
11515
11516         /* open mirror file */
11517         fname = argv[optind];
11518         fd = open(fname, O_DIRECT | O_RDONLY);
11519         if (fd < 0) {
11520                 fprintf(stderr, "%s %s: cannot open '%s': %s\n",
11521                         progname, argv[0], fname, strerror(errno));
11522                 return rc;
11523         }
11524
11525         /* verify mirror id */
11526         rc = verify_mirror_id_by_fd(fd, mirror_id);
11527         if (rc) {
11528                 fprintf(stderr,
11529                         "%s %s: cannot find mirror with ID %u in '%s'\n",
11530                         progname, argv[0], mirror_id, fname);
11531                 goto close_fd;
11532         }
11533
11534         /* open output file - O_EXCL ensures output is not the same as input */
11535         if (outfile) {
11536                 outfd = open(outfile, O_EXCL | O_WRONLY | O_CREAT, 0644);
11537                 if (outfd < 0) {
11538                         fprintf(stderr, "%s %s: cannot create file '%s': %s\n",
11539                                 progname, argv[0], outfile, strerror(errno));
11540                         rc = -errno;
11541                         goto close_fd;
11542                 }
11543         } else {
11544                 outfd = STDOUT_FILENO;
11545         }
11546
11547         /* allocate buffer */
11548         rc = posix_memalign(&buf, sysconf(_SC_PAGESIZE), buflen);
11549         if (rc) {
11550                 fprintf(stderr, "%s %s: posix_memalign returns %d\n",
11551                                 progname, argv[0], rc);
11552                 goto close_outfd;
11553         }
11554
11555         pos = 0;
11556         while (1) {
11557                 ssize_t bytes_read;
11558                 ssize_t written = 0;
11559
11560                 bytes_read = llapi_mirror_read(fd, mirror_id, buf, buflen, pos);
11561                 if (bytes_read < 0) {
11562                         rc = bytes_read;
11563                         fprintf(stderr,
11564                                 "%s %s: fail to read data from mirror %u: %s\n",
11565                                 progname, argv[0], mirror_id, strerror(-rc));
11566                         goto free_buf;
11567                 }
11568
11569                 /* EOF reached */
11570                 if (bytes_read == 0)
11571                         break;
11572
11573                 while (written < bytes_read) {
11574                         ssize_t written2;
11575
11576                         written2 = write(outfd, buf + written,
11577                                          bytes_read - written);
11578                         if (written2 < 0) {
11579                                 fprintf(stderr,
11580                                         "%s %s: fail to write %s: %s\n",
11581                                         progname, argv[0], outfile ? : "STDOUT",
11582                                         strerror(errno));
11583                                 rc = -errno;
11584                                 goto free_buf;
11585                         }
11586                         written += written2;
11587                 }
11588
11589                 if (written != bytes_read) {
11590                         fprintf(stderr,
11591                 "%s %s: written %ld bytes does not match with %ld read.\n",
11592                                 progname, argv[0], written, bytes_read);
11593                         rc = -EIO;
11594                         goto free_buf;
11595                 }
11596
11597                 pos += bytes_read;
11598         }
11599
11600         fsync(outfd);
11601         rc = 0;
11602
11603 free_buf:
11604         free(buf);
11605 close_outfd:
11606         if (outfile)
11607                 close(outfd);
11608 close_fd:
11609         close(fd);
11610
11611         return rc;
11612 }
11613
11614 static inline int lfs_mirror_write(int argc, char **argv)
11615 {
11616         int rc = CMD_HELP;
11617         __u16 mirror_id = 0;
11618         const char *inputfile = NULL;
11619         char *fname;
11620         int fd = 0;
11621         int inputfd;
11622         int c;
11623         void *buf;
11624         const size_t buflen = 4 << 20;
11625         off_t pos;
11626         size_t page_size = sysconf(_SC_PAGESIZE);
11627         struct ll_ioc_lease_id ioc;
11628         struct option long_opts[] = {
11629         { .val = 'h',   .name = "help",         .has_arg = no_argument },
11630         { .val = 'i',   .name = "inputfile",    .has_arg = required_argument },
11631         { .val = 'N',   .name = "mirror-id",    .has_arg = required_argument },
11632         { .name = NULL } };
11633
11634         while ((c = getopt_long(argc, argv, "hi:N:", long_opts, NULL)) >= 0) {
11635                 char *end;
11636
11637                 switch (c) {
11638                 case 'N': {
11639                         unsigned long int id;
11640
11641                         errno = 0;
11642                         id = strtoul(optarg, &end, 0);
11643                         if (errno != 0 || *end != '\0' || id == 0 ||
11644                             id > UINT16_MAX) {
11645                                 fprintf(stderr,
11646                                         "%s %s: invalid mirror ID '%s'\n",
11647                                         progname, argv[0], optarg);
11648                                 return rc;
11649                         }
11650
11651                         mirror_id = (__u16)id;
11652                         break;
11653                 }
11654                 case 'i':
11655                         inputfile = optarg;
11656                         break;
11657                 default:
11658                         fprintf(stderr, "%s: unrecognized option '%s'\n",
11659                                 progname, argv[optind - 1]);
11660                         fallthrough;
11661                 case 'h':
11662                         return CMD_HELP;
11663                 }
11664         }
11665
11666         if (argc == optind) {
11667                 fprintf(stderr, "%s %s: no mirrored file provided\n",
11668                         progname, argv[0]);
11669                 return rc;
11670         } else if (argc > optind + 1) {
11671                 fprintf(stderr, "%s %s: too many files\n", progname, argv[0]);
11672                 return rc;
11673         }
11674
11675         if (mirror_id == 0) {
11676                 fprintf(stderr, "%s %s: no valid mirror ID is provided\n",
11677                         progname, argv[0]);
11678                 return rc;
11679         }
11680
11681         /* open mirror file */
11682         fname = argv[optind];
11683         fd = open(fname, O_DIRECT | O_WRONLY);
11684         if (fd < 0) {
11685                 fprintf(stderr, "%s %s: cannot open '%s': %s\n",
11686                         progname, argv[0], fname, strerror(errno));
11687                 return rc;
11688         }
11689
11690         /* verify mirror id */
11691         rc = verify_mirror_id_by_fd(fd, mirror_id);
11692         if (rc) {
11693                 fprintf(stderr,
11694                         "%s %s: cannot find mirror with ID %u in '%s'\n",
11695                         progname, argv[0], mirror_id, fname);
11696                 goto close_fd;
11697         }
11698
11699         /* open input file */
11700         if (inputfile) {
11701                 rc = check_same_file(fd, inputfile);
11702                 if (rc == 0) {
11703                         fprintf(stderr,
11704                         "%s %s: input file cannot be the mirrored file '%s'\n",
11705                                 progname, argv[0], fname);
11706                         goto close_fd;
11707                 }
11708                 if (rc < 0)
11709                         goto close_fd;
11710
11711                 inputfd = open(inputfile, O_RDONLY, 0644);
11712                 if (inputfd < 0) {
11713                         fprintf(stderr, "%s %s: cannot open file '%s': %s\n",
11714                                 progname, argv[0], inputfile, strerror(errno));
11715                         rc = -errno;
11716                         goto close_fd;
11717                 }
11718         } else {
11719                 inputfd = STDIN_FILENO;
11720         }
11721
11722         /* allocate buffer */
11723         rc = posix_memalign(&buf, page_size, buflen);
11724         if (rc) {
11725                 fprintf(stderr, "%s %s: posix_memalign returns %d\n",
11726                         progname, argv[0], rc);
11727                 goto close_inputfd;
11728         }
11729
11730         /* prepare target mirror components instantiation */
11731         ioc.lil_mode = LL_LEASE_WRLCK;
11732         ioc.lil_flags = LL_LEASE_RESYNC;
11733         ioc.lil_mirror_id = mirror_id;
11734         rc = llapi_lease_set(fd, (struct ll_ioc_lease *)&ioc);
11735         if (rc < 0) {
11736                 fprintf(stderr,
11737                         "%s %s: '%s' llapi_lease_get_ext failed: %s\n",
11738                         progname, argv[0], fname, strerror(errno));
11739                 goto free_buf;
11740         }
11741
11742         pos = 0;
11743         while (1) {
11744                 ssize_t bytes_read;
11745                 ssize_t written;
11746                 size_t to_write;
11747
11748                 rc = llapi_lease_check(fd);
11749                 if (rc != LL_LEASE_WRLCK) {
11750                         fprintf(stderr, "%s %s: '%s' lost lease lock\n",
11751                                 progname, argv[0], fname);
11752                         goto free_buf;
11753                 }
11754
11755                 bytes_read = read(inputfd, buf, buflen);
11756                 if (bytes_read < 0) {
11757                         rc = bytes_read;
11758                         fprintf(stderr,
11759                                 "%s %s: fail to read data from '%s': %s\n",
11760                                 progname, argv[0], inputfile ? : "STDIN",
11761                                 strerror(errno));
11762                         rc = -errno;
11763                         goto free_buf;
11764                 }
11765
11766                 /* EOF reached */
11767                 if (bytes_read == 0)
11768                         break;
11769
11770                 /* round up to page align to make direct IO happy. */
11771                 to_write = (bytes_read + page_size - 1) & ~(page_size - 1);
11772
11773                 written = llapi_mirror_write(fd, mirror_id, buf, to_write,
11774                                              pos);
11775                 if (written < 0) {
11776                         rc = written;
11777                         fprintf(stderr,
11778                               "%s %s: fail to write to mirror %u: %s\n",
11779                                 progname, argv[0], mirror_id,
11780                                 strerror(-rc));
11781                         goto free_buf;
11782                 }
11783
11784                 pos += bytes_read;
11785         }
11786
11787         if (pos & (page_size - 1)) {
11788                 rc = llapi_mirror_truncate(fd, mirror_id, pos);
11789                 if (rc < 0)
11790                         goto free_buf;
11791         }
11792
11793         ioc.lil_mode = LL_LEASE_UNLCK;
11794         ioc.lil_flags = LL_LEASE_RESYNC_DONE;
11795         ioc.lil_count = 0;
11796         rc = llapi_lease_set(fd, (struct ll_ioc_lease *)&ioc);
11797         if (rc <= 0) {
11798                 if (rc == 0)
11799                         rc = -EBUSY;
11800                 fprintf(stderr,
11801                         "%s %s: release lease lock of '%s' failed: %s\n",
11802                         progname, argv[0], fname, strerror(-rc));
11803                 goto free_buf;
11804         }
11805
11806         rc = 0;
11807
11808 free_buf:
11809         free(buf);
11810 close_inputfd:
11811         if (inputfile)
11812                 close(inputfd);
11813 close_fd:
11814         close(fd);
11815
11816         return rc;
11817 }
11818
11819 static inline int get_other_mirror_ids(int fd, __u16 *ids, __u16 exclude_id)
11820 {
11821         struct llapi_layout *layout;
11822         struct collect_ids_data cid = { .cid_ids = ids,
11823                                         .cid_count = 0,
11824                                         .cid_exclude = exclude_id, };
11825         int rc;
11826
11827         layout = llapi_layout_get_by_fd(fd, 0);
11828         if (!layout) {
11829                 fprintf(stderr, "could not get layout\n");
11830                 return -EINVAL;
11831         }
11832
11833         rc = llapi_layout_comp_iterate(layout, collect_mirror_id, &cid);
11834         if (rc < 0) {
11835                 fprintf(stderr, "failed to iterate layout\n");
11836                 llapi_layout_free(layout);
11837
11838                 return rc;
11839         }
11840         llapi_layout_free(layout);
11841
11842         return cid.cid_count;
11843 }
11844
11845 #ifndef MIRROR_ID_NEG
11846 #define MIRROR_ID_NEG         0x8000
11847 #endif
11848
11849 static inline int lfs_mirror_copy(int argc, char **argv)
11850 {
11851         int rc = CMD_HELP;
11852         __u16 read_mirror_id = 0;
11853         __u16 ids[128] = { 0 };
11854         int count = 0;
11855         struct llapi_layout *layout = NULL;
11856         struct llapi_resync_comp comp_array[1024] = { { 0 } };
11857         int comp_size = 0;
11858         char *fname;
11859         int fd = 0;
11860         int c;
11861         int i;
11862         ssize_t copied;
11863         struct ll_ioc_lease *ioc = NULL;
11864         struct ll_ioc_lease_id *resync_ioc;
11865         struct option long_opts[] = {
11866         { .val = 'h',   .name = "help",         .has_arg = no_argument },
11867         { .val = 'i',   .name = "read-mirror",  .has_arg = required_argument },
11868         { .val = 'o',   .name = "write-mirror", .has_arg = required_argument },
11869         { .name = NULL } };
11870         char cmd[PATH_MAX];
11871
11872         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
11873         progname = cmd;
11874         while ((c = getopt_long(argc, argv, "hi:o:", long_opts, NULL)) >= 0) {
11875                 char *end;
11876
11877                 switch (c) {
11878                 case 'i': {
11879                         unsigned long int id;
11880
11881                         errno = 0;
11882                         id = strtoul(optarg, &end, 0);
11883                         if (errno != 0 || *end != '\0' || id == 0 ||
11884                             id > UINT16_MAX) {
11885                                 fprintf(stderr,
11886                                         "%s: invalid read mirror ID '%s'\n",
11887                                         progname, optarg);
11888                                 return rc;
11889                         }
11890
11891                         read_mirror_id = (__u16)id;
11892                         break;
11893                 }
11894                 case 'o':
11895                         if (!strcmp(optarg, "-1")) {
11896                                 /* specify all other mirrors */
11897                                 ids[0] = (__u16)-1;
11898                                 count = 1;
11899                         } else {
11900                                 count = parse_mirror_ids((__u16 *)ids,
11901                                                          ARRAY_SIZE(ids),
11902                                                          optarg);
11903                                 if (count < 0)
11904                                         return rc;
11905                         }
11906                         break;
11907                 default:
11908                         fprintf(stderr, "%s: unrecognized option '%s'\n",
11909                                 progname, argv[optind - 1]);
11910                         fallthrough;
11911                 case 'h':
11912                         return CMD_HELP;
11913                 }
11914         }
11915
11916         if (argc == optind) {
11917                 fprintf(stderr, "%s %s: no mirrored file provided\n",
11918                         progname, argv[0]);
11919                 return rc;
11920         } else if (argc > optind + 1) {
11921                 fprintf(stderr, "%s %s: too many files\n", progname, argv[0]);
11922                 return rc;
11923         }
11924
11925         if (read_mirror_id == 0) {
11926                 fprintf(stderr,
11927                         "%s %s: no valid read mirror ID %d is provided\n",
11928                         progname, argv[0], read_mirror_id);
11929                 return rc;
11930         }
11931
11932         if (count == 0) {
11933                 fprintf(stderr,
11934                         "%s %s: no write mirror ID is provided\n",
11935                         progname, argv[0]);
11936                 return rc;
11937         }
11938
11939         for (i = 0; i < count; i++) {
11940                 if (read_mirror_id == ids[i]) {
11941                         fprintf(stderr,
11942                         "%s %s: read and write mirror ID cannot be the same\n",
11943                                 progname, argv[0]);
11944                         return rc;
11945                 }
11946         }
11947
11948         /* open mirror file */
11949         fname = argv[optind];
11950
11951         fd = open(fname, O_DIRECT | O_RDWR);
11952         if (fd < 0) {
11953                 fprintf(stderr, "%s %s: cannot open '%s': %s\n",
11954                         progname, argv[0], fname, strerror(errno));
11955                 return rc;
11956         }
11957
11958         /* write to all other mirrors */
11959         if (ids[0] == (__u16)-1) {
11960                 count = get_other_mirror_ids(fd, ids, read_mirror_id);
11961                 if (count <= 0) {
11962                         rc = count;
11963                         fprintf(stderr,
11964                         "%s %s: failed to get other mirror ids in '%s': %d\n",
11965                                 progname, argv[0], fname, rc);
11966                         goto close_fd;
11967                 }
11968         }
11969
11970         /* verify mirror id */
11971         rc = verify_mirror_id_by_fd(fd, read_mirror_id);
11972         if (rc) {
11973                 fprintf(stderr,
11974                         "%s %s: cannot find mirror with ID %u in '%s'\n",
11975                         progname, argv[0], read_mirror_id, fname);
11976                 goto close_fd;
11977         }
11978
11979         for (i = 0; i < count; i++) {
11980                 rc = verify_mirror_id_by_fd(fd, ids[i]);
11981                 if (rc) {
11982                         fprintf(stderr,
11983                         "%s %s: cannot find mirror with ID %u in '%s'\n",
11984                                 progname, argv[0], ids[i], fname);
11985                         goto close_fd;
11986                 }
11987         }
11988
11989         ioc = calloc(sizeof(*ioc) + sizeof(__u32) * 4096, 1);
11990         if (!ioc) {
11991                 fprintf(stderr,
11992                         "%s %s: cannot alloc comp id array for ioc: %s\n",
11993                         progname, argv[0], strerror(errno));
11994                 rc = -errno;
11995                 goto close_fd;
11996         }
11997
11998         /* get stale component info */
11999         layout = llapi_layout_get_by_fd(fd, 0);
12000         if (!layout) {
12001                 fprintf(stderr, "%s %s: failed to get layout of '%s': %s\n",
12002                         progname, argv[0], fname, strerror(errno));
12003                 rc = -errno;
12004                 goto free_ioc;
12005         }
12006         comp_size = llapi_mirror_find_stale(layout, comp_array,
12007                                             ARRAY_SIZE(comp_array),
12008                                             ids, count);
12009         llapi_layout_free(layout);
12010         if (comp_size < 0) {
12011                 rc = comp_size;
12012                 goto free_ioc;
12013         }
12014
12015         /* prepare target mirror components instantiation */
12016         resync_ioc = (struct ll_ioc_lease_id *)ioc;
12017         resync_ioc->lil_mode = LL_LEASE_WRLCK;
12018         resync_ioc->lil_flags = LL_LEASE_RESYNC;
12019         if (count == 1)
12020                 resync_ioc->lil_mirror_id = ids[0];
12021         else
12022                 resync_ioc->lil_mirror_id = read_mirror_id | MIRROR_ID_NEG;
12023         rc = llapi_lease_set(fd, ioc);
12024         if (rc < 0) {
12025                 fprintf(stderr,
12026                         "%s %s: '%s' llapi_lease_get_ext failed: %s\n",
12027                         progname, argv[0], fname, strerror(errno));
12028                 goto free_ioc;
12029         }
12030
12031         copied = llapi_mirror_copy_many(fd, read_mirror_id, ids, count);
12032         if (copied < 0) {
12033                 rc = copied;
12034                 fprintf(stderr, "%s %s: copy error: %d\n",
12035                         progname, argv[0], rc);
12036                 goto free_ioc;
12037         }
12038
12039         fprintf(stdout, "mirror copied successfully: ");
12040         for (i = 0; i < copied; i++)
12041                 fprintf(stdout, "%d ", ids[i]);
12042         fprintf(stdout, "\n");
12043
12044         ioc->lil_mode = LL_LEASE_UNLCK;
12045         ioc->lil_flags = LL_LEASE_RESYNC_DONE;
12046         ioc->lil_count = 0;
12047         for (i = 0; i < comp_size; i++) {
12048                 int j;
12049
12050                 for (j = 0; j < copied; j++) {
12051                         if (comp_array[i].lrc_mirror_id != ids[j])
12052                                 continue;
12053
12054                         ioc->lil_ids[ioc->lil_count] = comp_array[i].lrc_id;
12055                         ioc->lil_count++;
12056                 }
12057         }
12058         rc = llapi_lease_set(fd, ioc);
12059         if (rc <= 0) {
12060                 if (rc == 0)
12061                         rc = -EBUSY;
12062                 fprintf(stderr,
12063                         "%s %s: release lease lock of '%s' failed: %s\n",
12064                         progname, argv[0], fname, strerror(errno));
12065                 goto free_ioc;
12066         }
12067
12068         rc = 0;
12069
12070 free_ioc:
12071         free(ioc);
12072 close_fd:
12073         close(fd);
12074
12075         return rc;
12076 }
12077
12078 /**
12079  * struct verify_chunk - Mirror chunk to be verified.
12080  * @chunk:        [start, end) of the chunk.
12081  * @mirror_count: Number of mirror ids in @mirror_id array.
12082  * @mirror_id:    Array of valid mirror ids that cover the chunk.
12083  */
12084 struct verify_chunk {
12085         struct lu_extent chunk;
12086         unsigned int mirror_count;
12087         __u16 mirror_id[LUSTRE_MIRROR_COUNT_MAX];
12088 };
12089
12090 /**
12091  * print_chunks() - Print chunk information.
12092  * @fname:       Mirrored file name.
12093  * @chunks:      Array of chunks.
12094  * @chunk_count: Number of chunks in @chunks array.
12095  *
12096  * This function prints [start, end) of each chunk in @chunks
12097  * for mirrored file @fname, and also prints the valid mirror ids
12098  * that cover the chunk.
12099  *
12100  * Return: void.
12101  */
12102 static inline
12103 void print_chunks(const char *fname, struct verify_chunk *chunks,
12104                   int chunk_count)
12105 {
12106         int i;
12107         int j;
12108
12109         fprintf(stdout, "Chunks to be verified in %s:\n", fname);
12110         for (i = 0; i < chunk_count; i++) {
12111                 fprintf(stdout, DEXT, PEXT(&chunks[i].chunk));
12112
12113                 if (chunks[i].mirror_count == 0)
12114                         fprintf(stdout, "\t[");
12115                 else {
12116                         fprintf(stdout, "\t[%u", chunks[i].mirror_id[0]);
12117                         for (j = 1; j < chunks[i].mirror_count; j++)
12118                                 fprintf(stdout, ", %u", chunks[i].mirror_id[j]);
12119                 }
12120                 fprintf(stdout, "]\t%u\n", chunks[i].mirror_count);
12121         }
12122         fprintf(stdout, "\n");
12123 }
12124
12125 /**
12126  * print_checksums() - Print CRC-32 checksum values.
12127  * @chunk: A chunk and its corresponding valid mirror ids.
12128  * @crc:   CRC-32 checksum values on the chunk for each valid mirror.
12129  *
12130  * This function prints CRC-32 checksum values on @chunk for
12131  * each valid mirror that covers it.
12132  *
12133  * Return: void.
12134  */
12135 static inline
12136 void print_checksums(struct verify_chunk *chunk, unsigned long *crc,
12137                      unsigned long long pos, unsigned long long len)
12138 {
12139         int i;
12140
12141         fprintf(stdout,
12142                 "CRC-32 checksum value for chunk "DEXT":\n", pos, pos + len);
12143         for (i = 0; i < chunk->mirror_count; i++)
12144                 fprintf(stdout, "Mirror %u:\t%#lx\n",
12145                         chunk->mirror_id[i], crc[i]);
12146         fprintf(stdout, "\n");
12147 }
12148
12149 /**
12150  * filter_mirror_id() - Filter specified mirror ids.
12151  * @chunks:      Array of chunks.
12152  * @chunk_count: Number of chunks in @chunks array.
12153  * @mirror_ids:  Specified mirror ids to be verified.
12154  * @ids_nr:      Number of specified mirror ids.
12155  *
12156  * This function scans valid mirror ids that cover each chunk in @chunks
12157  * and filters specified mirror ids.
12158  *
12159  * Return: void.
12160  */
12161 static inline
12162 void filter_mirror_id(struct verify_chunk *chunks, int chunk_count,
12163                       __u16 *mirror_ids, int ids_nr)
12164 {
12165         int i;
12166         int j;
12167         int k;
12168         __u16 valid_id[LUSTRE_MIRROR_COUNT_MAX] = { 0 };
12169         unsigned int valid_count = 0;
12170
12171         for (i = 0; i < chunk_count; i++) {
12172                 if (chunks[i].mirror_count == 0)
12173                         continue;
12174
12175                 valid_count = 0;
12176                 for (j = 0; j < ids_nr; j++) {
12177                         for (k = 0; k < chunks[i].mirror_count; k++) {
12178                                 if (chunks[i].mirror_id[k] == mirror_ids[j]) {
12179                                         valid_id[valid_count] = mirror_ids[j];
12180                                         valid_count++;
12181                                         break;
12182                                 }
12183                         }
12184                 }
12185
12186                 memcpy(chunks[i].mirror_id, valid_id,
12187                        sizeof(__u16) * valid_count);
12188                 chunks[i].mirror_count = valid_count;
12189         }
12190 }
12191
12192 /**
12193  * lfs_mirror_prepare_chunk() - Find mirror chunks to be verified.
12194  * @layout:      Mirror component list.
12195  * @chunks:      Array of chunks.
12196  * @chunks_size: Array size of @chunks.
12197  *
12198  * This function scans the components in @layout from offset 0 to LUSTRE_EOF
12199  * to find out chunk segments and store them in @chunks array.
12200  *
12201  * The @mirror_id array in each element of @chunks will store the valid
12202  * mirror ids that cover the chunk. If a mirror component covering the
12203  * chunk has LCME_FL_STALE or LCME_FL_OFFLINE flag, then the mirror id
12204  * will not be stored into the @mirror_id array, and the chunk for that
12205  * mirror will not be verified.
12206  *
12207  * The @mirror_count in each element of @chunks will store the number of
12208  * mirror ids in @mirror_id array. If @mirror_count is 0, it indicates the
12209  * chunk is invalid in all of the mirrors. And if @mirror_count is 1, it
12210  * indicates the chunk is valid in only one mirror. In both cases, the
12211  * chunk will not be verified.
12212  *
12213  * Here is an example:
12214  *
12215  *  0      1M     2M     3M     4M           EOF
12216  *  +------+-------------+--------------------+
12217  *  |      |             |      S             |       mirror1
12218  *  +------+------+------+------+-------------+
12219  *  |             |   S  |   S  |             |       mirror2
12220  *  +-------------+------+------+-------------+
12221  *
12222  * prepared @chunks array will contain 5 elements:
12223  * (([0, 1M), [1, 2], 2),
12224  *  ([1M, 2M), [1, 2], 2),
12225  *  ([2M, 3M), [1], 1),
12226  *  ([3M, 4M], [], 0),
12227  *  ([4M, EOF), [2], 1))
12228  *
12229  * Return: the actual array size of @chunks on success
12230  *         or a negative error code on failure.
12231  */
12232 static inline
12233 int lfs_mirror_prepare_chunk(struct llapi_layout *layout,
12234                              struct verify_chunk *chunks,
12235                              size_t chunks_size)
12236 {
12237         uint64_t start;
12238         uint64_t end;
12239         uint32_t mirror_id;
12240         uint32_t flags;
12241         int idx = 0;
12242         int i = 0;
12243         int rc = 0;
12244
12245         memset(chunks, 0, sizeof(*chunks) * chunks_size);
12246
12247         while (1) {
12248                 rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_FIRST);
12249                 if (rc < 0) {
12250                         fprintf(stderr,
12251                                 "%s: move to the first layout component: %s.\n",
12252                                 progname, strerror(errno));
12253                         goto error;
12254                 }
12255
12256                 i = 0;
12257                 rc = 0;
12258                 chunks[idx].chunk.e_end = LUSTRE_EOF;
12259                 while (rc == 0) {
12260                         rc = llapi_layout_comp_extent_get(layout, &start, &end);
12261                         if (rc < 0) {
12262                                 fprintf(stderr,
12263                                         "%s: llapi_layout_comp_extent_get failed: %s.\n",
12264                                         progname, strerror(errno));
12265                                 goto error;
12266                         }
12267
12268                         if (start > chunks[idx].chunk.e_start ||
12269                             end <= chunks[idx].chunk.e_start)
12270                                 goto next;
12271
12272                         if (end < chunks[idx].chunk.e_end)
12273                                 chunks[idx].chunk.e_end = end;
12274
12275                         rc = llapi_layout_comp_flags_get(layout, &flags);
12276                         if (rc < 0) {
12277                                 fprintf(stderr,
12278                                         "%s: llapi_layout_comp_flags_get failed: %s.\n",
12279                                         progname, strerror(errno));
12280                                 goto error;
12281                         }
12282
12283                         if (flags & LCME_FL_STALE || flags & LCME_FL_OFFLINE)
12284                                 goto next;
12285
12286                         rc = llapi_layout_mirror_id_get(layout, &mirror_id);
12287                         if (rc < 0) {
12288                                 fprintf(stderr,
12289                                         "%s: llapi_layout_mirror_id_get failed: %s.\n",
12290                                         progname, strerror(errno));
12291                                 goto error;
12292                         }
12293
12294                         if (i >= ARRAY_SIZE(chunks[idx].mirror_id)) {
12295                                 fprintf(stderr,
12296                                         "%s: mirror_id array is too small.\n",
12297                                         progname);
12298                                 rc = -EINVAL;
12299                                 goto error;
12300                         }
12301                         chunks[idx].mirror_id[i] = mirror_id;
12302                         i++;
12303
12304 next:
12305                         rc = llapi_layout_comp_use(layout,
12306                                                    LLAPI_LAYOUT_COMP_USE_NEXT);
12307                         if (rc < 0) {
12308                                 fprintf(stderr,
12309                                         "%s: move to the next layout component: %s.\n",
12310                                         progname, strerror(errno));
12311                                 goto error;
12312                         }
12313                 } /* loop through all components */
12314
12315                 chunks[idx].mirror_count = i;
12316
12317                 if (chunks[idx].chunk.e_end == LUSTRE_EOF)
12318                         break;
12319
12320                 idx++;
12321                 if (idx >= chunks_size) {
12322                         fprintf(stderr, "%s: chunks array is too small.\n",
12323                                 progname);
12324                         rc = -EINVAL;
12325                         goto error;
12326                 }
12327
12328                 chunks[idx].chunk.e_start = chunks[idx - 1].chunk.e_end;
12329         }
12330
12331 error:
12332         return rc < 0 ? rc : idx + 1;
12333 }
12334
12335 /**
12336  * lfs_mirror_verify_chunk() - Verify a chunk.
12337  * @fd:        File descriptor of the mirrored file.
12338  * @file_size: Size of the mirrored file.
12339  * @chunk:     A chunk and its corresponding valid mirror ids.
12340  * @verbose:   Verbose mode.
12341  *
12342  * This function verifies a @chunk contains exactly the same data
12343  * ammong the mirrors that cover it.
12344  *
12345  * If @verbose is specified, then the function will print where the
12346  * differences are if the data do not match. Otherwise, it will
12347  * just return an error in that case.
12348  *
12349  * Return: 0 on success or a negative error code on failure.
12350  */
12351 static inline
12352 int lfs_mirror_verify_chunk(int fd, size_t file_size,
12353                             struct verify_chunk *chunk, int verbose)
12354 {
12355         const size_t buflen = 4 * 1024 * 1024; /* 4M */
12356         void *buf;
12357         size_t page_size = sysconf(_SC_PAGESIZE);
12358         ssize_t bytes_read;
12359         ssize_t bytes_done;
12360         size_t count;
12361         off_t pos;
12362         unsigned long crc;
12363         unsigned long crc_array[LUSTRE_MIRROR_COUNT_MAX] = { 0 };
12364         int i;
12365         int rc = 0;
12366
12367         if (file_size == 0)
12368                 return 0;
12369
12370         rc = posix_memalign(&buf, page_size, buflen);
12371         if (rc) /* error code is returned directly */
12372                 return -rc;
12373
12374         if (verbose > 1) {
12375                 fprintf(stdout, "Verifying chunk "DEXT" on mirror:",
12376                         PEXT(&chunk->chunk));
12377                 for (i = 0; i < chunk->mirror_count; i++)
12378                         fprintf(stdout, " %u", chunk->mirror_id[i]);
12379                 fprintf(stdout, "\n");
12380         }
12381
12382         bytes_done = 0;
12383         count = MIN(chunk->chunk.e_end, file_size) - chunk->chunk.e_start;
12384         pos = chunk->chunk.e_start;
12385         while (bytes_done < count) {
12386                 /* compute initial CRC-32 checksum */
12387                 crc = crc32(0L, Z_NULL, 0);
12388                 memset(crc_array, 0, sizeof(crc_array));
12389
12390                 bytes_read = 0;
12391                 for (i = 0; i < chunk->mirror_count; i++) {
12392                         bytes_read = llapi_mirror_read(fd, chunk->mirror_id[i],
12393                                                        buf, buflen, pos);
12394                         if (bytes_read < 0) {
12395                                 rc = bytes_read;
12396                                 fprintf(stderr,
12397                                         "%s: failed to read data from mirror %u: %s.\n",
12398                                         progname, chunk->mirror_id[i],
12399                                         strerror(-rc));
12400                                 goto error;
12401                         }
12402
12403                         /* compute new CRC-32 checksum */
12404                         crc_array[i] = crc32(crc, buf, bytes_read);
12405                 }
12406
12407                 if (verbose)
12408                         print_checksums(chunk, crc_array, pos, buflen);
12409
12410                 /* compare CRC-32 checksum values */
12411                 for (i = 1; i < chunk->mirror_count; i++) {
12412                         if (crc_array[i] != crc_array[0]) {
12413                                 rc = -EINVAL;
12414
12415                                 fprintf(stderr,
12416                                         "%s: chunk "DEXT" has different checksum value on mirror %u and mirror %u.\n",
12417                                         progname, PEXT(&chunk->chunk),
12418                                         chunk->mirror_id[0],
12419                                         chunk->mirror_id[i]);
12420                         }
12421                 }
12422
12423                 pos += bytes_read;
12424                 bytes_done += bytes_read;
12425         }
12426
12427         if (verbose > 1 && rc == 0) {
12428                 fprintf(stdout, "Verifying chunk "DEXT" on mirror:",
12429                         PEXT(&chunk->chunk));
12430                 for (i = 0; i < chunk->mirror_count; i++)
12431                         fprintf(stdout, " %u", chunk->mirror_id[i]);
12432                 fprintf(stdout, " PASS\n\n");
12433         }
12434
12435 error:
12436         free(buf);
12437         return rc;
12438 }
12439
12440 /**
12441  * lfs_mirror_verify_file() - Verify a mirrored file.
12442  * @fname:      Mirrored file name.
12443  * @mirror_ids: Specified mirror ids to be verified.
12444  * @ids_nr:     Number of specified mirror ids.
12445  * @verbose:    Verbose mode.
12446  *
12447  * This function verifies that each SYNC mirror of a mirrored file
12448  * specified by @fname contains exactly the same data.
12449  *
12450  * If @mirror_ids is specified, then the function will verify the
12451  * mirrors specified by @mirror_ids contain exactly the same data.
12452  *
12453  * If @verbose is specified, then the function will print where the
12454  * differences are if the data do not match. Otherwise, it will
12455  * just return an error in that case.
12456  *
12457  * Return: 0 on success or a negative error code on failure.
12458  */
12459 static inline
12460 int lfs_mirror_verify_file(const char *fname, __u16 *mirror_ids, int ids_nr,
12461                            int verbose)
12462 {
12463         struct verify_chunk chunks_array[1024] = { };
12464         struct llapi_layout *layout = NULL;
12465         struct stat stbuf;
12466         uint32_t flr_state;
12467         int fd;
12468         int chunk_count = 0;
12469         int idx = 0;
12470         int rc = 0;
12471         int rc1 = 0;
12472         int rc2 = 0;
12473
12474         if (stat(fname, &stbuf) < 0) {
12475                 fprintf(stderr, "%s: cannot stat file '%s': %s.\n",
12476                         progname, fname, strerror(errno));
12477                 rc = -errno;
12478                 goto error;
12479         }
12480
12481         if (!S_ISREG(stbuf.st_mode)) {
12482                 fprintf(stderr, "%s: '%s' is not a regular file.\n",
12483                         progname, fname);
12484                 rc = -EINVAL;
12485                 goto error;
12486         }
12487
12488         if (stbuf.st_size == 0) {
12489                 if (verbose)
12490                         fprintf(stdout, "%s: '%s' file size is 0.\n",
12491                                 progname, fname);
12492                 rc = 0;
12493                 goto error;
12494         }
12495
12496         /* Allow mirror verify even without the key on encrypted files */
12497         fd = open(fname, O_DIRECT | O_RDONLY | O_FILE_ENC);
12498         if (fd < 0) {
12499                 fprintf(stderr, "%s: cannot open '%s': %s.\n",
12500                         progname, fname, strerror(errno));
12501                 rc = -errno;
12502                 goto error;
12503         }
12504
12505         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
12506         if (rc < 0) {
12507                 fprintf(stderr, "%s: '%s' llapi_lease_acquire failed: %s.\n",
12508                         progname, fname, strerror(errno));
12509                 goto close_fd;
12510         }
12511
12512         layout = llapi_layout_get_by_fd(fd, 0);
12513         if (!layout) {
12514                 fprintf(stderr, "%s: '%s' llapi_layout_get_by_fd failed: %s.\n",
12515                         progname, fname, strerror(errno));
12516                 rc = -errno;
12517                 llapi_lease_release(fd);
12518                 goto close_fd;
12519         }
12520
12521         rc = llapi_layout_flags_get(layout, &flr_state);
12522         if (rc < 0) {
12523                 fprintf(stderr, "%s: '%s' llapi_layout_flags_get failed: %s.\n",
12524                         progname, fname, strerror(errno));
12525                 rc = -errno;
12526                 goto free_layout;
12527         }
12528
12529         flr_state &= LCM_FL_FLR_MASK;
12530         switch (flr_state) {
12531         case LCM_FL_NONE:
12532                 rc = -EINVAL;
12533                 fprintf(stderr, "%s: '%s' file state error: %s.\n",
12534                         progname, fname, llapi_layout_flags_string(flr_state));
12535                 goto free_layout;
12536         default:
12537                 break;
12538         }
12539
12540         /* find out mirror chunks to be verified */
12541         chunk_count = lfs_mirror_prepare_chunk(layout, chunks_array,
12542                                                ARRAY_SIZE(chunks_array));
12543         if (chunk_count < 0) {
12544                 rc = chunk_count;
12545                 goto free_layout;
12546         }
12547
12548         if (ids_nr > 0)
12549                 /* filter specified mirror ids */
12550                 filter_mirror_id(chunks_array, chunk_count, mirror_ids, ids_nr);
12551
12552         if (verbose > 2)
12553                 print_chunks(fname, chunks_array, chunk_count);
12554
12555         for (idx = 0; idx < chunk_count; idx++) {
12556                 if (chunks_array[idx].chunk.e_start >= stbuf.st_size) {
12557                         if (verbose)
12558                                 fprintf(stdout,
12559                                         "%s: '%s' chunk "DEXT" exceeds file size %#llx: skipped\n",
12560                                         progname, fname,
12561                                         PEXT(&chunks_array[idx].chunk),
12562                                         (unsigned long long)stbuf.st_size);
12563                         break;
12564                 }
12565
12566                 if (chunks_array[idx].mirror_count == 0) {
12567                         fprintf(stderr,
12568                                 "%s: '%s' chunk "DEXT" is invalid in all of the mirrors: ",
12569                                 progname, fname,
12570                                 PEXT(&chunks_array[idx].chunk));
12571                         if (verbose) {
12572                                 fprintf(stderr, "skipped\n");
12573                                 continue;
12574                         }
12575                         rc = -EINVAL;
12576                         fprintf(stderr, "failed\n");
12577                         goto free_layout;
12578                 }
12579
12580                 if (chunks_array[idx].mirror_count == 1) {
12581                         if (verbose)
12582                                 fprintf(stdout,
12583                                         "%s: '%s' chunk "DEXT" is only valid in mirror %u: skipped\n",
12584                                         progname, fname,
12585                                         PEXT(&chunks_array[idx].chunk),
12586                                         chunks_array[idx].mirror_id[0]);
12587                         continue;
12588                 }
12589
12590                 rc = llapi_lease_check(fd);
12591                 if (rc != LL_LEASE_RDLCK) {
12592                         fprintf(stderr, "%s: '%s' lost lease lock.\n",
12593                                 progname, fname);
12594                         goto free_layout;
12595                 }
12596
12597                 /* verify one chunk */
12598                 rc1 = lfs_mirror_verify_chunk(fd, stbuf.st_size,
12599                                               &chunks_array[idx], verbose);
12600                 if (rc1 < 0) {
12601                         rc2 = rc1;
12602                         if (!verbose) {
12603                                 rc = rc1;
12604                                 goto free_layout;
12605                         }
12606                 }
12607         }
12608
12609         if (rc2 < 0)
12610                 rc = rc2;
12611
12612 free_layout:
12613         llapi_layout_free(layout);
12614         llapi_lease_release(fd);
12615 close_fd:
12616         close(fd);
12617 error:
12618         return rc;
12619 }
12620
12621 /**
12622  * lfs_mirror_verify() - Parse and execute lfs mirror verify command.
12623  * @argc: The count of lfs mirror verify command line arguments.
12624  * @argv: Array of strings for lfs mirror verify command line arguments.
12625  *
12626  * This function parses lfs mirror verify command and verifies the
12627  * specified mirrored file(s).
12628  *
12629  * Return: 0 on success or a negative error code on failure.
12630  */
12631 static inline int lfs_mirror_verify(int argc, char **argv)
12632 {
12633         __u16 mirror_ids[LUSTRE_MIRROR_COUNT_MAX] = { 0 };
12634         int ids_nr = 0;
12635         int c;
12636         int verbose = 0;
12637         int rc = 0;
12638         int rc1 = 0;
12639         char cmd[PATH_MAX];
12640
12641         struct option long_opts[] = {
12642         { .val = 'h',   .name = "help",         .has_arg = no_argument },
12643         { .val = 'o',   .name = "only",         .has_arg = required_argument },
12644         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
12645         { .name = NULL } };
12646
12647         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
12648         progname = cmd;
12649         while ((c = getopt_long(argc, argv, "ho:v", long_opts, NULL)) >= 0) {
12650                 switch (c) {
12651                 case 'o':
12652                         rc = parse_mirror_ids(mirror_ids,
12653                                               ARRAY_SIZE(mirror_ids),
12654                                               optarg);
12655                         if (rc < 0) {
12656                                 fprintf(stderr,
12657                                         "%s: bad mirror ids '%s'.\n",
12658                                         progname, optarg);
12659                                 goto error;
12660                         }
12661                         ids_nr = rc;
12662                         if (ids_nr < 2) {
12663                                 fprintf(stderr,
12664                                         "%s: at least 2 mirror ids needed with '--only' option.\n",
12665                                         progname);
12666                                 rc = CMD_HELP;
12667                                 goto error;
12668                         }
12669                         break;
12670                 case 'v':
12671                         verbose++;
12672                         break;
12673                 default:
12674                         fprintf(stderr, "%s: unrecognized option '%s'\n",
12675                                 progname, argv[optind - 1]);
12676                         fallthrough;
12677                 case 'h':
12678                         rc = CMD_HELP;
12679                         goto error;
12680                 }
12681         }
12682
12683         if (argc == optind) {
12684                 fprintf(stderr, "%s: no file name given.\n", progname);
12685                 rc = CMD_HELP;
12686                 goto error;
12687         }
12688
12689         if (ids_nr > 0 && argc > optind + 1) {
12690                 fprintf(stderr,
12691                         "%s: '--only' cannot be used upon multiple files.\n",
12692                         progname);
12693                 rc = CMD_HELP;
12694                 goto error;
12695         }
12696
12697         if (ids_nr > 0) {
12698                 rc = verify_mirror_ids(argv[optind], mirror_ids, ids_nr);
12699                 if (rc < 0)
12700                         goto error;
12701         }
12702
12703         rc = 0;
12704         for (; optind < argc; optind++) {
12705                 rc1 = lfs_mirror_verify_file(argv[optind], mirror_ids, ids_nr,
12706                                              verbose);
12707                 if (rc1 < 0)
12708                         rc = rc1;
12709         }
12710 error:
12711         return rc;
12712 }
12713
12714 /**
12715  * lfs_mirror() - Parse and execute lfs mirror commands.
12716  * @argc: The count of lfs mirror command line arguments.
12717  * @argv: Array of strings for lfs mirror command line arguments.
12718  *
12719  * This function parses lfs mirror commands and performs the
12720  * corresponding functions specified in mirror_cmdlist[].
12721  *
12722  * Return: 0 on success or an error code on failure.
12723  */
12724 static int lfs_mirror(int argc, char **argv)
12725 {
12726         char cmd[PATH_MAX];
12727         int rc = 0;
12728
12729         setlinebuf(stdout);
12730
12731         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
12732         progname = cmd;
12733         program_invocation_short_name = cmd;
12734         rc = cfs_parser(argc, argv, mirror_cmdlist);
12735
12736         return rc < 0 ? -rc : rc;
12737 }
12738
12739 static void lustre_som_swab(struct lustre_som_attrs *attrs)
12740 {
12741 #if __BYTE_ORDER == __BIG_ENDIAN
12742         __swab16s(&attrs->lsa_valid);
12743         __swab64s(&attrs->lsa_size);
12744         __swab64s(&attrs->lsa_blocks);
12745 #endif
12746 }
12747
12748 enum lfs_som_type {
12749         LFS_SOM_SIZE = 0x1,
12750         LFS_SOM_BLOCKS = 0x2,
12751         LFS_SOM_FLAGS = 0x4,
12752         LFS_SOM_ATTR_ALL = LFS_SOM_SIZE | LFS_SOM_BLOCKS |
12753                            LFS_SOM_FLAGS,
12754 };
12755
12756 static int lfs_getsom(int argc, char **argv)
12757 {
12758         const char *path;
12759         struct lustre_som_attrs *attrs;
12760         char buf[sizeof(*attrs) + 64];
12761         enum lfs_som_type type = LFS_SOM_ATTR_ALL;
12762         int rc = 0, c;
12763
12764         while ((c = getopt(argc, argv, "bfhs")) != -1) {
12765                 switch (c) {
12766                 case 'b':
12767                         type = LFS_SOM_BLOCKS;
12768                         break;
12769                 case 'f':
12770                         type = LFS_SOM_FLAGS;
12771                         break;
12772                 case 's':
12773                         type = LFS_SOM_SIZE;
12774                         break;
12775                 default:
12776                         fprintf(stderr, "%s: unrecognized option '%s'\n",
12777                                 progname, argv[optind - 1]);
12778                         fallthrough;
12779                 case 'h':
12780                         return CMD_HELP;
12781                 }
12782         }
12783
12784         argc -= optind;
12785         argv += optind;
12786
12787         if (argc != 1) {
12788                 fprintf(stderr, "%s: %s\n",
12789                         progname, argc == 0 ? "miss file target" :
12790                         "input more than 2 files");
12791                 return CMD_HELP;
12792         }
12793
12794         path = argv[0];
12795         attrs = (void *)buf;
12796         rc = lgetxattr(path, "trusted.som", attrs, sizeof(buf));
12797         if (rc < 0) {
12798                 rc = -errno;
12799                 fprintf(stderr, "%s failed to get som xattr: %s (%d)\n",
12800                         argv[0], strerror(errno), errno);
12801                 return rc;
12802         }
12803
12804         lustre_som_swab(attrs);
12805
12806         switch (type) {
12807         case LFS_SOM_ATTR_ALL:
12808                 printf("file: %s size: %llu blocks: %llu flags: %x\n",
12809                        path, (unsigned long long)attrs->lsa_size,
12810                        (unsigned long long)attrs->lsa_blocks,
12811                        attrs->lsa_valid);
12812                 break;
12813         case LFS_SOM_SIZE:
12814                 printf("%llu\n", (unsigned long long)attrs->lsa_size);
12815                 break;
12816         case LFS_SOM_BLOCKS:
12817                 printf("%llu\n", (unsigned long long)attrs->lsa_blocks);
12818                 break;
12819         case LFS_SOM_FLAGS:
12820                 printf("%x\n", attrs->lsa_valid);
12821                 break;
12822         default:
12823                 fprintf(stderr, "%s: unknown option\n", progname);
12824                 return CMD_HELP;
12825         }
12826
12827         return 0;
12828 }
12829
12830 static int lfs_pcc_attach(int argc, char **argv)
12831 {
12832         struct option long_opts[] = {
12833         { .val = 'h',   .name = "help", .has_arg = no_argument },
12834         { .val = 'i',   .name = "id",   .has_arg = required_argument },
12835         { .name = NULL } };
12836         int c;
12837         int rc = 0;
12838         __u32 archive_id = 0;
12839         const char *path;
12840         char *end;
12841         char fullpath[PATH_MAX];
12842         enum lu_pcc_type type = LU_PCC_READWRITE;
12843
12844         optind = 0;
12845         while ((c = getopt_long(argc, argv, "hi:",
12846                                 long_opts, NULL)) != -1) {
12847                 switch (c) {
12848                 case 'i':
12849                         errno = 0;
12850                         archive_id = strtoul(optarg, &end, 0);
12851                         if (errno != 0 || *end != '\0' ||
12852                             archive_id == 0 || archive_id > UINT32_MAX) {
12853                                 fprintf(stderr,
12854                                         "error: %s: bad archive ID '%s'\n",
12855                                         progname, optarg);
12856                                 return CMD_HELP;
12857                         }
12858                         break;
12859                 default:
12860                         fprintf(stderr, "%s: unrecognized option '%s'\n",
12861                                 progname, argv[optind - 1]);
12862                         fallthrough;
12863                 case 'h':
12864                         return CMD_HELP;
12865                 }
12866         }
12867
12868         if (archive_id == 0) {
12869                 fprintf(stderr, "%s: must specify attach ID\n", argv[0]);
12870                 return CMD_HELP;
12871         }
12872
12873         if (argc <= optind) {
12874                 fprintf(stderr, "%s: must specify one or more file names\n",
12875                         argv[0]);
12876                 return CMD_HELP;
12877         }
12878
12879         while (optind < argc) {
12880                 int rc2;
12881
12882                 path = argv[optind++];
12883                 if (!realpath(path, fullpath)) {
12884                         fprintf(stderr, "%s: could not find path '%s': %s\n",
12885                                 argv[0], path, strerror(errno));
12886                         if (rc == 0)
12887                                 rc = -EINVAL;
12888                         continue;
12889                 }
12890
12891                 rc2 = llapi_pcc_attach(fullpath, archive_id, type);
12892                 if (rc2 < 0) {
12893                         fprintf(stderr,
12894                                 "%s: cannot attach '%s' to PCC with archive ID '%u': %s\n",
12895                                 argv[0], path, archive_id, strerror(-rc2));
12896                         if (rc == 0)
12897                                 rc = rc2;
12898                 }
12899         }
12900         return rc;
12901 }
12902
12903 static int lfs_pcc_attach_fid(int argc, char **argv)
12904 {
12905         struct option long_opts[] = {
12906         { .val = 'h',   .name = "help", .has_arg = no_argument },
12907         { .val = 'i',   .name = "id",   .has_arg = required_argument },
12908         { .val = 'm',   .name = "mnt",  .has_arg = required_argument },
12909         { .name = NULL } };
12910         int c;
12911         int rc = 0;
12912         __u32 archive_id = 0;
12913         char *end;
12914         const char *mntpath = NULL;
12915         const char *fidstr;
12916         enum lu_pcc_type type = LU_PCC_READWRITE;
12917
12918         optind = 0;
12919         while ((c = getopt_long(argc, argv, "hi:m:",
12920                                 long_opts, NULL)) != -1) {
12921                 switch (c) {
12922                 case 'i':
12923                         errno = 0;
12924                         archive_id = strtoul(optarg, &end, 0);
12925                         if (errno != 0 || *end != '\0' ||
12926                             archive_id > UINT32_MAX) {
12927                                 fprintf(stderr,
12928                                         "error: %s: bad archive ID '%s'\n",
12929                                         argv[0], optarg);
12930                                 return CMD_HELP;
12931                         }
12932                         break;
12933                 case 'm':
12934                         mntpath = optarg;
12935                         break;
12936                 default:
12937                         fprintf(stderr, "%s: unrecognized option '%s'\n",
12938                                 progname, argv[optind - 1]);
12939                         fallthrough;
12940                 case 'h':
12941                         return CMD_HELP;
12942                 }
12943         }
12944
12945         if (archive_id == 0) {
12946                 fprintf(stderr, "%s: must specify an archive ID\n", argv[0]);
12947                 return CMD_HELP;
12948         }
12949
12950         if (!mntpath) {
12951                 fprintf(stderr, "%s: must specify Lustre mount point\n",
12952                         argv[0]);
12953                 return CMD_HELP;
12954         }
12955
12956         if (argc <= optind) {
12957                 fprintf(stderr, "%s: must specify one or more fids\n", argv[0]);
12958                 return CMD_HELP;
12959         }
12960
12961         while (optind < argc) {
12962                 int rc2;
12963
12964                 fidstr = argv[optind++];
12965
12966                 rc2 = llapi_pcc_attach_fid_str(mntpath, fidstr,
12967                                                archive_id, type);
12968                 if (rc2 < 0) {
12969                         fprintf(stderr,
12970                                 "%s: cannot attach '%s' on '%s' to PCC with archive ID '%u': %s\n",
12971                                 argv[0], fidstr, mntpath, archive_id,
12972                                 strerror(rc2));
12973                 }
12974                 if (rc == 0 && rc2 < 0)
12975                         rc = rc2;
12976         }
12977         return rc;
12978 }
12979
12980 static int lfs_pcc_detach(int argc, char **argv)
12981 {
12982         struct option long_opts[] = {
12983         { .val = 'h',   .name = "help", .has_arg = no_argument },
12984         { .val = 'k',   .name = "keep", .has_arg = no_argument },
12985         { .name = NULL } };
12986         int c;
12987         int rc = 0;
12988         const char *path;
12989         char fullpath[PATH_MAX];
12990         __u32 detach_opt = PCC_DETACH_OPT_UNCACHE;
12991
12992         optind = 0;
12993         while ((c = getopt_long(argc, argv, "hk",
12994                                 long_opts, NULL)) != -1) {
12995                 switch (c) {
12996                 case 'k':
12997                         detach_opt = PCC_DETACH_OPT_NONE;
12998                         break;
12999                 default:
13000                         fprintf(stderr, "%s: unrecognized option '%s'\n",
13001                                 progname, argv[optind - 1]);
13002                         fallthrough;
13003                 case 'h':
13004                         return CMD_HELP;
13005                 }
13006         }
13007
13008         while (optind < argc) {
13009                 int rc2;
13010
13011                 path = argv[optind++];
13012                 if (!realpath(path, fullpath)) {
13013                         fprintf(stderr, "%s: could not find path '%s': %s\n",
13014                                 argv[0], path, strerror(errno));
13015                         if (rc == 0)
13016                                 rc = -EINVAL;
13017                         continue;
13018                 }
13019
13020                 rc2 = llapi_pcc_detach_file(fullpath, detach_opt);
13021                 if (rc2 < 0) {
13022                         rc2 = -errno;
13023                         fprintf(stderr,
13024                                 "%s: cannot detach '%s' from PCC: %s\n",
13025                                 argv[0], path, strerror(errno));
13026                         if (rc == 0)
13027                                 rc = rc2;
13028                 }
13029         }
13030         return rc;
13031 }
13032
13033 static int lfs_pcc_detach_fid(int argc, char **argv)
13034 {
13035         struct option long_opts[] = {
13036         { .val = 'h',   .name = "help", .has_arg = no_argument },
13037         { .val = 'k',   .name = "keep", .has_arg = no_argument },
13038         { .name = NULL } };
13039         int c;
13040         int rc = 0;
13041         const char *fid;
13042         const char *mntpath;
13043         __u32 detach_opt = PCC_DETACH_OPT_UNCACHE;
13044
13045         optind = 0;
13046         while ((c = getopt_long(argc, argv, "hk",
13047                                 long_opts, NULL)) != -1) {
13048                 switch (c) {
13049                 case 'k':
13050                         detach_opt = PCC_DETACH_OPT_NONE;
13051                         break;
13052                 default:
13053                         fprintf(stderr, "%s: unrecognized option '%s'\n",
13054                                 progname, argv[optind - 1]);
13055                         fallthrough;
13056                 case 'h':
13057                         return CMD_HELP;
13058                 }
13059         }
13060
13061         mntpath = argv[optind++];
13062
13063         while (optind < argc) {
13064                 int rc2;
13065
13066                 fid = argv[optind++];
13067
13068                 rc2 = llapi_pcc_detach_fid_str(mntpath, fid, detach_opt);
13069                 if (rc2 < 0) {
13070                         fprintf(stderr,
13071                                 "%s: cannot detach '%s' on '%s' from PCC: %s\n",
13072                                 argv[0], fid, mntpath, strerror(-rc2));
13073                         if (rc == 0)
13074                                 rc = rc2;
13075                 }
13076         }
13077         return rc;
13078 }
13079
13080 static int lfs_pcc_state(int argc, char **argv)
13081 {
13082         int rc = 0;
13083         const char *path;
13084         char fullpath[PATH_MAX];
13085         struct lu_pcc_state state;
13086
13087         optind = 1;
13088
13089         if (argc <= 1) {
13090                 fprintf(stderr, "%s: must specify one or more file names\n",
13091                         progname);
13092                 return CMD_HELP;
13093         }
13094
13095         while (optind < argc) {
13096                 int rc2;
13097
13098                 path = argv[optind++];
13099                 if (!realpath(path, fullpath)) {
13100                         fprintf(stderr, "%s: could not find path '%s': %s\n",
13101                                 argv[0], path, strerror(errno));
13102                         if (rc == 0)
13103                                 rc = -EINVAL;
13104                         continue;
13105                 }
13106
13107                 rc2 = llapi_pcc_state_get(fullpath, &state);
13108                 if (rc2 < 0) {
13109                         if (rc == 0)
13110                                 rc = rc2;
13111                         fprintf(stderr,
13112                                 "%s: cannot get PCC state of '%s': %s\n",
13113                                 argv[0], path, strerror(-rc2));
13114                         continue;
13115                 }
13116
13117                 printf("file: %s", path);
13118                 printf(", type: %s", pcc_type2string(state.pccs_type));
13119                 if (state.pccs_type == LU_PCC_NONE &&
13120                     state.pccs_open_count == 0) {
13121                         printf("\n");
13122                         continue;
13123                 }
13124
13125                 printf(", PCC file: %s", state.pccs_path);
13126                 printf(", user number: %u", state.pccs_open_count);
13127                 printf(", flags: %x", state.pccs_flags);
13128                 printf("\n");
13129         }
13130         return rc;
13131 }
13132
13133 /**
13134  * lfs_pcc() - Parse and execute lfs pcc commands.
13135  * @argc: The count of lfs pcc command line arguments.
13136  * @argv: Array of strings for lfs pcc command line arguments.
13137  *
13138  * This function parses lfs pcc commands and performs the
13139  * corresponding functions specified in pcc_cmdlist[].
13140  *
13141  * Return: 0 on success or an error code on failure.
13142  */
13143 static int lfs_pcc(int argc, char **argv)
13144 {
13145         char cmd[PATH_MAX];
13146         int rc = 0;
13147
13148         setlinebuf(stdout);
13149
13150         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
13151         progname = cmd;
13152         program_invocation_short_name = cmd;
13153         rc = cfs_parser(argc, argv, pcc_cmdlist);
13154
13155         return rc < 0 ? -rc : rc;
13156 }
13157
13158 int main(int argc, char **argv)
13159 {
13160         int rc;
13161
13162         /* Ensure that liblustreapi constructor has run */
13163         if (!llapi_liblustreapi_initialized())
13164                 fprintf(stderr, "liblustreapi was not properly initialized\n");
13165
13166         setlinebuf(stdout);
13167         opterr = 0;
13168
13169         progname = program_invocation_short_name; /* Used in error messages */
13170         llapi_set_command_name(argv[1]);
13171         rc = cfs_parser(argc, argv, cmdlist);
13172         llapi_clear_command_name();
13173
13174         return rc < 0 ? -rc : rc;
13175 }
13176
13177 #ifdef _LUSTRE_IDL_H_
13178 /* Everything we need here should be included by lustreapi.h. */
13179 # error "lfs should not depend on lustre_idl.h"
13180 #endif /* _LUSTRE_IDL_H_ */