Whamcloud - gitweb
381d940d68bdd2f6cdac7b3694044bc8528d0c8f
[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          "[--print0|-0] <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 && !mirror_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 prev_optind = optind;
5159         int optidx = 0;
5160         int pathstart = -1;
5161         int pathend = -1;
5162         int pathbad = -1;
5163         int neg_opt = 0;
5164         time_t *xtime;
5165         int *xsign;
5166         int isoption;
5167         char *endptr;
5168
5169         time(&t);
5170
5171         /* when getopt_long_only() hits '!' it returns 1, puts "!" in optarg */
5172         while ((c = getopt_long_only(argc, argv,
5173                 "-0A:b:B:c:C:D:E:g:G:hH:i:lL:m:M:n:N:O:Ppqrs:S:t:T:u:U:z:",
5174                 long_opts, &optidx)) >= 0) {
5175                 xtime = NULL;
5176                 xsign = NULL;
5177                 if (neg_opt)
5178                         --neg_opt;
5179                 /* '!' is part of option */
5180                 /*
5181                  * when getopt_long_only() finds a string which is not
5182                  * an option nor a known option argument it returns 1
5183                  * in that case if we already have found pathstart and pathend
5184                  * (i.e. we have the list of pathnames),
5185                  * the only supported value is "!"
5186                  */
5187                 isoption = (c != 1) || (strcmp(optarg, "!") == 0);
5188                 if (!isoption && pathend != -1) {
5189                         fprintf(stderr,
5190                                 "err: %s: filename|dirname must either precede options or follow options\n",
5191                                 argv[0]);
5192                         ret = CMD_HELP;
5193                         goto err;
5194                 }
5195                 if (!isoption && pathstart == -1)
5196                         pathstart = prev_optind;
5197                 if (isoption && pathstart != -1 && pathend == -1)
5198                         pathend = prev_optind;
5199
5200                 prev_optind = optind;
5201
5202                 switch (c) {
5203                 case 0:
5204                         /* Long options. */
5205                         break;
5206                 case 1:
5207                         /*
5208                          * unknown; opt is "!" or path component,
5209                          * checking done above.
5210                          */
5211                         if (strcmp(optarg, "!") == 0)
5212                                 neg_opt = 2;
5213                         break;
5214                 case 'A':
5215                         xtime = &param.fp_atime;
5216                         xsign = &param.fp_asign;
5217                         param.fp_exclude_atime = !!neg_opt;
5218                         /* no break, this falls through to 'B' for btime */
5219                         fallthrough;
5220                 case 'B':
5221                         if (c == 'B') {
5222                                 xtime = &param.fp_btime;
5223                                 xsign = &param.fp_bsign;
5224                                 param.fp_exclude_btime = !!neg_opt;
5225                         }
5226                         /* no break, this falls through to 'C' for ctime */
5227                         fallthrough;
5228                 case 'C':
5229                         if (c == 'C') {
5230                                 xtime = &param.fp_ctime;
5231                                 xsign = &param.fp_csign;
5232                                 param.fp_exclude_ctime = !!neg_opt;
5233                         }
5234                         /* no break, this falls through to 'M' for mtime */
5235                         fallthrough;
5236                 case 'M':
5237                         if (c == 'M') {
5238                                 xtime = &param.fp_mtime;
5239                                 xsign = &param.fp_msign;
5240                                 param.fp_exclude_mtime = !!neg_opt;
5241                         }
5242                         rc = set_time(&param, &t, xtime, optarg);
5243                         if (rc == INT_MAX) {
5244                                 ret = -1;
5245                                 goto err;
5246                         }
5247                         if (rc)
5248                                 *xsign = rc;
5249                         break;
5250                 case 'b':
5251                         if (optarg[0] == '+') {
5252                                 param.fp_blocks_sign = -1;
5253                                 optarg++;
5254                         } else if (optarg[0] == '-') {
5255                                 param.fp_blocks_sign =  1;
5256                                 optarg++;
5257                         }
5258
5259                         param.fp_blocks_units = 1024;
5260                         ret = llapi_parse_size(optarg, &param.fp_blocks,
5261                                                &param.fp_blocks_units, 0);
5262                         if (ret) {
5263                                 fprintf(stderr, "error: bad blocks '%s'\n",
5264                                         optarg);
5265                                 goto err;
5266                         }
5267                         param.fp_check_blocks = 1;
5268                         param.fp_exclude_blocks = !!neg_opt;
5269                         break;
5270                 case LFS_COMP_COUNT_OPT:
5271                         if (optarg[0] == '+') {
5272                                 param.fp_comp_count_sign = -1;
5273                                 optarg++;
5274                         } else if (optarg[0] == '-') {
5275                                 param.fp_comp_count_sign =  1;
5276                                 optarg++;
5277                         }
5278
5279                         errno = 0;
5280                         param.fp_comp_count = strtoul(optarg, &endptr, 0);
5281                         if (errno != 0 || *endptr != '\0' ||
5282                             param.fp_comp_count > UINT32_MAX) {
5283                                 fprintf(stderr,
5284                                         "error: bad component count '%s'\n",
5285                                         optarg);
5286                                 goto err;
5287                         }
5288                         param.fp_check_comp_count = 1;
5289                         param.fp_exclude_comp_count = !!neg_opt;
5290                         break;
5291                 case LFS_COMP_FLAGS_OPT:
5292                         rc = comp_str2flags(optarg, &param.fp_comp_flags,
5293                                             &param.fp_comp_neg_flags);
5294                         if (rc) {
5295                                 fprintf(stderr,
5296                                         "error: bad component flags '%s'\n",
5297                                         optarg);
5298                                 goto err;
5299                         }
5300                         param.fp_check_comp_flags = 1;
5301                         if (neg_opt) {
5302                                 __u32 flags = param.fp_comp_neg_flags;
5303
5304                                 param.fp_comp_neg_flags = param.fp_comp_flags;
5305                                 param.fp_comp_flags = flags;
5306                         }
5307                         break;
5308                 case LFS_COMP_START_OPT:
5309                         if (optarg[0] == '+') {
5310                                 param.fp_comp_start_sign = -1;
5311                                 optarg++;
5312                         } else if (optarg[0] == '-') {
5313                                 param.fp_comp_start_sign =  1;
5314                                 optarg++;
5315                         }
5316
5317                         rc = llapi_parse_size(optarg, &param.fp_comp_start,
5318                                               &param.fp_comp_start_units, 0);
5319                         if (rc) {
5320                                 fprintf(stderr,
5321                                         "error: bad component start '%s'\n",
5322                                         optarg);
5323                                 goto err;
5324                         }
5325                         param.fp_check_comp_start = 1;
5326                         param.fp_exclude_comp_start = !!neg_opt;
5327                         break;
5328                 case LFS_MIRROR_STATE_OPT:
5329                         rc = mirror_str2state(optarg, &param.fp_mirror_state,
5330                                               &param.fp_mirror_neg_state);
5331                         if (rc) {
5332                                 fprintf(stderr,
5333                                         "error: bad mirrored file state '%s'\n",
5334                                         optarg);
5335                                 goto err;
5336                         }
5337                         param.fp_check_mirror_state = 1;
5338                         if (neg_opt) {
5339                                 __u16 state = param.fp_mirror_neg_state;
5340
5341                                 param.fp_mirror_neg_state =
5342                                         param.fp_mirror_state;
5343                                 param.fp_mirror_state = state;
5344                         }
5345                         break;
5346                 case 'c':
5347                         if (optarg[0] == '+') {
5348                                 param.fp_stripe_count_sign = -1;
5349                                 optarg++;
5350                         } else if (optarg[0] == '-') {
5351                                 param.fp_stripe_count_sign =  1;
5352                                 optarg++;
5353                         }
5354
5355                         errno = 0;
5356                         param.fp_stripe_count = strtoul(optarg, &endptr, 0);
5357                         if (errno != 0 || *endptr != '\0' ||
5358                             param.fp_stripe_count > LOV_MAX_STRIPE_COUNT) {
5359                                 fprintf(stderr,
5360                                         "error: bad stripe_count '%s'\n",
5361                                         optarg);
5362                                 ret = -1;
5363                                 goto err;
5364                         }
5365                         param.fp_check_stripe_count = 1;
5366                         param.fp_exclude_stripe_count = !!neg_opt;
5367                         break;
5368                 case 'D':
5369                         errno = 0;
5370                         param.fp_max_depth = strtol(optarg, 0, 0);
5371                         if (errno != 0 || param.fp_max_depth < 0) {
5372                                 fprintf(stderr,
5373                                         "error: bad maxdepth '%s'\n",
5374                                         optarg);
5375                                 ret = -1;
5376                                 goto err;
5377                         }
5378                         break;
5379                 case 'E':
5380                         if (optarg[0] == '+') {
5381                                 param.fp_comp_end_sign = -1;
5382                                 optarg++;
5383                         } else if (optarg[0] == '-') {
5384                                 param.fp_comp_end_sign =  1;
5385                                 optarg++;
5386                         }
5387
5388                         if (arg_is_eof(optarg)) {
5389                                 param.fp_comp_end = LUSTRE_EOF;
5390                                 param.fp_comp_end_units = 1;
5391                                 rc = 0;
5392                         } else {
5393                                 rc = llapi_parse_size(optarg,
5394                                                 &param.fp_comp_end,
5395                                                 &param.fp_comp_end_units, 0);
5396                                 /* assume units of KB if too small */
5397                                 if (param.fp_comp_end < 4096)
5398                                         param.fp_comp_end *= 1024;
5399                         }
5400                         if (rc) {
5401                                 fprintf(stderr,
5402                                         "error: bad component end '%s'\n",
5403                                         optarg);
5404                                 goto err;
5405                         }
5406                         param.fp_check_comp_end = 1;
5407                         param.fp_exclude_comp_end = !!neg_opt;
5408                         break;
5409                 case LFS_LAYOUT_FOREIGN_OPT: {
5410                         /* all types by default */
5411                         uint32_t type = LU_FOREIGN_TYPE_UNKNOWN;
5412
5413                         if (optarg) {
5414                                 /* check pure numeric */
5415                                 type = strtoul(optarg, &endptr, 0);
5416                                 if (*endptr) {
5417                                         /* check name */
5418                                         type = check_foreign_type_name(optarg);
5419                                         if (type == LU_FOREIGN_TYPE_UNKNOWN) {
5420                                                 fprintf(stderr,
5421                                                         "%s %s: unknown foreign type '%s'\n",
5422                                                         progname, argv[0],
5423                                                         optarg);
5424                                                 return CMD_HELP;
5425                                         }
5426                                 } else if (type >= UINT32_MAX) {
5427                                         fprintf(stderr,
5428                                                 "%s %s: invalid foreign type '%s'\n",
5429                                                 progname, argv[0], optarg);
5430                                         return CMD_HELP;
5431                                 }
5432                         }
5433                         param.fp_foreign_type = type;
5434                         param.fp_check_foreign = 1;
5435                         param.fp_exclude_foreign = !!neg_opt;
5436                         break;
5437                 }
5438                 case LFS_NEWERXY_OPT: {
5439                         char x = 'm';
5440                         char y = 'm';
5441                         int xidx;
5442                         int negidx;
5443                         time_t *newery;
5444                         time_t ref = time(NULL);
5445
5446                         /* no need to check bad options, they won't get here */
5447                         if (strlen(long_opts[optidx].name) == 7) {
5448                                 x = long_opts[optidx].name[5];
5449                                 y = long_opts[optidx].name[6];
5450                         }
5451
5452                         if (y == 't') {
5453                                 static const char *const fmts[] = {
5454                                         "%Y-%m-%d %H:%M:%S",
5455                                         "%Y-%m-%d %H:%M",
5456                                         "%Y-%m-%d",
5457                                         "%H:%M:%S", /* sometime today */
5458                                         "%H:%M",
5459                                         "@%s",
5460                                         "%s",
5461                                         NULL };
5462                                 struct tm tm;
5463                                 bool found = false;
5464                                 int i;
5465
5466                                 for (i = 0; fmts[i] != NULL; i++) {
5467                                         char *ptr;
5468
5469                                         /* Init for times relative to today */
5470                                         if (strncmp(fmts[i], "%H", 2) == 0) {
5471                                                 localtime_r(&ref, &tm);
5472                                         } else {
5473                                                 memset(&tm, 0, sizeof(tm));
5474                                                 tm.tm_isdst = -1;
5475                                         }
5476                                         ptr = strptime(optarg, fmts[i], &tm);
5477                                         /* Skip spaces */
5478                                         while (ptr && isspace(*ptr))
5479                                                 ptr++;
5480                                         if (ptr == optarg + strlen(optarg)) {
5481                                                 found = true;
5482                                                 break;
5483                                         }
5484                                 }
5485
5486                                 if (!found) {
5487                                         fprintf(stderr,
5488                                                 "%s: invalid time '%s'\n",
5489                                                 progname, optarg);
5490                                         fprintf(stderr,
5491                                                 "supported formats are:\n  ");
5492                                         for (i = 0; fmts[i] != NULL; i++)
5493                                                 fprintf(stderr, "'%s', ",
5494                                                         fmts[i]);
5495                                         fprintf(stderr, "\n");
5496                                         ret = -EINVAL;
5497                                         goto err;
5498                                 }
5499
5500                                 ref = mktime(&tm);
5501                         } else if (y == 'b' || y == 'B') {
5502                                 lstatx_t stx;
5503
5504                                 rc = llapi_get_lum_file(optarg, NULL, &stx,
5505                                                         NULL, 0);
5506                                 if (rc || !(stx.stx_mask & STATX_BTIME)) {
5507                                         if (!(stx.stx_mask & STATX_BTIME))
5508                                                 ret = -EOPNOTSUPP;
5509                                         else
5510                                                 ret = -errno;
5511                                         fprintf(stderr,
5512                                                 "%s: get btime failed '%s': %s\n",
5513                                                 progname, optarg,
5514                                                 strerror(-ret));
5515                                         goto err;
5516                                 }
5517
5518                                 ref = stx.stx_btime.tv_sec;
5519                         } else {
5520                                 struct stat statbuf;
5521
5522                                 if (stat(optarg, &statbuf) < 0) {
5523                                         fprintf(stderr,
5524                                                 "%s: cannot stat file '%s': %s\n",
5525                                                 progname, optarg,
5526                                                 strerror(errno));
5527                                         ret = -errno;
5528                                         goto err;
5529                                 }
5530
5531                                 switch (y) {
5532                                 case 'a':
5533                                         ref = statbuf.st_atime;
5534                                         break;
5535                                 case 'm':
5536                                         ref = statbuf.st_mtime;
5537                                         break;
5538                                 case 'c':
5539                                         ref = statbuf.st_ctime;
5540                                         break;
5541                                 default:
5542                                         fprintf(stderr,
5543                                                 "%s: invalid Y argument: '%c'\n",
5544                                                 progname, x);
5545                                         ret = -EINVAL;
5546                                         goto err;
5547                                 }
5548                         }
5549
5550                         switch (x) {
5551                         case 'a':
5552                                 xidx = NEWERXY_ATIME;
5553                                 break;
5554                         case 'm':
5555                                 xidx = NEWERXY_MTIME;
5556                                 break;
5557                         case 'c':
5558                                 xidx = NEWERXY_CTIME;
5559                                 break;
5560                         case 'b':
5561                         case 'B':
5562                                 xidx = NEWERXY_BTIME;
5563                                 break;
5564                         default:
5565                                 fprintf(stderr,
5566                                         "%s: invalid X argument: '%c'\n",
5567                                         progname, x);
5568                                 ret = -EINVAL;
5569                                 goto err;
5570                         }
5571
5572                         negidx = !!neg_opt;
5573                         newery = &param.fp_newery[xidx][negidx];
5574
5575                         if (*newery == 0) {
5576                                 *newery = ref;
5577                         } else {
5578                                 if (negidx)
5579                                         *newery = *newery > ref ? ref : *newery;
5580                                 else
5581                                         *newery = *newery > ref ? *newery : ref;
5582                         }
5583                         param.fp_newerxy = 1;
5584                         break;
5585                 }
5586                 case 'g':
5587                 case 'G':
5588                         rc = name2gid(&param.fp_gid, optarg);
5589                         if (rc) {
5590                                 if (str2quotaid(&param.fp_gid, optarg)) {
5591                                         fprintf(stderr,
5592                                                 "Group/GID: %s cannot be found.\n",
5593                                                 optarg);
5594                                         ret = -1;
5595                                         goto err;
5596                                 }
5597                         }
5598                         param.fp_exclude_gid = !!neg_opt;
5599                         param.fp_check_gid = 1;
5600                         break;
5601                 case 'H':
5602                         rc = mdthash_input(optarg, &param.fp_hash_inflags,
5603                                            &param.fp_hash_exflags,
5604                                            &param.fp_hash_type);
5605                         if (rc) {
5606                                 ret = -1;
5607                                 goto err;
5608                         }
5609                         if (param.fp_hash_inflags || param.fp_hash_exflags)
5610                                 param.fp_check_hash_flag = 1;
5611                         param.fp_exclude_hash_type = !!neg_opt;
5612                         break;
5613                 case 'l':
5614                         param.fp_lazy = 1;
5615                         break;
5616                 case 'L':
5617                         ret = name2layout(&param.fp_layout, optarg);
5618                         if (ret)
5619                                 goto err;
5620                         param.fp_exclude_layout = !!neg_opt;
5621                         param.fp_check_layout = 1;
5622                         break;
5623                 case LFS_LINKS_OPT:
5624                         if (optarg[0] == '+') {
5625                                 param.fp_nlink_sign = -1;
5626                                 optarg++;
5627                         } else if (optarg[0] == '-') {
5628                                 param.fp_nlink_sign =  1;
5629                                 optarg++;
5630                         }
5631                         errno = 0;
5632                         param.fp_nlink = strtoul(optarg, &endptr, 0);
5633                         if (errno != 0 || *endptr != '\0' || !param.fp_nlink) {
5634                                 fprintf(stderr, "error: bad link count '%s'\n",
5635                                         optarg);
5636                                 ret = -1;
5637                                 goto err;
5638                         }
5639                         param.fp_exclude_nlink = !!neg_opt;
5640                         break;
5641                 case 'u':
5642                 case 'U':
5643                         rc = name2uid(&param.fp_uid, optarg);
5644                         if (rc) {
5645                                 if (str2quotaid(&param.fp_uid, optarg)) {
5646                                         fprintf(stderr,
5647                                                 "User/UID: %s cannot be found.\n",
5648                                                 optarg);
5649                                         ret = -1;
5650                                         goto err;
5651                                 }
5652                         }
5653                         param.fp_exclude_uid = !!neg_opt;
5654                         param.fp_check_uid = 1;
5655                         break;
5656                 case 'n':
5657                         param.fp_pattern = (char *)optarg;
5658                         param.fp_exclude_pattern = !!neg_opt;
5659                         break;
5660                 case 'N':
5661                         if (optarg[0] == '+') {
5662                                 param.fp_mirror_count_sign = -1;
5663                                 optarg++;
5664                         } else if (optarg[0] == '-') {
5665                                 param.fp_mirror_count_sign =  1;
5666                                 optarg++;
5667                         }
5668
5669                         errno = 0;
5670                         param.fp_mirror_count = strtoul(optarg, &endptr, 0);
5671                         if (errno != 0 || *endptr != '\0' ||
5672                             param.fp_mirror_count > LUSTRE_MIRROR_COUNT_MAX) {
5673                                 fprintf(stderr,
5674                                         "error: bad mirror count '%s'\n",
5675                                         optarg);
5676                                 goto err;
5677                         }
5678                         param.fp_check_mirror_count = 1;
5679                         param.fp_exclude_mirror_count = !!neg_opt;
5680                         break;
5681                 case 'm':
5682                 case 'i':
5683                 case 'O': {
5684                         char *buf, *token, *next, *p;
5685                         int len = 1;
5686                         void *tmp;
5687
5688                         buf = strdup(optarg);
5689                         if (!buf) {
5690                                 ret = -ENOMEM;
5691                                 goto err;
5692                         }
5693
5694                         param.fp_exclude_obd = !!neg_opt;
5695
5696                         token = buf;
5697                         while (token && *token) {
5698                                 token = strchr(token, ',');
5699                                 if (token) {
5700                                         len++;
5701                                         token++;
5702                                 }
5703                         }
5704                         if (c == 'm') {
5705                                 param.fp_exclude_mdt = !!neg_opt;
5706                                 param.fp_num_alloc_mdts += len;
5707                                 tmp = realloc(param.fp_mdt_uuid,
5708                                               param.fp_num_alloc_mdts *
5709                                               sizeof(*param.fp_mdt_uuid));
5710                                 if (!tmp) {
5711                                         ret = -ENOMEM;
5712                                         goto err_free;
5713                                 }
5714
5715                                 param.fp_mdt_uuid = tmp;
5716                         } else {
5717                                 param.fp_exclude_obd = !!neg_opt;
5718                                 param.fp_num_alloc_obds += len;
5719                                 tmp = realloc(param.fp_obd_uuid,
5720                                               param.fp_num_alloc_obds *
5721                                               sizeof(*param.fp_obd_uuid));
5722                                 if (!tmp) {
5723                                         ret = -ENOMEM;
5724                                         goto err_free;
5725                                 }
5726
5727                                 param.fp_obd_uuid = tmp;
5728                         }
5729                         for (token = buf; token && *token; token = next) {
5730                                 struct obd_uuid *puuid;
5731
5732                                 if (c == 'm') {
5733                                         puuid =
5734                                         &param.fp_mdt_uuid[param.fp_num_mdts++];
5735                                 } else {
5736                                         puuid =
5737                                         &param.fp_obd_uuid[param.fp_num_obds++];
5738                                 }
5739                                 p = strchr(token, ',');
5740                                 next = 0;
5741                                 if (p) {
5742                                         *p = 0;
5743                                         next = p+1;
5744                                 }
5745
5746                                 if (strlen(token) > sizeof(puuid->uuid) - 1) {
5747                                         ret = -E2BIG;
5748                                         goto err_free;
5749                                 }
5750
5751                                 strncpy(puuid->uuid, token,
5752                                         sizeof(puuid->uuid));
5753                         }
5754 err_free:
5755                         if (buf)
5756                                 free(buf);
5757                         break;
5758                 }
5759 #if LUSTRE_VERSION_CODE >= OBD_OCD_VERSION(2, 18, 53, 0)
5760                 case 'p':
5761 #endif
5762                 case LFS_POOL_OPT:
5763                         if (strlen(optarg) > LOV_MAXPOOLNAME) {
5764                                 fprintf(stderr,
5765                                         "Pool name %s is too long (max %d)\n",
5766                                         optarg, LOV_MAXPOOLNAME);
5767                                 ret = -1;
5768                                 goto err;
5769                         }
5770                         /*
5771                          * We do check for empty pool because empty pool
5772                          * is used to find V1 LOV attributes
5773                          */
5774                         strncpy(param.fp_poolname, optarg, LOV_MAXPOOLNAME);
5775                         param.fp_poolname[LOV_MAXPOOLNAME] = '\0';
5776                         param.fp_exclude_pool = !!neg_opt;
5777                         param.fp_check_pool = 1;
5778                         break;
5779                 case '0':
5780                         param.fp_zero_end = 1;
5781                         break;
5782                 case 'P': /* we always print, this option is a no-op */
5783                         break;
5784                 case LFS_PRINTF_OPT:
5785                         param.fp_format_printf_str = strdup(optarg);
5786                         break;
5787                 case LFS_PROJID_OPT:
5788                         rc = name2projid(&param.fp_projid, optarg);
5789                         if (rc) {
5790                                 if (str2quotaid(&param.fp_projid, optarg)) {
5791                                         fprintf(stderr,
5792                                                 "Invalid project ID: %s\n",
5793                                                 optarg);
5794                                         ret = -1;
5795                                         goto err;
5796                                 }
5797                         }
5798                         param.fp_exclude_projid = !!neg_opt;
5799                         param.fp_check_projid = 1;
5800                         break;
5801                 case 's':
5802                         if (optarg[0] == '+') {
5803                                 param.fp_size_sign = -1;
5804                                 optarg++;
5805                         } else if (optarg[0] == '-') {
5806                                 param.fp_size_sign =  1;
5807                                 optarg++;
5808                         }
5809
5810                         ret = llapi_parse_size(optarg, &param.fp_size,
5811                                                &param.fp_size_units, 0);
5812                         if (ret) {
5813                                 fprintf(stderr, "error: bad file size '%s'\n",
5814                                         optarg);
5815                                 goto err;
5816                         }
5817                         param.fp_check_size = 1;
5818                         param.fp_exclude_size = !!neg_opt;
5819                         break;
5820                 case 'S':
5821                         if (optarg[0] == '+') {
5822                                 param.fp_stripe_size_sign = -1;
5823                                 optarg++;
5824                         } else if (optarg[0] == '-') {
5825                                 param.fp_stripe_size_sign =  1;
5826                                 optarg++;
5827                         }
5828
5829                         ret = llapi_parse_size(optarg, &param.fp_stripe_size,
5830                                                &param.fp_stripe_size_units, 0);
5831                         /* assume units of KB if too small to be valid */
5832                         if (param.fp_stripe_size < 4096)
5833                                 param.fp_stripe_size *= 1024;
5834                         if (ret) {
5835                                 fprintf(stderr, "error: bad stripe_size '%s'\n",
5836                                         optarg);
5837                                 goto err;
5838                         }
5839                         param.fp_check_stripe_size = 1;
5840                         param.fp_exclude_stripe_size = !!neg_opt;
5841                         break;
5842                 case 't':
5843                         param.fp_exclude_type = !!neg_opt;
5844                         switch (optarg[0]) {
5845                         case 'b':
5846                                 param.fp_type = S_IFBLK;
5847                                 break;
5848                         case 'c':
5849                                 param.fp_type = S_IFCHR;
5850                                 break;
5851                         case 'd':
5852                                 param.fp_type = S_IFDIR;
5853                                 break;
5854                         case 'f':
5855                                 param.fp_type = S_IFREG;
5856                                 break;
5857                         case 'l':
5858                                 param.fp_type = S_IFLNK;
5859                                 break;
5860                         case 'p':
5861                                 param.fp_type = S_IFIFO;
5862                                 break;
5863                         case 's':
5864                                 param.fp_type = S_IFSOCK;
5865                                 break;
5866                         default:
5867                                 fprintf(stderr, "%s: bad type '%s'\n",
5868                                         progname, optarg);
5869                                 ret = CMD_HELP;
5870                                 goto err;
5871                         }
5872                         break;
5873                 case LFS_FIND_PERM:
5874                         param.fp_exclude_perm = !!neg_opt;
5875                         param.fp_perm_sign = LFS_FIND_PERM_EXACT;
5876                         if (*optarg == '/') {
5877                                 param.fp_perm_sign = LFS_FIND_PERM_ANY;
5878                                 optarg++;
5879                         } else if (*optarg == '-') {
5880                                 param.fp_perm_sign = LFS_FIND_PERM_ALL;
5881                                 optarg++;
5882                         }
5883
5884                         if (str2mode_t(optarg, &param.fp_perm)) {
5885                                 fprintf(stderr, "error: invalid mode '%s'\n",
5886                                         optarg);
5887                                 ret = -1;
5888                                 goto err;
5889                         }
5890                         break;
5891                 case 'T':
5892                         if (optarg[0] == '+') {
5893                                 param.fp_mdt_count_sign = -1;
5894                                 optarg++;
5895                         } else if (optarg[0] == '-') {
5896                                 param.fp_mdt_count_sign =  1;
5897                                 optarg++;
5898                         }
5899
5900                         errno = 0;
5901                         param.fp_mdt_count = strtoul(optarg, &endptr, 0);
5902                         if (errno != 0 || *endptr != '\0' ||
5903                             param.fp_mdt_count >= UINT32_MAX) {
5904                                 fprintf(stderr, "error: bad mdt_count '%s'\n",
5905                                         optarg);
5906                                 ret = -1;
5907                                 goto err;
5908                         }
5909                         param.fp_check_mdt_count = 1;
5910                         param.fp_exclude_mdt_count = !!neg_opt;
5911                         break;
5912                 case 'z':
5913                         if (optarg[0] == '+') {
5914                                 param.fp_ext_size_sign = -1;
5915                                 optarg++;
5916                         } else if (optarg[0] == '-') {
5917                                 param.fp_ext_size_sign =  1;
5918                                 optarg++;
5919                         }
5920
5921                         ret = llapi_parse_size(optarg, &param.fp_ext_size,
5922                                                &param.fp_ext_size_units, 0);
5923                         if (ret) {
5924                                 fprintf(stderr, "error: bad ext-size '%s'\n",
5925                                         optarg);
5926                                 goto err;
5927                         }
5928                         param.fp_ext_size /= SEL_UNIT_SIZE;
5929                         param.fp_ext_size_units /= SEL_UNIT_SIZE;
5930                         param.fp_check_ext_size = 1;
5931                         param.fp_exclude_ext_size = !!neg_opt;
5932                         break;
5933                 default:
5934                         fprintf(stderr, "%s: unrecognized option '%s'\n",
5935                                 progname, argv[optind - 1]);
5936                 case 'h':
5937                         ret = CMD_HELP;
5938                         goto err;
5939                 }
5940         }
5941         if (!param.fp_verbose)
5942                 param.fp_verbose = VERBOSE_DEFAULT;
5943
5944         if (pathstart == -1) {
5945                 fprintf(stderr, "error: %s: no filename|pathname\n",
5946                         argv[0]);
5947                 ret = CMD_HELP;
5948                 goto err;
5949         } else if (pathend == -1) {
5950                 /* no options */
5951                 pathend = argc;
5952         }
5953
5954         do {
5955                 rc = llapi_find(argv[pathstart], &param);
5956                 if (rc && !ret) {
5957                         ret = rc;
5958                         pathbad = pathstart;
5959                 }
5960         } while (++pathstart < pathend);
5961
5962         if (ret)
5963                 fprintf(stderr, "%s: failed for '%s': %s\n",
5964                         progname, argv[pathbad], strerror(-rc));
5965
5966 err:
5967         if (param.fp_obd_uuid && param.fp_num_alloc_obds)
5968                 free(param.fp_obd_uuid);
5969
5970         if (param.fp_mdt_uuid && param.fp_num_alloc_mdts)
5971                 free(param.fp_mdt_uuid);
5972
5973         if (param.fp_format_printf_str)
5974                 free(param.fp_format_printf_str);
5975
5976         return ret;
5977 }
5978
5979 static int lfs_getstripe_internal(int argc, char **argv,
5980                                   struct find_param *param)
5981 {
5982         struct option long_opts[] = {
5983 /* find { .val = 'A',   .name = "atime",        .has_arg = required_argument }*/
5984 /* find { .val = 'b',   .name = "blocks",       .has_arg = required_argument }*/
5985 /* find { .val = 'B',   .name = "btime",        .has_arg = required_argument }*/
5986 /* find { .val = 'B',   .name = "Btime",        .has_arg = required_argument }*/
5987         { .val = LFS_COMP_COUNT_OPT,
5988                         .name = "comp-count",   .has_arg = no_argument },
5989         { .val = LFS_COMP_COUNT_OPT,
5990                 .name = "component-count",      .has_arg = no_argument },
5991         { .val = LFS_COMP_FLAGS_OPT,
5992                         .name = "comp-flags",   .has_arg = optional_argument },
5993         { .val = LFS_COMP_FLAGS_OPT,
5994                 .name = "component-flags",      .has_arg = optional_argument },
5995         { .val = LFS_COMP_START_OPT,
5996                         .name = "comp-start",   .has_arg = optional_argument },
5997         { .val = LFS_COMP_START_OPT,
5998                 .name = "component-start",      .has_arg = optional_argument },
5999         { .val = 'c',   .name = "stripe-count", .has_arg = no_argument },
6000         { .val = 'c',   .name = "stripe_count", .has_arg = no_argument },
6001 /* find { .val = 'C',   .name = "ctime",        .has_arg = required_argument }*/
6002         { .val = 'd',   .name = "directory",    .has_arg = no_argument },
6003         { .val = 'D',   .name = "default",      .has_arg = no_argument },
6004         { .val = 'E',   .name = "comp-end",     .has_arg = optional_argument },
6005         { .val = 'E',   .name = "component-end", .has_arg = optional_argument },
6006         { .val = 'F',   .name = "fid",          .has_arg = no_argument },
6007         { .val = 'g',   .name = "generation",   .has_arg = no_argument },
6008 /* find { .val = 'G',   .name = "group",        .has_arg = required_argument }*/
6009         { .val = 'h',   .name = "help",         .has_arg = no_argument },
6010         { .val = LFS_HEX_IDX_OPT,
6011                         .name = "hex-idx",      .has_arg = no_argument },
6012 /* dirstripe { .val = 'H', .name = "mdt-hash",  .has_arg = required_argument }*/
6013         { .val = 'i',   .name = "stripe-index", .has_arg = no_argument },
6014         { .val = 'i',   .name = "stripe_index", .has_arg = no_argument },
6015         { .val = 'I',   .name = "comp-id",      .has_arg = optional_argument },
6016         { .val = 'I',   .name = "component-id", .has_arg = optional_argument },
6017 /* find { .val = 'l',   .name = "lazy",         .has_arg = no_argument }, */
6018         { .val = 'L',   .name = "layout",       .has_arg = no_argument },
6019         { .val = 'm',   .name = "mdt",          .has_arg = no_argument },
6020         { .val = 'm',   .name = "mdt-index",    .has_arg = no_argument },
6021         { .val = 'm',   .name = "mdt_index",    .has_arg = no_argument },
6022 /* find { .val = 'M',   .name = "mtime",        .has_arg = required_argument }*/
6023 /* find { .val = 'n',   .name = "name",         .has_arg = required_argument }*/
6024         { .val = 'N',   .name = "mirror-count", .has_arg = no_argument },
6025         { .val = LFS_MIRROR_INDEX_OPT,
6026                         .name = "mirror-index", .has_arg = required_argument },
6027         { .val = LFS_MIRROR_ID_OPT,
6028                         .name = "mirror-id",    .has_arg = required_argument },
6029         { .val = LFS_NO_FOLLOW_OPT,
6030                         .name = "no-follow",    .has_arg = no_argument },
6031         { .val = 'O',   .name = "obd",          .has_arg = required_argument },
6032         { .val = 'O',   .name = "ost",          .has_arg = required_argument },
6033         { .val = 'p',   .name = "pool",         .has_arg = no_argument },
6034 /* find { .val = 'P',   .name = "print",        .has_arg = no_argument }, */
6035         { .val = 'q',   .name = "quiet",        .has_arg = no_argument },
6036         { .val = 'r',   .name = "recursive",    .has_arg = no_argument },
6037         { .val = 'R',   .name = "raw",          .has_arg = no_argument },
6038         { .val = 'S',   .name = "stripe-size",  .has_arg = no_argument },
6039         { .val = 'S',   .name = "stripe_size",  .has_arg = no_argument },
6040 /* find { .val = 't',   .name = "type",         .has_arg = required_argument }*/
6041 /* dirstripe { .val = 'T', .name = "mdt-count", .has_arg = required_argument }*/
6042 /* find { .val = 'u',   .name = "uid",          .has_arg = required_argument }*/
6043 /* find { .val = 'U',   .name = "user",         .has_arg = required_argument }*/
6044         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
6045 /* dirstripe { .val = 'X',.name = "max-inherit",.has_arg = required_argument }*/
6046 /* setstripe { .val = 'W', .name = "bandwidth", .has_arg = required_argument }*/
6047         { .val = 'y',   .name = "yaml",         .has_arg = no_argument },
6048         { .val = 'z',   .name = "extension-size", .has_arg = no_argument },
6049         { .val = 'z',   .name = "ext-size",     .has_arg = no_argument },
6050         { .name = NULL } };
6051         int c, rc = 0;
6052         int neg_opt = 0;
6053         int pathstart = -1, pathend = -1;
6054         int isoption;
6055         char *end, *tmp;
6056
6057         while ((c = getopt_long(argc, argv,
6058                         "-cdDE::FghiI::LmMNoO:pqrRsSvyz",
6059                         long_opts, NULL)) != -1) {
6060                 if (neg_opt)
6061                         --neg_opt;
6062
6063                 /* '!' is part of option */
6064                 isoption = (c != 1) || (strcmp(optarg, "!") == 0);
6065                 if (!isoption && pathend != -1) {
6066                         fprintf(stderr,
6067                                 "error: %s: filename|dirname must either precede options or follow options\n",
6068                                 argv[0]);
6069                         return CMD_HELP;
6070                 }
6071                 if (!isoption && pathstart == -1)
6072                         pathstart = optind - 1;
6073                 if (isoption && pathstart != -1 && pathend == -1)
6074                         pathend = optind - 2;
6075
6076                 switch (c) {
6077                 case 1:
6078                         /* unknown: opt is "!" */
6079                         if (strcmp(optarg, "!") == 0)
6080                                 neg_opt = 2;
6081                         break;
6082                 case 'c':
6083                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6084                                 param->fp_verbose |= VERBOSE_COUNT;
6085                                 param->fp_max_depth = 0;
6086                         }
6087                         break;
6088                 case LFS_COMP_COUNT_OPT:
6089                         param->fp_verbose |= VERBOSE_COMP_COUNT;
6090                         param->fp_max_depth = 0;
6091                         break;
6092                 case LFS_COMP_FLAGS_OPT:
6093                         if (optarg) {
6094                                 rc = comp_str2flags(optarg,
6095                                                     &param->fp_comp_flags,
6096                                                     &param->fp_comp_neg_flags);
6097                                 if (rc != 0) {
6098                                         fprintf(stderr,
6099                                                 "error: %s bad component flags '%s'.\n",
6100                                                 argv[0], optarg);
6101                                         return CMD_HELP;
6102                                 }
6103                                 param->fp_check_comp_flags = 1;
6104                         } else {
6105                                 param->fp_verbose |= VERBOSE_COMP_FLAGS;
6106                                 param->fp_max_depth = 0;
6107                         }
6108                         break;
6109                 case LFS_COMP_START_OPT:
6110                         if (optarg) {
6111                                 tmp = optarg;
6112                                 if (tmp[0] == '+') {
6113                                         param->fp_comp_start_sign = -1;
6114                                         tmp++;
6115                                 } else if (tmp[0] == '-') {
6116                                         param->fp_comp_start_sign = 1;
6117                                         tmp++;
6118                                 }
6119                                 rc = llapi_parse_size(tmp,
6120                                                 &param->fp_comp_start,
6121                                                 &param->fp_comp_start_units, 0);
6122                                 if (rc != 0) {
6123                                         fprintf(stderr,
6124                                                 "error: %s bad component start '%s'.\n",
6125                                                 argv[0], tmp);
6126                                         return CMD_HELP;
6127                                 }
6128                                 param->fp_check_comp_start = 1;
6129                         } else {
6130                                 param->fp_verbose |= VERBOSE_COMP_START;
6131                                 param->fp_max_depth = 0;
6132                         }
6133                         break;
6134                 case LFS_MIRROR_INDEX_OPT: {
6135                         unsigned long int mirror_index;
6136
6137                         if (optarg[0] == '+') {
6138                                 param->fp_mirror_index_sign = -1;
6139                                 optarg++;
6140                         } else if (optarg[0] == '-') {
6141                                 param->fp_mirror_index_sign = 1;
6142                                 optarg++;
6143                         }
6144
6145                         errno = 0;
6146                         mirror_index = strtoul(optarg, &end, 0);
6147                         if (errno != 0 || *end != '\0' ||
6148                             mirror_index > UINT16_MAX || (mirror_index == 0 &&
6149                             param->fp_mirror_index_sign == 0 && neg_opt == 0)) {
6150                                 fprintf(stderr,
6151                                         "%s %s: invalid mirror index '%s'\n",
6152                                         progname, argv[0], optarg);
6153                                 return CMD_HELP;
6154                         }
6155
6156                         param->fp_mirror_index = (__u16)mirror_index;
6157
6158                         if (param->fp_mirror_id != 0) {
6159                                 fprintf(stderr,
6160                                         "%s %s: can't specify both mirror index and mirror ID\n",
6161                                         progname, argv[0]);
6162                                 return CMD_HELP;
6163                         }
6164                         param->fp_check_mirror_index = 1;
6165                         param->fp_exclude_mirror_index = !!neg_opt;
6166                         break;
6167                 }
6168                 case LFS_MIRROR_ID_OPT: {
6169                         unsigned long int mirror_id;
6170
6171                         if (optarg[0] == '+') {
6172                                 param->fp_mirror_id_sign = -1;
6173                                 optarg++;
6174                         } else if (optarg[0] == '-') {
6175                                 param->fp_mirror_id_sign = 1;
6176                                 optarg++;
6177                         }
6178
6179                         errno = 0;
6180                         mirror_id = strtoul(optarg, &end, 0);
6181                         if (errno != 0 || *end != '\0' ||
6182                             mirror_id > UINT16_MAX || (mirror_id == 0 &&
6183                             param->fp_mirror_id_sign == 0 && neg_opt == 0)) {
6184                                 fprintf(stderr,
6185                                         "%s %s: invalid mirror ID '%s'\n",
6186                                         progname, argv[0], optarg);
6187                                 return CMD_HELP;
6188                         }
6189
6190                         param->fp_mirror_id = (__u16)mirror_id;
6191
6192                         if (param->fp_mirror_index != 0) {
6193                                 fprintf(stderr,
6194                                         "%s %s: can't specify both mirror index and mirror ID\n",
6195                                         progname, argv[0]);
6196                                 return CMD_HELP;
6197                         }
6198                         param->fp_check_mirror_id = 1;
6199                         param->fp_exclude_mirror_id = !!neg_opt;
6200                         break;
6201                 }
6202                 case LFS_NO_FOLLOW_OPT:
6203                         param->fp_no_follow = true;
6204                         break;
6205                 case LFS_HEX_IDX_OPT:
6206                         param->fp_hex_idx = true;
6207                         break;
6208                 case 'd':
6209                         param->fp_max_depth = 0;
6210                         break;
6211                 case 'D':
6212                         param->fp_get_default_lmv = 1;
6213                         break;
6214                 case 'E':
6215                         if (optarg) {
6216                                 tmp = optarg;
6217                                 if (tmp[0] == '+') {
6218                                         param->fp_comp_end_sign = -1;
6219                                         tmp++;
6220                                 } else if (tmp[0] == '-') {
6221                                         param->fp_comp_end_sign = 1;
6222                                         tmp++;
6223                                 }
6224
6225                                 if (arg_is_eof(tmp)) {
6226                                         param->fp_comp_end = LUSTRE_EOF;
6227                                         param->fp_comp_end_units = 1;
6228                                         rc = 0;
6229                                 } else {
6230                                         rc = llapi_parse_size(tmp,
6231                                                 &param->fp_comp_end,
6232                                                 &param->fp_comp_end_units, 0);
6233                                         /* assume units of KB if too small */
6234                                         if (param->fp_comp_end < 4096)
6235                                                 param->fp_comp_end *= 1024;
6236                                 }
6237                                 if (rc != 0) {
6238                                         fprintf(stderr,
6239                                                 "error: %s bad component end '%s'.\n",
6240                                                 argv[0], tmp);
6241                                         return CMD_HELP;
6242                                 }
6243                                 param->fp_check_comp_end = 1;
6244                         } else {
6245                                 param->fp_verbose |= VERBOSE_COMP_END;
6246                                 param->fp_max_depth = 0;
6247                         }
6248                         break;
6249                 case 'F':
6250                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6251                                 param->fp_verbose |= VERBOSE_DFID;
6252                                 param->fp_max_depth = 0;
6253                         }
6254                         break;
6255                 case 'g':
6256                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6257                                 param->fp_verbose |= VERBOSE_GENERATION;
6258                                 param->fp_max_depth = 0;
6259                         }
6260                         break;
6261                 case 'i':
6262                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6263                                 param->fp_verbose |= VERBOSE_STRIPE_OFFSET;
6264                                 param->fp_max_depth = 0;
6265                         }
6266                         break;
6267                 case 'I':
6268                         if (optarg) {
6269                                 param->fp_comp_id = strtoul(optarg, &end, 0);
6270                                 if (*end != '\0' || param->fp_comp_id == 0 ||
6271                                     param->fp_comp_id > LCME_ID_MAX) {
6272                                         fprintf(stderr,
6273                                                 "error: %s bad component id '%s'\n",
6274                                                 argv[0], optarg);
6275                                         return CMD_HELP;
6276                                 }
6277                                 param->fp_check_comp_id = 1;
6278                         } else {
6279                                 param->fp_max_depth = 0;
6280                                 param->fp_verbose |= VERBOSE_COMP_ID;
6281                         }
6282                         break;
6283                 case 'L':
6284                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6285                                 param->fp_verbose |= VERBOSE_PATTERN;
6286                                 param->fp_max_depth = 0;
6287                         }
6288                         break;
6289 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
6290                 case 'M':
6291                         fprintf(stderr,
6292                                 "warning: '-M' deprecated, use '--mdt-index' or '-m' instead\n");
6293 #endif
6294                 case 'm':
6295                         if (!(param->fp_verbose & VERBOSE_DETAIL))
6296                                 param->fp_max_depth = 0;
6297                         param->fp_verbose |= VERBOSE_MDTINDEX;
6298                         break;
6299                 case 'N':
6300                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6301                                 param->fp_verbose |= VERBOSE_MIRROR_COUNT;
6302                                 param->fp_max_depth = 0;
6303                         }
6304                         break;
6305                 case 'O':
6306                         if (param->fp_obd_uuid) {
6307                                 fprintf(stderr,
6308                                         "error: %s: only one obduuid allowed",
6309                                         argv[0]);
6310                                 return CMD_HELP;
6311                         }
6312                         param->fp_obd_uuid = (struct obd_uuid *)optarg;
6313                         break;
6314                 case 'p':
6315                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6316                                 param->fp_verbose |= VERBOSE_POOL;
6317                                 param->fp_max_depth = 0;
6318                         }
6319                         break;
6320                 case 'q':
6321                         param->fp_quiet++;
6322                         break;
6323                 case 'r':
6324                         param->fp_recursive = 1;
6325                         break;
6326                 case 'R':
6327                         param->fp_raw = 1;
6328                         break;
6329                 case 'S':
6330                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6331                                 param->fp_verbose |= VERBOSE_STRIPE_SIZE;
6332                                 param->fp_max_depth = 0;
6333                         }
6334                         break;
6335                 case 'v':
6336                         param->fp_verbose = VERBOSE_DEFAULT | VERBOSE_DETAIL;
6337                         break;
6338                 case 'y':
6339                         param->fp_yaml = 1;
6340                         break;
6341                 case 'z':
6342                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6343                                 param->fp_verbose |= VERBOSE_EXT_SIZE;
6344                                 param->fp_max_depth = 0;
6345                         }
6346                         break;
6347                 default:
6348                         fprintf(stderr, "%s: unrecognized option '%s'\n",
6349                                 progname, argv[optind - 1]);
6350                 case 'h':
6351                         return CMD_HELP;
6352                 }
6353         }
6354
6355         if (pathstart == -1) {
6356                 fprintf(stderr, "error: %s: no filename|pathname\n",
6357                                 argv[0]);
6358                 return CMD_HELP;
6359         } else if (pathend == -1) {
6360                 /* no options */
6361                 pathend = argc;
6362         }
6363
6364         if (pathend > argc)
6365                 return CMD_HELP;
6366
6367         if (param->fp_recursive)
6368                 param->fp_max_depth = -1;
6369         else if (param->fp_verbose & VERBOSE_DETAIL)
6370                 param->fp_max_depth = 1;
6371
6372         if (!param->fp_verbose)
6373                 param->fp_verbose = VERBOSE_DEFAULT;
6374         if (param->fp_quiet)
6375                 param->fp_verbose = VERBOSE_OBJID;
6376
6377         do {
6378                 int rc2;
6379
6380                 rc2 = llapi_getstripe(argv[pathstart], param);
6381                 if (rc2) {
6382                         fprintf(stderr, "%s: %s for '%s' failed: %s\n",
6383                                 progname, argv[0], argv[optind - 1],
6384                                 strerror(-rc2));
6385                         if (!rc)
6386                                 rc = rc2;
6387                 }
6388         } while (++pathstart < pathend);
6389
6390         return rc;
6391 }
6392
6393 static int lfs_tgts(int argc, char **argv)
6394 {
6395         char mntdir[PATH_MAX] = {'\0'}, path[PATH_MAX] = {'\0'};
6396         struct find_param param;
6397         int index = 0, rc = 0;
6398
6399         if (argc > 2)
6400                 return CMD_HELP;
6401
6402         if (argc == 2 && !realpath(argv[1], path)) {
6403                 rc = -errno;
6404                 fprintf(stderr, "error: invalid path '%s': %s\n",
6405                         argv[1], strerror(-rc));
6406                 return rc;
6407         }
6408
6409         while (!llapi_search_mounts(path, index++, mntdir, NULL)) {
6410                 /* Check if we have a mount point */
6411                 if (mntdir[0] == '\0')
6412                         continue;
6413
6414                 memset(&param, 0, sizeof(param));
6415                 if (!strcmp(argv[0], "mdts"))
6416                         param.fp_get_lmv = 1;
6417
6418                 rc = llapi_ostlist(mntdir, &param);
6419                 if (rc) {
6420                         fprintf(stderr, "error: %s: failed on %s\n",
6421                                 argv[0], mntdir);
6422                 }
6423                 if (path[0] != '\0')
6424                         break;
6425                 memset(mntdir, 0, PATH_MAX);
6426         }
6427
6428         return rc;
6429 }
6430
6431 static int lfs_getstripe(int argc, char **argv)
6432 {
6433         struct find_param param = { 0 };
6434
6435         param.fp_max_depth = 1;
6436         return lfs_getstripe_internal(argc, argv, &param);
6437 }
6438
6439 /* functions */
6440 static int lfs_getdirstripe(int argc, char **argv)
6441 {
6442         struct find_param param = { 0 };
6443         struct option long_opts[] = {
6444         { .val = 'c',   .name = "mdt-count",     .has_arg = no_argument },
6445         { .val = 'D',   .name = "default",       .has_arg = no_argument },
6446         { .val = 'h',   .name = "help",         .has_arg = no_argument },
6447         { .val = 'H',   .name = "mdt-hash",      .has_arg = no_argument },
6448         { .val = LFS_HEX_IDX_OPT,
6449                         .name = "hex-idx",       .has_arg = no_argument },
6450         { .val = 'i',   .name = "mdt-index",     .has_arg = no_argument },
6451         { .val = 'm',   .name = "mdt-index",     .has_arg = no_argument },
6452         { .val = 'O',   .name = "obd",           .has_arg = required_argument },
6453         { .val = 'r',   .name = "recursive",     .has_arg = no_argument },
6454         { .val = 'R',   .name = "raw",          .has_arg = no_argument },
6455         { .val = 'T',   .name = "mdt-count",     .has_arg = no_argument },
6456         { .val = 'v',   .name = "verbose",       .has_arg = no_argument },
6457         { .val = 'X',   .name = "max-inherit",   .has_arg = no_argument },
6458         { .val = LFS_INHERIT_RR_OPT,
6459                         .name = "max-inherit-rr", .has_arg = no_argument },
6460         { .val = 'y',   .name = "yaml",          .has_arg = no_argument },
6461         { .name = NULL } };
6462         int c, rc = 0;
6463
6464         param.fp_get_lmv = 1;
6465
6466         while ((c = getopt_long(argc, argv,
6467                                 "cDhHimO:rRtTvXy", long_opts, NULL)) != -1) {
6468                 switch (c) {
6469                 case 'c':
6470                 case 'T':
6471                         param.fp_verbose |= VERBOSE_COUNT;
6472                         break;
6473                 case 'D':
6474                         param.fp_get_default_lmv = 1;
6475                         break;
6476 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
6477                 case 't':
6478                         fprintf(stderr,
6479                                 "warning: '-t' deprecated, use '--mdt-hash' or '-H' instead\n");
6480                         fallthrough;
6481 #endif
6482                 case 'H':
6483                         param.fp_verbose |= VERBOSE_HASH_TYPE;
6484                         break;
6485                 case LFS_HEX_IDX_OPT:
6486                         param.fp_hex_idx = 1;
6487                         break;
6488                 case 'i':
6489                         fallthrough;
6490                 case 'm':
6491                         param.fp_verbose |= VERBOSE_STRIPE_OFFSET;
6492                         break;
6493                 case 'O':
6494                         if (param.fp_obd_uuid) {
6495                                 fprintf(stderr,
6496                                         "%s: only one obduuid allowed",
6497                                         progname);
6498                                 return CMD_HELP;
6499                         }
6500                         param.fp_obd_uuid = (struct obd_uuid *)optarg;
6501                         break;
6502                 case 'r':
6503                         param.fp_recursive = 1;
6504                         break;
6505                 case 'R':
6506                         param.fp_raw = 1;
6507                         break;
6508                 case 'v':
6509                         param.fp_verbose |= VERBOSE_DEFAULT;
6510                         param.fp_verbose |= VERBOSE_DETAIL;
6511                         break;
6512                 case 'X':
6513                         param.fp_verbose |= VERBOSE_INHERIT;
6514                         break;
6515                 case LFS_INHERIT_RR_OPT:
6516                         param.fp_verbose |= VERBOSE_INHERIT_RR;
6517                         break;
6518                 case 'y':
6519                         param.fp_yaml = 1;
6520                         break;
6521                 default:
6522                         fprintf(stderr, "%s: unrecognized option '%s'\n",
6523                                 progname, argv[optind - 1]);
6524                         fallthrough;
6525                 case 'h':
6526                         return CMD_HELP;
6527                 }
6528         }
6529
6530         if (optind >= argc)
6531                 return CMD_HELP;
6532
6533         if (param.fp_recursive)
6534                 param.fp_max_depth = -1;
6535
6536         if (!param.fp_verbose)
6537                 param.fp_verbose = VERBOSE_DEFAULT;
6538
6539         do {
6540                 int rc2;
6541
6542                 rc2 = llapi_getstripe(argv[optind], &param);
6543                 if (rc2) {
6544                         fprintf(stderr, "%s: %s for '%s' failed: %s\n",
6545                                 progname, argv[0], argv[optind],
6546                                 strerror(-rc2));
6547                         if (!rc)
6548                                 rc = rc2;
6549                 }
6550         } while (++optind < argc);
6551
6552         return rc;
6553 }
6554
6555 enum mntdf_flags {
6556         MNTDF_INODES    = 0x0001,
6557         MNTDF_COOKED    = 0x0002,
6558         MNTDF_LAZY      = 0x0004,
6559         MNTDF_VERBOSE   = 0x0008,
6560         MNTDF_SHOW      = 0x0010,
6561         MNTDF_DECIMAL   = 0x0020,
6562 };
6563
6564 #define COOK(value, base)                                       \
6565 ({                                                              \
6566         int radix = 0;                                          \
6567         while (value > base) {                                  \
6568                 value /= base;                                  \
6569                 radix++;                                        \
6570         }                                                       \
6571         radix;                                                  \
6572 })
6573 #define UUF     "%-20s"
6574 #define CSF     "%11s"
6575 #define CDF     "%11llu"
6576 #define HDF     "%8.1f%c"
6577 #define RSF     "%4s"
6578 #define RDF     "%3d%%"
6579
6580 static inline int obd_statfs_ratio(const struct obd_statfs *st, bool inodes)
6581 {
6582         double avail, used, ratio = 0;
6583
6584         if (inodes) {
6585                 avail = st->os_ffree;
6586                 used = st->os_files - st->os_ffree;
6587         } else {
6588                 avail = st->os_bavail;
6589                 used = st->os_blocks - st->os_bfree;
6590         }
6591         if (avail + used > 0)
6592                 ratio = used / (used + avail) * 100;
6593
6594         /* Round up to match df(1) usage percentage */
6595         return (ratio - (int)ratio) > 0 ? (int)(ratio + 1) : (int)ratio;
6596 }
6597
6598 /*
6599  * This is to identify various problem states for "lfs df" if .osn_err = true,
6600  * so only show flags reflecting those states by default. Informational states
6601  * are only shown with "-v" and use lower-case names to distinguish them.
6602  * UNUSED[12] were for "EROFS = 30" until 1.6 but are now available for use.
6603  */
6604 static struct obd_statfs_state_names {
6605         enum obd_statfs_state   osn_state;
6606         const char              osn_name;
6607         bool                    osn_err;
6608 } oss_names[] = {
6609         { .osn_state = OS_STATFS_DEGRADED,   .osn_name = 'D', .osn_err = true },
6610         { .osn_state = OS_STATFS_READONLY,   .osn_name = 'R', .osn_err = true },
6611         { .osn_state = OS_STATFS_NOPRECREATE,.osn_name = 'N', .osn_err = true },
6612         { .osn_state = OS_STATFS_UNUSED1,    .osn_name = '?', .osn_err = true },
6613         { .osn_state = OS_STATFS_UNUSED2,    .osn_name = '?', .osn_err = true },
6614         { .osn_state = OS_STATFS_ENOSPC,     .osn_name = 'S', .osn_err = true },
6615         { .osn_state = OS_STATFS_ENOINO,     .osn_name = 'I', .osn_err = true },
6616         { .osn_state = OS_STATFS_SUM,        .osn_name = 'a', /* aggregate */ },
6617         { .osn_state = OS_STATFS_NONROT,     .osn_name = 'f', /* flash */     },
6618 };
6619
6620 static int showdf(char *mntdir, struct obd_statfs *stat,
6621                   char *uuid, enum mntdf_flags flags,
6622                   char *type, int index, int rc)
6623 {
6624         long long avail, used, total;
6625         int ratio = 0;
6626         char *suffix = flags & MNTDF_DECIMAL ? "kMGTPEZY" : "KMGTPEZY";
6627         /* Note if we have >2^64 bytes/fs these buffers will need to be grown */
6628         char tbuf[3 * sizeof(__u64)];
6629         char ubuf[3 * sizeof(__u64)];
6630         char abuf[3 * sizeof(__u64)];
6631         char rbuf[3 * sizeof(__u64)];
6632
6633         if (!uuid || !stat)
6634                 return -EINVAL;
6635
6636         switch (rc) {
6637         case 0:
6638                 if (flags & MNTDF_INODES) {
6639                         avail = stat->os_ffree;
6640                         used = stat->os_files - stat->os_ffree;
6641                         total = stat->os_files;
6642                 } else {
6643                         int shift = flags & MNTDF_COOKED ? 0 : 10;
6644
6645                         avail = (stat->os_bavail * stat->os_bsize) >> shift;
6646                         used  = ((stat->os_blocks - stat->os_bfree) *
6647                                  stat->os_bsize) >> shift;
6648                         total = (stat->os_blocks * stat->os_bsize) >> shift;
6649                 }
6650
6651                 ratio = obd_statfs_ratio(stat, flags & MNTDF_INODES);
6652
6653                 if (flags & MNTDF_COOKED) {
6654                         int base = flags & MNTDF_DECIMAL ? 1000 : 1024;
6655                         double cook_val;
6656                         int i;
6657
6658                         cook_val = (double)total;
6659                         i = COOK(cook_val, base);
6660                         if (i > 0)
6661                                 snprintf(tbuf, sizeof(tbuf), HDF, cook_val,
6662                                          suffix[i - 1]);
6663                         else
6664                                 snprintf(tbuf, sizeof(tbuf), CDF, total);
6665
6666                         cook_val = (double)used;
6667                         i = COOK(cook_val, base);
6668                         if (i > 0)
6669                                 snprintf(ubuf, sizeof(ubuf), HDF, cook_val,
6670                                          suffix[i - 1]);
6671                         else
6672                                 snprintf(ubuf, sizeof(ubuf), CDF, used);
6673
6674                         cook_val = (double)avail;
6675                         i = COOK(cook_val, base);
6676                         if (i > 0)
6677                                 snprintf(abuf, sizeof(abuf), HDF, cook_val,
6678                                          suffix[i - 1]);
6679                         else
6680                                 snprintf(abuf, sizeof(abuf), CDF, avail);
6681                 } else {
6682                         snprintf(tbuf, sizeof(tbuf), CDF, total);
6683                         snprintf(ubuf, sizeof(tbuf), CDF, used);
6684                         snprintf(abuf, sizeof(tbuf), CDF, avail);
6685                 }
6686
6687                 sprintf(rbuf, RDF, ratio);
6688                 printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s",
6689                        uuid, tbuf, ubuf, abuf, rbuf, mntdir);
6690                 if (type)
6691                         printf("[%s:%d]", type, index);
6692
6693                 if (stat->os_state) {
6694                         uint32_t i;
6695
6696                         printf(" ");
6697                         for (i = 0; i < ARRAY_SIZE(oss_names); i++) {
6698                                 if (oss_names[i].osn_state & stat->os_state &&
6699                                     (oss_names[i].osn_err ||
6700                                      flags & MNTDF_VERBOSE))
6701                                         printf("%c", oss_names[i].osn_name);
6702                         }
6703                 }
6704
6705                 printf("\n");
6706                 break;
6707         case -ENODATA:
6708                 printf(UUF": inactive device\n", uuid);
6709                 break;
6710         default:
6711                 printf(UUF": %s\n", uuid, strerror(-rc));
6712                 break;
6713         }
6714
6715         return 0;
6716 }
6717
6718 struct ll_stat_type {
6719         int   st_op;
6720         char *st_name;
6721 };
6722
6723 #define LL_STATFS_MAX   LOV_MAX_STRIPE_COUNT
6724
6725 struct ll_statfs_data {
6726         int                     sd_index;
6727         struct obd_statfs       sd_st;
6728 };
6729
6730 struct ll_statfs_buf {
6731         int                     sb_count;
6732         struct ll_statfs_data   sb_buf[LL_STATFS_MAX];
6733 };
6734
6735 static int mntdf(char *mntdir, char *fsname, char *pool, enum mntdf_flags flags,
6736                  int ops, struct ll_statfs_buf *lsb)
6737 {
6738         struct obd_statfs stat_buf, sum = { .os_bsize = 1 };
6739         struct obd_uuid uuid_buf;
6740         char *poolname = NULL;
6741         struct ll_stat_type types[] = {
6742                 { .st_op = LL_STATFS_LMV,       .st_name = "MDT" },
6743                 { .st_op = LL_STATFS_LOV,       .st_name = "OST" },
6744                 { .st_name = NULL } };
6745         struct ll_stat_type *tp;
6746         __u64 ost_files = 0;
6747         __u64 ost_ffree = 0;
6748         __u32 index;
6749         __u32 type;
6750         int fd;
6751         int rc = 0;
6752         int rc2;
6753
6754         if (pool) {
6755                 poolname = strchr(pool, '.');
6756                 if (poolname) {
6757                         if (strncmp(fsname, pool, strlen(fsname))) {
6758                                 fprintf(stderr, "filesystem name incorrect\n");
6759                                 return -ENODEV;
6760                         }
6761                         poolname++;
6762                 } else
6763                         poolname = pool;
6764         }
6765
6766         fd = open(mntdir, O_RDONLY);
6767         if (fd < 0) {
6768                 rc = -errno;
6769                 fprintf(stderr, "%s: cannot open '%s': %s\n", progname, mntdir,
6770                         strerror(errno));
6771                 return rc;
6772         }
6773
6774         if (flags & MNTDF_SHOW) {
6775                 if (flags & MNTDF_INODES)
6776                         printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s\n",
6777                                "UUID", "Inodes", "IUsed", "IFree",
6778                                "IUse%", "Mounted on");
6779                 else
6780                         printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s\n",
6781                                "UUID",
6782                                flags & MNTDF_COOKED ? "bytes" : "1K-blocks",
6783                                "Used", "Available", "Use%", "Mounted on");
6784         }
6785
6786         for (tp = types; tp->st_name != NULL; tp++) {
6787                 bool have_ost = false;
6788
6789                 if (!(tp->st_op & ops))
6790                         continue;
6791
6792                 for (index = 0; index < LOV_ALL_STRIPES &&
6793                      (!lsb || lsb->sb_count < LL_STATFS_MAX); index++) {
6794                         memset(&stat_buf, 0, sizeof(struct obd_statfs));
6795                         memset(&uuid_buf, 0, sizeof(struct obd_uuid));
6796                         type = flags & MNTDF_LAZY ?
6797                                 tp->st_op | LL_STATFS_NODELAY : tp->st_op;
6798                         rc2 = llapi_obd_fstatfs(fd, type, index,
6799                                                 &stat_buf, &uuid_buf);
6800                         if (rc2 == -ENODEV)
6801                                 break;
6802                         if (rc2 == -EAGAIN)
6803                                 continue;
6804                         if (rc2 == -ENODATA) { /* Inactive device, OK. */
6805                                 if (!(flags & MNTDF_VERBOSE))
6806                                         continue;
6807                         } else if (rc2 < 0 && rc == 0) {
6808                                 rc = rc2;
6809                         }
6810
6811                         /*
6812                          * If we have OSTs then don't report MDT block counts.
6813                          * For MDT-only filesystems the expectation is that all
6814                          * layouts have a DoM component.  For filesystems with
6815                          * OSTs, files are not necessarily going to store data
6816                          * on MDTs, and MDT space is limited to a fraction of
6817                          * OST space, so don't include it in the summary.
6818                          */
6819                         if (tp->st_op == LL_STATFS_LOV && !have_ost) {
6820                                 have_ost = true;
6821                                 sum.os_blocks = 0;
6822                                 sum.os_bfree = 0;
6823                                 sum.os_bavail = 0;
6824                         }
6825
6826                         if (poolname && tp->st_op == LL_STATFS_LOV &&
6827                             llapi_search_ost(fsname, poolname,
6828                                              obd_uuid2str(&uuid_buf)) != 1)
6829                                 continue;
6830
6831                         /*
6832                          * the llapi_obd_fstatfs() call may have returned with
6833                          * an error, but if it filled in uuid_buf we will at
6834                          * lease use that to print out a message for that OBD.
6835                          * If we didn't get anything in the uuid_buf, then fill
6836                          * it in so that we can print an error message.
6837                          */
6838                         if (uuid_buf.uuid[0] == '\0')
6839                                 snprintf(uuid_buf.uuid, sizeof(uuid_buf.uuid),
6840                                          "%s%04x", tp->st_name, index);
6841                         if (!rc && lsb) {
6842                                 lsb->sb_buf[lsb->sb_count].sd_index = index;
6843                                 lsb->sb_buf[lsb->sb_count].sd_st = stat_buf;
6844                                 lsb->sb_count++;
6845                         }
6846                         if (flags & MNTDF_SHOW)
6847                                 showdf(mntdir, &stat_buf,
6848                                        obd_uuid2str(&uuid_buf), flags,
6849                                        tp->st_name, index, rc2);
6850
6851                         if (rc2)
6852                                 continue;
6853
6854                         if (tp->st_op == LL_STATFS_LMV) {
6855                                 sum.os_ffree += stat_buf.os_ffree;
6856                                 sum.os_files += stat_buf.os_files;
6857                         } else /* if (tp->st_op == LL_STATFS_LOV) */ {
6858                                 ost_files += stat_buf.os_files;
6859                                 ost_ffree += stat_buf.os_ffree;
6860                         }
6861                         sum.os_blocks += stat_buf.os_blocks *
6862                                          stat_buf.os_bsize;
6863                         sum.os_bfree  += stat_buf.os_bfree *
6864                                          stat_buf.os_bsize;
6865                         sum.os_bavail += stat_buf.os_bavail *
6866                                          stat_buf.os_bsize;
6867                 }
6868         }
6869
6870         close(fd);
6871
6872         /*
6873          * If we have _some_ OSTs, but don't have as many free objects on the
6874          * OST as inodes on the MDTs, reduce the reported number of inodes
6875          * to compensate, so that the "inodes in use" number is correct.
6876          * This should be kept in sync with ll_statfs_internal().
6877          */
6878         if (ost_files && ost_ffree < sum.os_ffree) {
6879                 sum.os_files = (sum.os_files - sum.os_ffree) + ost_ffree;
6880                 sum.os_ffree = ost_ffree;
6881         }
6882         if (flags & MNTDF_SHOW) {
6883                 printf("\n");
6884                 showdf(mntdir, &sum, "filesystem_summary:", flags, NULL, 0, 0);
6885                 printf("\n");
6886         }
6887
6888         return rc;
6889 }
6890
6891 enum {
6892         LAYOUT_INHERIT_UNSET    = -2,
6893 };
6894
6895 /* functions */
6896 static int lfs_setdirstripe(int argc, char **argv)
6897 {
6898         char *dname;
6899         struct lfs_setstripe_args lsa = { 0 };
6900         struct llapi_stripe_param *param = NULL;
6901         __u32 mdts[LMV_MAX_STRIPE_COUNT] = { 0 };
6902         char *end;
6903         int c;
6904         char *mode_opt = NULL;
6905         bool default_stripe = false;
6906         bool delete = false;
6907         bool foreign_mode = false;
6908         bool mdt_count_set = false;
6909         mode_t mode = S_IRWXU | S_IRWXG | S_IRWXO;
6910         mode_t previous_mode = 0;
6911         char *xattr = NULL;
6912         __u32 type = LU_FOREIGN_TYPE_SYMLINK, flags = 0;
6913         int max_inherit = LAYOUT_INHERIT_UNSET;
6914         int max_inherit_rr = LAYOUT_INHERIT_UNSET;
6915         struct option long_opts[] = {
6916         { .val = 'c',   .name = "count",        .has_arg = required_argument },
6917         { .val = 'c',   .name = "mdt-count",    .has_arg = required_argument },
6918         { .val = 'd',   .name = "delete",       .has_arg = no_argument },
6919         { .val = 'D',   .name = "default",      .has_arg = no_argument },
6920         { .val = 'D',   .name = "default_stripe", .has_arg = no_argument },
6921         { .val = LFS_LAYOUT_FLAGS_OPT,
6922                         .name = "flags",        .has_arg = required_argument },
6923         { .val = LFS_LAYOUT_FOREIGN_OPT,
6924                         .name = "foreign",      .has_arg = optional_argument},
6925         { .val = 'h',   .name = "help",         .has_arg = no_argument },
6926         { .val = 'H',   .name = "mdt-hash",     .has_arg = required_argument },
6927 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 17, 53, 0)
6928         { .val = 'i',   .name = "mdt-index",    .has_arg = required_argument },
6929         { .val = 'i',   .name = "mdt",          .has_arg = required_argument },
6930 #else
6931 /* find { .val = 'l',   .name = "lazy",         .has_arg = no_argument }, */
6932         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument },
6933         { .val = 'm',   .name = "mdt",          .has_arg = required_argument },
6934 #endif
6935 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
6936         { .val = 'i',   .name = "index",        .has_arg = required_argument },
6937 #endif
6938         { .val = 'o',   .name = "mode",         .has_arg = required_argument },
6939 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
6940         { .val = 't',   .name = "hash-type",    .has_arg = required_argument },
6941 #endif
6942         { .val = 'T',   .name = "mdt-count",    .has_arg = required_argument },
6943         { .val = 'x',   .name = "xattr",        .has_arg = required_argument },
6944         { .val = 'X',   .name = "max-inherit",  .has_arg = required_argument },
6945         { .val = LFS_INHERIT_RR_OPT,
6946                         .name = "max-inherit-rr", .has_arg = required_argument},
6947 /* setstripe { .val = 'y', .name = "yaml",      .has_arg = no_argument }, */
6948 /* setstripe { .val = 'W', .name = "bandwidth", .has_arg = required_argument }, */
6949         { .name = NULL } };
6950         int result = 0;
6951
6952         setstripe_args_init(&lsa);
6953
6954         while ((c = getopt_long(argc, argv, "c:dDi:hH:m:o:t:T:x:X:",
6955                                 long_opts, NULL)) >= 0) {
6956                 switch (c) {
6957                 case 0:
6958                         /* Long options. */
6959                         break;
6960                 case 'c':
6961                 case 'T':
6962                         errno = 0;
6963                         lsa.lsa_stripe_count = strtoul(optarg, &end, 0);
6964                         if (errno != 0 || *end != '\0' ||
6965                             lsa.lsa_stripe_count < -1 ||
6966                             lsa.lsa_stripe_count > LOV_MAX_STRIPE_COUNT) {
6967                                 fprintf(stderr,
6968                                         "%s: invalid stripe count '%s'\n",
6969                                         progname, optarg);
6970                                 return CMD_HELP;
6971                         }
6972                         mdt_count_set = true;
6973                         break;
6974                 case 'd':
6975                         delete = true;
6976                         default_stripe = true;
6977                         break;
6978                 case 'D':
6979                         default_stripe = true;
6980                         break;
6981                 case LFS_LAYOUT_FOREIGN_OPT:
6982                         if (optarg) {
6983                                 /* check pure numeric */
6984                                 type = strtoul(optarg, &end, 0);
6985                                 if (*end) {
6986                                         /* check name */
6987                                         type = check_foreign_type_name(optarg);
6988                                         if (type == LU_FOREIGN_TYPE_UNKNOWN) {
6989                                                 fprintf(stderr,
6990                                                         "%s %s: unknown foreign type '%s'\n",
6991                                                         progname, argv[0],
6992                                                         optarg);
6993                                                 return CMD_HELP;
6994                                         }
6995                                 } else if (type >= UINT32_MAX) {
6996                                         fprintf(stderr,
6997                                                 "%s %s: invalid foreign type '%s'\n",
6998                                                 progname, argv[0], optarg);
6999                                         return CMD_HELP;
7000                                 }
7001                         }
7002                         foreign_mode = true;
7003                         break;
7004                 case LFS_LAYOUT_FLAGS_OPT:
7005                         errno = 0;
7006                         flags = strtoul(optarg, &end, 16);
7007                         if (errno != 0 || *end != '\0' ||
7008                             flags >= UINT32_MAX) {
7009                                 fprintf(stderr,
7010                                         "%s %s: invalid hex flags '%s'\n",
7011                                         progname, argv[0], optarg);
7012                                 return CMD_HELP;
7013                         }
7014                         if (!foreign_mode) {
7015                                 fprintf(stderr,
7016                                         "%s %s: hex flags must be specified with --foreign option\n",
7017                                         progname, argv[0]);
7018                                 return CMD_HELP;
7019                         }
7020                         break;
7021 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
7022                 case 't':
7023                         fprintf(stderr,
7024                                 "warning: '--hash-type' and '-t' deprecated, use '--mdt-hash' or '-H' instead\n");
7025                         fallthrough;
7026 #endif
7027                 case 'H':
7028                         lsa.lsa_pattern = check_hashtype(optarg);
7029                         if (lsa.lsa_pattern == 0) {
7030                                 fprintf(stderr,
7031                                         "%s %s: bad directory hash type '%s'\n",
7032                                         progname, argv[0], optarg);
7033                                 return CMD_HELP;
7034                         }
7035                         break;
7036                 case 'i':
7037 #if LUSTRE_VERSION_CODE >= OBD_OCD_VERSION(2, 17, 53, 0)
7038                 case 'm':
7039 #endif
7040 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
7041                         if (strcmp(argv[optind - 1], "--index") == 0)
7042                                 fprintf(stderr,
7043                                         "%s %s: warning: '--index' deprecated, use '--mdt-index' instead\n",
7044                                         progname, argv[0]);
7045 #endif
7046                         lsa.lsa_nr_tgts = parse_targets(mdts,
7047                                                 sizeof(mdts) / sizeof(__u32),
7048                                                 lsa.lsa_nr_tgts, optarg, NULL);
7049                         if (lsa.lsa_nr_tgts < 0) {
7050                                 fprintf(stderr,
7051                                         "%s %s: invalid MDT target(s) '%s'\n",
7052                                         progname, argv[0], optarg);
7053                                 return CMD_HELP;
7054                         }
7055
7056                         lsa.lsa_tgts = mdts;
7057                         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
7058                                 lsa.lsa_stripe_off = mdts[0];
7059                         break;
7060                 case 'o':
7061                         mode_opt = optarg;
7062                         break;
7063                 case 'x':
7064                         xattr = optarg;
7065                         break;
7066                 case 'X':
7067                         errno = 0;
7068                         max_inherit = strtol(optarg, &end, 10);
7069                         if (errno != 0 || *end != '\0' || max_inherit < -2) {
7070                                 fprintf(stderr,
7071                                         "%s %s: invalid max-inherit '%s'\n",
7072                                         progname, argv[0], optarg);
7073                                 return CMD_HELP;
7074                         }
7075                         if (max_inherit == 0) {
7076                                 max_inherit = LMV_INHERIT_NONE;
7077                         } else if (max_inherit == -1) {
7078                                 max_inherit = LMV_INHERIT_UNLIMITED;
7079                         } else if (max_inherit > LMV_INHERIT_MAX) {
7080                                 fprintf(stderr,
7081                                         "%s %s: max-inherit %d exceeds maximum %u\n",
7082                                         progname, argv[0], max_inherit,
7083                                         LMV_INHERIT_MAX);
7084                                 return CMD_HELP;
7085                         }
7086                         break;
7087                 case LFS_INHERIT_RR_OPT:
7088                         if (!default_stripe) {
7089                                 fprintf(stderr,
7090                                         "%s %s: '--max-inherit-rr' must be specified with '-D'\n",
7091                                         progname, argv[0]);
7092                                 return CMD_HELP;
7093                         }
7094                         errno = 0;
7095                         max_inherit_rr = strtol(optarg, &end, 10);
7096                         if (errno != 0 || *end != '\0' || max_inherit_rr < -2) {
7097                                 fprintf(stderr,
7098                                         "%s %s: invalid max-inherit-rr '%s'\n",
7099                                         progname, argv[0], optarg);
7100                                 return CMD_HELP;
7101                         }
7102                         if (max_inherit_rr == 0) {
7103                                 max_inherit_rr = LMV_INHERIT_RR_NONE;
7104                         } else if (max_inherit_rr == -1) {
7105                                 max_inherit_rr = LMV_INHERIT_RR_UNLIMITED;
7106                         } else if (max_inherit_rr > LMV_INHERIT_RR_MAX) {
7107                                 fprintf(stderr,
7108                                         "%s %s: max-inherit-rr %d exceeds maximum %u\n",
7109                                         progname, argv[0], max_inherit_rr,
7110                                         LMV_INHERIT_RR_MAX);
7111                                 return CMD_HELP;
7112                         }
7113                         break;
7114                 default:
7115                         fprintf(stderr, "%s: unrecognized option '%s'\n",
7116                                 progname, argv[optind - 1]);
7117                         fallthrough;
7118                 case 'h':
7119                         return CMD_HELP;
7120                 }
7121         }
7122
7123         if (optind == argc) {
7124                 fprintf(stderr, "%s %s: DIR must be specified\n",
7125                         progname, argv[0]);
7126                 return CMD_HELP;
7127         }
7128
7129         if (xattr && !foreign_mode) {
7130                 /*
7131                  * only print a warning as this is armless and will be
7132                  * ignored
7133                  */
7134                 fprintf(stderr,
7135                         "%s %s: xattr has been specified for non-foreign layout\n",
7136                         progname, argv[0]);
7137         } else if (foreign_mode && !xattr) {
7138                 fprintf(stderr,
7139                         "%s %s: xattr must be provided in foreign mode\n",
7140                         progname, argv[0]);
7141                 return CMD_HELP;
7142         }
7143
7144         if (foreign_mode && (delete || default_stripe || lsa.lsa_nr_tgts ||
7145             lsa.lsa_tgts || setstripe_args_specified(&lsa))) {
7146                 fprintf(stderr,
7147                         "%s %s: only --xattr/--flags/--mode options are valid with --foreign\n",
7148                         progname, argv[0]);
7149                 return CMD_HELP;
7150         }
7151
7152         if (!delete && lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT &&
7153             lsa.lsa_stripe_count == LLAPI_LAYOUT_DEFAULT && !foreign_mode) {
7154                 /* if no parameters set, create directory on least-used MDTs */
7155                 lsa.lsa_stripe_off = LMV_OFFSET_DEFAULT;
7156                 lsa.lsa_stripe_count = 1;
7157         }
7158
7159         if (delete &&
7160             (lsa.lsa_stripe_off != LLAPI_LAYOUT_DEFAULT ||
7161              lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT)) {
7162                 fprintf(stderr,
7163                         "%s %s: cannot specify -d with -c or -i options\n",
7164                         progname, argv[0]);
7165                 return CMD_HELP;
7166         }
7167
7168         if (mode_opt) {
7169                 mode = strtoul(mode_opt, &end, 8);
7170                 if (*end != '\0') {
7171                         fprintf(stderr,
7172                                 "%s %s: bad MODE '%s'\n",
7173                                 progname, argv[0], mode_opt);
7174                         return CMD_HELP;
7175                 }
7176                 previous_mode = umask(0);
7177         }
7178
7179         /* check max-inherit and warn user in some cases */
7180         if (default_stripe &&
7181             (lsa.lsa_stripe_count < 0 || lsa.lsa_stripe_count > 1)) {
7182                 if (max_inherit == LMV_INHERIT_UNLIMITED)
7183                         fprintf(stderr,
7184                         "%s %s: unrecommended max-inherit=-1 when default stripe-count=%lld\n",
7185                         progname, argv[0], lsa.lsa_stripe_count);
7186                 else if (max_inherit > LMV_INHERIT_DEFAULT_STRIPED + 2 &&
7187                          max_inherit != LMV_INHERIT_NONE)
7188                         fprintf(stderr,
7189                                 "%s %s: unrecommended max-inherit=%d when default stripe-count=%lld\n",
7190                                 progname, argv[0], max_inherit,
7191                                 lsa.lsa_stripe_count);
7192         }
7193
7194         if (default_stripe && lsa.lsa_nr_tgts > 1 && !mdt_count_set) {
7195                 fprintf(stderr,
7196                         "%s %s: trying to create unrecommended default striped directory layout,\n"
7197                         "       '-D -i x,y,z' will stripe every new directory across all MDTs,\n"
7198                         "       add -c with the number of MDTs to do this anyway\n",
7199                         progname, argv[0]);
7200                 return CMD_HELP;
7201         }
7202
7203         if (max_inherit_rr != LAYOUT_INHERIT_UNSET &&
7204             lsa.lsa_stripe_off != LLAPI_LAYOUT_DEFAULT &&
7205             lsa.lsa_stripe_off != LMV_OFFSET_DEFAULT) {
7206                 fprintf(stderr,
7207                         "%s %s: max-inherit-rr needs mdt-index=-1, not %lld\n",
7208                         progname, argv[0], lsa.lsa_stripe_off);
7209                 return CMD_HELP;
7210         }
7211
7212         /* foreign LMV/dir case */
7213         if (foreign_mode) {
7214                 if (argc > optind + 1) {
7215                         fprintf(stderr,
7216                                 "%s %s: cannot specify multiple foreign dirs\n",
7217                                 progname, argv[0]);
7218                         return CMD_HELP;
7219                 }
7220
7221                 dname = argv[optind];
7222                 result = llapi_dir_create_foreign(dname, mode, type, flags,
7223                                                   xattr);
7224                 if (result != 0)
7225                         fprintf(stderr,
7226                                 "%s mkdir: can't create foreign dir '%s': %s\n",
7227                                 progname, dname, strerror(-result));
7228                 return result;
7229         }
7230
7231         /*
7232          * initialize stripe parameters, in case param is converted to specific,
7233          * i.e, 'lfs mkdir -i -1 -c N', always allocate space for lsp_tgts.
7234          */
7235         param = calloc(1, offsetof(typeof(*param),
7236                        lsp_tgts[lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT ?
7237                                 lsa.lsa_stripe_count : lsa.lsa_nr_tgts]));
7238         if (!param) {
7239                 fprintf(stderr,
7240                         "%s %s: cannot allocate memory for parameters: %s\n",
7241                         progname, argv[0], strerror(ENOMEM));
7242                 return CMD_HELP;
7243         }
7244
7245         /* if "lfs setdirstripe -D -i -1" is used, assume 1-stripe directory */
7246         if (default_stripe && lsa.lsa_stripe_off == LMV_OFFSET_DEFAULT &&
7247             (lsa.lsa_stripe_count == LLAPI_LAYOUT_DEFAULT ||
7248              lsa.lsa_stripe_count == 0))
7249                 lsa.lsa_stripe_count = 1;
7250         if (lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT)
7251                 param->lsp_stripe_count = lsa.lsa_stripe_count;
7252         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
7253                 param->lsp_stripe_offset = LMV_OFFSET_DEFAULT;
7254         else
7255                 param->lsp_stripe_offset = lsa.lsa_stripe_off;
7256         if (lsa.lsa_pattern != LLAPI_LAYOUT_RAID0)
7257                 param->lsp_stripe_pattern = lsa.lsa_pattern;
7258         else
7259                 param->lsp_stripe_pattern = LMV_HASH_TYPE_UNKNOWN;
7260         param->lsp_pool = lsa.lsa_pool_name;
7261         param->lsp_is_specific = false;
7262
7263         if (max_inherit == LAYOUT_INHERIT_UNSET) {
7264                 if (lsa.lsa_stripe_count == 0 || lsa.lsa_stripe_count == 1 ||
7265                     lsa.lsa_stripe_count == LLAPI_LAYOUT_DEFAULT)
7266                         max_inherit = LMV_INHERIT_DEFAULT_PLAIN;
7267                 else
7268                         max_inherit = LMV_INHERIT_DEFAULT_STRIPED;
7269         }
7270         param->lsp_max_inherit = max_inherit;
7271         if (default_stripe) {
7272
7273                 if (max_inherit_rr == LAYOUT_INHERIT_UNSET)
7274                         max_inherit_rr = LMV_INHERIT_RR_DEFAULT;
7275                 param->lsp_max_inherit_rr = max_inherit_rr;
7276         }
7277         if (strcmp(argv[0], "mkdir") == 0)
7278                 param->lsp_is_create = true;
7279         if (lsa.lsa_nr_tgts > 1) {
7280                 if (lsa.lsa_stripe_count > 0 &&
7281                     lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT &&
7282                     lsa.lsa_stripe_count != lsa.lsa_nr_tgts) {
7283                         fprintf(stderr,
7284                                 "error: %s: stripe count %lld doesn't match the number of MDTs: %d\n",
7285                                 argv[0], lsa.lsa_stripe_count,
7286                                 lsa.lsa_nr_tgts);
7287                         free(param);
7288                         return CMD_HELP;
7289                 }
7290
7291                 param->lsp_is_specific = true;
7292                 param->lsp_stripe_count = lsa.lsa_nr_tgts;
7293                 memcpy(param->lsp_tgts, mdts, sizeof(*mdts) * lsa.lsa_nr_tgts);
7294         }
7295
7296         dname = argv[optind];
7297         do {
7298                 if (default_stripe) {
7299                         result = llapi_dir_set_default_lmv(dname, param);
7300                         if (result)
7301                                 fprintf(stderr,
7302                                         "%s setdirstripe: cannot set default stripe on dir '%s': %s\n",
7303                                         progname, dname, strerror(-result));
7304                         continue;
7305                 }
7306
7307                 result = llapi_dir_create(dname, mode, param);
7308                 if (result)
7309                         fprintf(stderr,
7310                                 "%s setdirstripe: cannot create dir '%s': %s\n",
7311                                 progname, dname, strerror(-result));
7312         } while (!result && (dname = argv[++optind]));
7313
7314         if (mode_opt)
7315                 umask(previous_mode);
7316
7317         free(param);
7318         return result;
7319 }
7320
7321 static int lfs_rmentry(int argc, char **argv)
7322 {
7323         char *dname;
7324         int index;
7325         int result = 0;
7326
7327         if (argc <= 1) {
7328                 fprintf(stderr, "error: %s: missing dirname\n",
7329                         argv[0]);
7330                 return CMD_HELP;
7331         }
7332
7333         index = 1;
7334         dname = argv[index];
7335         while (dname) {
7336                 int rc2;
7337
7338                 rc2 = llapi_direntry_remove(dname);
7339                 if (rc2) {
7340                         fprintf(stderr,
7341                                 "%s %s: remove dir entry '%s' failed: %s\n",
7342                                 progname, argv[0], dname, strerror(-rc2));
7343                         if (!result)
7344                                 result = rc2;
7345                 }
7346                 dname = argv[++index];
7347         }
7348         return result;
7349 }
7350
7351 static int lfs_unlink_foreign(int argc, char **argv)
7352 {
7353         char *name;
7354         int   index;
7355         int   result = 0;
7356
7357         if (argc <= 1) {
7358                 fprintf(stderr, "error: %s: missing pathname\n",
7359                         argv[0]);
7360                 return CMD_HELP;
7361         }
7362
7363         index = 1;
7364         name = argv[index];
7365         while (name != NULL) {
7366                 result = llapi_unlink_foreign(name);
7367                 if (result) {
7368                         fprintf(stderr,
7369                                 "error: %s: unlink foreign entry '%s' failed\n",
7370                                 argv[0], name);
7371                         break;
7372                 }
7373                 name = argv[++index];
7374         }
7375         return result;
7376 }
7377
7378 static int lfs_mv(int argc, char **argv)
7379 {
7380         struct lmv_user_md lmu = { LMV_USER_MAGIC };
7381         struct find_param param = {
7382                 .fp_max_depth = -1,
7383                 .fp_mdt_index = -1,
7384         };
7385         char *end;
7386         int c;
7387         int rc = 0;
7388         struct option long_opts[] = {
7389         { .val = 'm',   .name = "mdt",          .has_arg = required_argument },
7390         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument },
7391         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
7392         { .name = NULL } };
7393
7394         while ((c = getopt_long(argc, argv, "m:M:v", long_opts, NULL)) != -1) {
7395                 switch (c) {
7396 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
7397                 case 'M':
7398                         fprintf(stderr,
7399                                 "warning: '-M' deprecated, use '--mdt-index' or '-m' instead\n");
7400 #endif
7401                 case 'm':
7402                         errno = 0;
7403                         lmu.lum_stripe_offset = strtoul(optarg, &end, 0);
7404                         if (errno != 0 || *end != '\0' ||
7405                             lmu.lum_stripe_offset >= UINT32_MAX) {
7406                                 fprintf(stderr, "%s mv: bad MDT index '%s'\n",
7407                                         progname, optarg);
7408                                 return CMD_HELP;
7409                         }
7410                         break;
7411                 case 'v':
7412                         param.fp_verbose = VERBOSE_DETAIL;
7413                         break;
7414                 default:
7415                         fprintf(stderr, "%s mv: unrecognized option '%s'\n",
7416                                 progname, argv[optind - 1]);
7417                         return CMD_HELP;
7418                 }
7419         }
7420
7421         if (lmu.lum_stripe_offset == LMV_OFFSET_DEFAULT) {
7422                 fprintf(stderr, "%s mv: MDT index must be specified\n",
7423                         progname);
7424                 return CMD_HELP;
7425         }
7426
7427         if (optind >= argc) {
7428                 fprintf(stderr, "%s mv: DIR must be specified\n", progname);
7429                 return CMD_HELP;
7430         }
7431
7432         lmu.lum_hash_type = LMV_HASH_TYPE_UNKNOWN;
7433
7434         /* initialize migrate mdt parameters */
7435         param.fp_lmv_md = &lmu;
7436         param.fp_migrate = 1;
7437         rc = llapi_migrate_mdt(argv[optind], &param);
7438         if (rc != 0)
7439                 fprintf(stderr, "%s mv: cannot migrate '%s' to MDT%04x: %s\n",
7440                         progname, argv[optind], lmu.lum_stripe_offset,
7441                         strerror(-rc));
7442         return rc;
7443 }
7444
7445 static int lfs_osts(int argc, char **argv)
7446 {
7447         return lfs_tgts(argc, argv);
7448 }
7449
7450 static int lfs_mdts(int argc, char **argv)
7451 {
7452         return lfs_tgts(argc, argv);
7453 }
7454
7455 static int lfs_df(int argc, char **argv)
7456 {
7457         char mntdir[PATH_MAX] = {'\0'}, path[PATH_MAX] = {'\0'};
7458         enum mntdf_flags flags = MNTDF_SHOW;
7459         int ops = LL_STATFS_LMV | LL_STATFS_LOV;
7460         int c, rc = 0, rc1 = 0, index = 0, arg_idx = 0;
7461         char fsname[PATH_MAX] = "", *pool_name = NULL;
7462         struct option long_opts[] = {
7463         { .val = 'h',   .name = "human-readable", .has_arg = no_argument },
7464         { .val = 'H',   .name = "si",           .has_arg = no_argument },
7465         { .val = 'i',   .name = "inodes",       .has_arg = no_argument },
7466         { .val = 'l',   .name = "lazy",         .has_arg = no_argument },
7467         { .val = 'p',   .name = "pool",         .has_arg = required_argument },
7468         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
7469         { .name = NULL} };
7470
7471         while ((c = getopt_long(argc, argv, "hHilp:v", long_opts, NULL)) != -1) {
7472                 switch (c) {
7473                 case 'h':
7474                         flags = (flags & ~MNTDF_DECIMAL) | MNTDF_COOKED;
7475                         break;
7476                 case 'H':
7477                         flags |= MNTDF_COOKED | MNTDF_DECIMAL;
7478                         break;
7479                 case 'i':
7480                         flags |= MNTDF_INODES;
7481                         break;
7482                 case 'l':
7483                         flags |= MNTDF_LAZY;
7484                         break;
7485                 case 'p':
7486                         pool_name = optarg;
7487                         break;
7488                 case 'v':
7489                         flags |= MNTDF_VERBOSE;
7490                         break;
7491                 default:
7492                         fprintf(stderr, "%s: unrecognized option '%s'\n",
7493                                 progname, argv[optind - 1]);
7494                         return CMD_HELP;
7495                 }
7496         }
7497
7498         /* Handle case where path is not specified */
7499         if (optind == argc) {
7500                 while (!llapi_search_mounts(path, index++, mntdir, fsname)) {
7501                         /* Check if we have a mount point */
7502                         if (mntdir[0] == '\0')
7503                                 continue;
7504
7505                         rc = mntdf(mntdir, fsname, pool_name, flags, ops, NULL);
7506                         if (rc || path[0] != '\0')
7507                                 break;
7508
7509                         fsname[0] = '\0'; /* avoid matching in next loop */
7510                         mntdir[0] = '\0'; /* avoid matching in next loop */
7511                         path[0] = '\0'; /* clean for next loop */
7512                 }
7513                 return rc;
7514         }
7515
7516         /* Loop through all the remaining arguments. These are Lustre FS
7517          * paths.
7518          */
7519         for (arg_idx = optind; arg_idx <= argc - 1; arg_idx++) {
7520                 bool valid = false;
7521
7522                 fsname[0] = '\0'; /* start clean */
7523                 mntdir[0] = '\0'; /* start clean */
7524                 path[0] = '\0';   /* start clean */
7525
7526                 /* path does not exists at all */
7527                 if (!realpath(argv[arg_idx], path)) {
7528                         rc = -errno;
7529                         fprintf(stderr, "error: invalid path '%s': %s\n",
7530                                 argv[arg_idx], strerror(-rc));
7531                         /* save first seen error */
7532                         if (!rc1)
7533                                 rc1 = rc;
7534
7535                         continue;
7536                 }
7537
7538                 /* path exists but may not be a Lustre filesystem */
7539                 while (!llapi_search_mounts(path, index++, mntdir, fsname)) {
7540                         /* Check if we have a mount point */
7541                         if (mntdir[0] == '\0')
7542                                 continue;
7543
7544                         rc = mntdf(mntdir, fsname, pool_name, flags, ops, NULL);
7545                         if (rc || path[0] != '\0') {
7546                                 valid = true;
7547
7548                                 /* save first seen error */
7549                                 if (!rc1)
7550                                         rc1 = rc;
7551                                 break;
7552                         }
7553                 }
7554
7555                 if (!valid) {
7556                         llapi_printf(LLAPI_MSG_ERROR,
7557                                      "%s:%s Not a Lustre filesystem\n",
7558                                      argv[0], argv[arg_idx]);
7559                         /* save first seen error */
7560                         if (!rc1)
7561                                 rc1 = -EOPNOTSUPP;
7562                 }
7563         }
7564
7565         return rc1;
7566 }
7567
7568 static int print_instance(const char *mntdir, char *buf, size_t buflen,
7569                           bool opt_instance, bool opt_fsname, bool opt_mntdir)
7570 {
7571         int rc = 0;
7572
7573         if (opt_fsname == opt_instance) { /* both true or both false */
7574                 rc = llapi_getname(mntdir, buf, buflen);
7575         } else if (opt_fsname) {
7576                 /*
7577                  * llapi_search_mounts() fills @buf with fsname, but that is not
7578                  * called if explicit paths are specified on the command-line
7579                  */
7580                 if (buf[0] == '\0')
7581                         rc = llapi_get_fsname(mntdir, buf, buflen);
7582         } else /* if (opt_instance) */ {
7583                 rc = llapi_get_instance(mntdir, buf, buflen);
7584         }
7585
7586         if (rc < 0) {
7587                 fprintf(stderr, "cannot get instance for '%s': %s\n",
7588                         mntdir, strerror(-rc));
7589                 return rc;
7590         }
7591
7592         if (opt_mntdir)
7593                 printf("%s %s\n", buf, mntdir);
7594         else
7595                 printf("%s\n", buf);
7596
7597         return 0;
7598 }
7599
7600 static int lfs_getname(int argc, char **argv)
7601 {
7602         struct option long_opts[] = {
7603         { .val = 'h',   .name = "help",         .has_arg = no_argument },
7604         { .val = 'i',   .name = "instance",     .has_arg = no_argument },
7605         { .val = 'n',   .name = "fsname",       .has_arg = no_argument },
7606         { .name = NULL} };
7607         bool opt_instance = false, opt_fsname = false;
7608         char fsname[PATH_MAX] = "";
7609         int rc = 0, rc2, c;
7610
7611         while ((c = getopt_long(argc, argv, "hin", long_opts, NULL)) != -1) {
7612                 switch (c) {
7613                 case 'i':
7614                         opt_instance = true;
7615                         break;
7616                 case 'n':
7617                         opt_fsname = true;
7618                         break;
7619                 default:
7620                         fprintf(stderr, "%s: unrecognized option '%s'\n",
7621                                 progname, argv[optind - 1]);
7622                         fallthrough;
7623                 case 'h':
7624                         return CMD_HELP;
7625                 }
7626         }
7627
7628         if (optind == argc) { /* no paths specified, get all paths. */
7629                 char mntdir[PATH_MAX] = "", path[PATH_MAX] = "";
7630                 int index = 0;
7631
7632                 while (!llapi_search_mounts(path, index++, mntdir, fsname)) {
7633                         rc2 = print_instance(mntdir, fsname, sizeof(fsname),
7634                                              opt_instance, opt_fsname, true);
7635                         if (!rc)
7636                                 rc = rc2;
7637                         path[0] = fsname[0] = mntdir[0] = '\0';
7638                 }
7639         } else { /* paths specified, only attempt to search these. */
7640                 bool opt_mntdir;
7641
7642                 /* if only one path is given, print only requested info */
7643                 opt_mntdir = argc - optind > 1 || (opt_instance == opt_fsname);
7644
7645                 for (; optind < argc; optind++) {
7646                         rc2 = print_instance(argv[optind], fsname,
7647                                              sizeof(fsname), opt_instance,
7648                                              opt_fsname, opt_mntdir);
7649                         if (!rc)
7650                                 rc = rc2;
7651                         fsname[0] = '\0';
7652                 }
7653         }
7654
7655         return rc;
7656 }
7657
7658 static int lfs_check(int argc, char **argv)
7659 {
7660         char mntdir[PATH_MAX] = {'\0'}, path[PATH_MAX] = {'\0'};
7661         int num_types = 1;
7662         char *obd_types[3];
7663         char obd_type1[4];
7664         char obd_type2[4];
7665         char obd_type3[4];
7666         int rc;
7667
7668         if (argc < 2 || argc > 3) {
7669                 fprintf(stderr, "%s check: server type must be specified\n",
7670                         progname);
7671                 return CMD_HELP;
7672         }
7673
7674         obd_types[0] = obd_type1;
7675         obd_types[1] = obd_type2;
7676         obd_types[2] = obd_type3;
7677
7678         if (strcmp(argv[1], "osts") == 0) {
7679                 strcpy(obd_types[0], "osc");
7680         } else if (strcmp(argv[1], "mdts") == 0 ||
7681                    strcmp(argv[1], "mds") == 0) {
7682                 strcpy(obd_types[0], "mdc");
7683         } else if (strcmp(argv[1], "mgts") == 0) {
7684                 strcpy(obd_types[0], "mgc");
7685         } else if (strcmp(argv[1], "all") == 0 ||
7686                    strcmp(argv[1], "servers") == 0) {
7687                 num_types = 3;
7688                 strcpy(obd_types[0], "osc");
7689                 strcpy(obd_types[1], "mdc");
7690                 strcpy(obd_types[2], "mgc");
7691         } else {
7692                 fprintf(stderr, "%s check: unrecognized option '%s'\n",
7693                         progname, argv[1]);
7694                 return CMD_HELP;
7695         }
7696
7697         if (argc >= 3 && !realpath(argv[2], path)) {
7698                 rc = -errno;
7699                 fprintf(stderr, "error: invalid path '%s': %s\n",
7700                         argv[2], strerror(-rc));
7701                 return rc;
7702         }
7703
7704         rc = llapi_search_mounts(path, 0, mntdir, NULL);
7705         if (rc < 0 || mntdir[0] == '\0') {
7706                 fprintf(stderr,
7707                         "%s %s: cannot find mounted Lustre filesystem: %s\n",
7708                         progname, argv[0],
7709                         (rc < 0) ? strerror(-rc) : strerror(ENODEV));
7710                 return rc;
7711         }
7712
7713         rc = llapi_target_check(num_types, obd_types, path);
7714         if (rc)
7715                 fprintf(stderr, "%s %s: cannot check target '%s': %s\n",
7716                         progname, argv[0], argv[1], strerror(-rc));
7717
7718         return rc;
7719 }
7720
7721 #ifdef HAVE_SYS_QUOTA_H
7722 #define ADD_OVERFLOW(a, b) \
7723                      ((((a) + (b)) < (a)) ? \
7724                       ((a) = ULONG_MAX) : ((a) = (a) + (b)))
7725
7726 /* Convert format time string "XXwXXdXXhXXmXXs" into seconds value
7727  * returns the value or ULONG_MAX on integer overflow or incorrect format
7728  * Notes:
7729  *        1. the order of specifiers is arbitrary (may be: 5w3s or 3s5w)
7730  *        2. specifiers may be encountered multiple times (2s3s is 5 seconds)
7731  *        3. empty integer value is interpreted as 0
7732  */
7733 static unsigned long str2sec(const char *timestr)
7734 {
7735         const char spec[] = "smhdw";
7736         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
7737         unsigned long val = 0;
7738         char *tail;
7739
7740         if (strpbrk(timestr, spec) == NULL) {
7741                 /*
7742                  * no specifiers inside the time string,
7743                  * should treat it as an integer value
7744                  */
7745                 val = strtoul(timestr, &tail, 10);
7746                 return *tail ? ULONG_MAX : val;
7747         }
7748
7749         /* format string is XXwXXdXXhXXmXXs */
7750         while (*timestr) {
7751                 unsigned long v;
7752                 int ind;
7753                 char *ptr;
7754
7755                 v = strtoul(timestr, &tail, 10);
7756                 if (v == ULONG_MAX || *tail == '\0')
7757                         /*
7758                          * value too large (ULONG_MAX or more)
7759                          * or missing specifier
7760                          */
7761                         goto error;
7762
7763                 ptr = strchr(spec, *tail);
7764                 if (!ptr)
7765                         /* unknown specifier */
7766                         goto error;
7767
7768                 ind = ptr - spec;
7769
7770                 /* check if product will overflow the type */
7771                 if (!(v < ULONG_MAX / mult[ind]))
7772                         goto error;
7773
7774                 ADD_OVERFLOW(val, mult[ind] * v);
7775                 if (val == ULONG_MAX)
7776                         goto error;
7777
7778                 timestr = tail + 1;
7779         }
7780
7781         return val;
7782
7783 error:
7784         return ULONG_MAX;
7785 }
7786
7787 #define ARG2ULL(nr, str, def_units)                                     \
7788 do {                                                                    \
7789         unsigned long long limit, units = def_units;                    \
7790         int rc;                                                         \
7791                                                                         \
7792         rc = llapi_parse_size(str, &limit, &units, 1);                  \
7793         if (rc < 0) {                                                   \
7794                 fprintf(stderr, "%s: invalid limit '%s'\n",             \
7795                         progname, str);                                 \
7796                 return CMD_HELP;                                        \
7797         }                                                               \
7798         nr = limit;                                                     \
7799 } while (0)
7800
7801 static inline int has_times_option(int argc, char **argv)
7802 {
7803         int i;
7804
7805         for (i = 1; i < argc; i++)
7806                 if (!strcmp(argv[i], "-t"))
7807                         return 1;
7808
7809         return 0;
7810 }
7811
7812 static inline int lfs_verify_poolarg(char *pool)
7813 {
7814         if (strnlen(optarg, LOV_MAXPOOLNAME + 1) > LOV_MAXPOOLNAME) {
7815                 fprintf(stderr,
7816                         "Pool name '%.*s' is longer than %d\n",
7817                         LOV_MAXPOOLNAME, pool, LOV_MAXPOOLNAME);
7818                 return 1;
7819         }
7820         return 0;
7821 }
7822
7823 /* special grace time, only notify the user when its quota is over soft limit
7824  * but doesn't block new writes until the hard limit is reached.
7825  */
7826 #define NOTIFY_GRACE            "notify"
7827 #define NOTIFY_GRACE_TIME       LQUOTA_GRACE_MASK
7828
7829 #ifndef toqb
7830 static inline __u64 lustre_stoqb(size_t space)
7831 {
7832         return (space + QIF_DQBLKSIZE - 1) >> QIF_DQBLKSIZE_BITS;
7833 }
7834 #else
7835 #define lustre_stoqb   toqb
7836 #endif
7837
7838 int lfs_setquota_times(int argc, char **argv, struct if_quotactl *qctl)
7839 {
7840         int c, rc;
7841         char *mnt, *obd_type = (char *)qctl->obd_type;
7842         struct obd_dqblk *dqb = &qctl->qc_dqblk;
7843         struct obd_dqinfo *dqi = &qctl->qc_dqinfo;
7844         struct option long_opts[] = {
7845         { .val = 'b',   .name = "block-grace",  .has_arg = required_argument },
7846         { .val = 'g',   .name = "group",        .has_arg = no_argument },
7847         { .val = 'h',   .name = "help",         .has_arg = no_argument },
7848         { .val = 'i',   .name = "inode-grace",  .has_arg = required_argument },
7849         { .val = 'p',   .name = "projid",       .has_arg = no_argument },
7850         { .val = 't',   .name = "times",        .has_arg = no_argument },
7851         { .val = 'u',   .name = "user",         .has_arg = no_argument },
7852         { .val = LFS_POOL_OPT,
7853                         .name = "pool",         .has_arg = required_argument },
7854         { .name = NULL } };
7855         int qtype;
7856
7857         qctl->qc_cmd  = LUSTRE_Q_SETINFO;
7858         qctl->qc_type = ALLQUOTA;
7859
7860         while ((c = getopt_long(argc, argv, "b:ghi:ptu",
7861                                 long_opts, NULL)) != -1) {
7862                 switch (c) {
7863                 case 'u':
7864                         qtype = USRQUOTA;
7865                         goto quota_type;
7866                 case 'g':
7867                         qtype = GRPQUOTA;
7868                         goto quota_type;
7869                 case 'p':
7870                         qtype = PRJQUOTA;
7871 quota_type:
7872                         if (qctl->qc_type != ALLQUOTA) {
7873                                 fprintf(stderr,
7874                                         "%s: -u/g/p cannot be used more than once\n",
7875                                         progname);
7876                                 return CMD_HELP;
7877                         }
7878                         qctl->qc_type = qtype;
7879                         break;
7880                 case 'b':
7881                         if (strncmp(optarg, NOTIFY_GRACE,
7882                                     strlen(NOTIFY_GRACE)) == 0) {
7883                                 dqi->dqi_bgrace = NOTIFY_GRACE_TIME;
7884                         } else {
7885                                 dqi->dqi_bgrace = str2sec(optarg);
7886                                 if (dqi->dqi_bgrace >= NOTIFY_GRACE_TIME) {
7887                                         fprintf(stderr,
7888                                                 "%s: bad block-grace: %s\n",
7889                                                 progname, optarg);
7890                                         return CMD_HELP;
7891                                 }
7892                         }
7893                         dqb->dqb_valid |= QIF_BTIME;
7894                         break;
7895                 case 'i':
7896                         if (strncmp(optarg, NOTIFY_GRACE,
7897                                     strlen(NOTIFY_GRACE)) == 0) {
7898                                 dqi->dqi_igrace = NOTIFY_GRACE_TIME;
7899                         } else {
7900                                 dqi->dqi_igrace = str2sec(optarg);
7901                                 if (dqi->dqi_igrace >= NOTIFY_GRACE_TIME) {
7902                                         fprintf(stderr,
7903                                                 "%s: bad inode-grace: %s\n",
7904                                                 progname, optarg);
7905                                         return CMD_HELP;
7906                                 }
7907                         }
7908                         dqb->dqb_valid |= QIF_ITIME;
7909                         break;
7910                 case 't': /* Yes, of course! */
7911                         break;
7912                 case LFS_POOL_OPT:
7913                         if (lfs_verify_poolarg(optarg))
7914                                 return -1;
7915                         strncpy(qctl->qc_poolname, optarg, LOV_MAXPOOLNAME);
7916                         qctl->qc_cmd  = LUSTRE_Q_SETINFOPOOL;
7917                         break;
7918                 /* getopt prints error message for us when opterr != 0 */
7919                 default:
7920                         fprintf(stderr, "%s: unrecognized option '%s'\n",
7921                                 progname, argv[optind - 1]);
7922                         fallthrough;
7923                 case 'h':
7924                         return CMD_HELP;
7925                 }
7926         }
7927
7928         if (qctl->qc_type == ALLQUOTA) {
7929                 fprintf(stderr, "%s: neither -u, -g nor -p specified\n",
7930                         progname);
7931                 return CMD_HELP;
7932         }
7933
7934         if (optind != argc - 1) {
7935                 fprintf(stderr, "%s: unexpected parameter '%s'\n",
7936                         progname, argv[optind + 1]);
7937                 return CMD_HELP;
7938         }
7939
7940         mnt = argv[optind];
7941         rc = llapi_quotactl(mnt, qctl);
7942         if (rc) {
7943                 if (*obd_type)
7944                         fprintf(stderr, "%s %s ", obd_type,
7945                                 obd_uuid2str(&qctl->obd_uuid));
7946                 fprintf(stderr, "setquota failed: %s\n", strerror(-rc));
7947                 return rc;
7948         }
7949
7950         return 0;
7951 }
7952
7953 static int lfs_reset_quota(char *mnt, struct if_quotactl *qctl)
7954 {
7955         struct if_quotactl tmp_qctl;
7956         int index, md_count, dt_count;
7957         int wait_phase = 0, wait_index = 0, wait_count = 0;
7958         int rc, rc2;
7959
7960         /* reset the quota ID, the existing quota setting will be returned */
7961         rc = llapi_quotactl(mnt, qctl);
7962         if (rc)
7963                 return rc;
7964
7965         /* sanity check */
7966         if ((qctl->qc_dqblk.dqb_valid & QIF_LIMITS) != QIF_LIMITS) {
7967                 fprintf(stderr,
7968                         "the existing quota settings are not returned!\n");
7969                 return -EINVAL;
7970         }
7971
7972         rc = llapi_get_obd_count(mnt, &md_count, 1);
7973         if (rc) {
7974                 fprintf(stderr, "can not get mdt count: %s\n", strerror(-rc));
7975                 return rc;
7976         }
7977
7978         rc = llapi_get_obd_count(mnt, &dt_count, 0);
7979         if (rc) {
7980                 fprintf(stderr, "can not get ost count: %s\n", strerror(-rc));
7981                 return rc;
7982         }
7983
7984         memset(&tmp_qctl, 0, sizeof(tmp_qctl));
7985         tmp_qctl.qc_type = qctl->qc_type;
7986         tmp_qctl.qc_id = qctl->qc_id;
7987         tmp_qctl.qc_cmd = LUSTRE_Q_GETQUOTA;
7988
7989 retry:
7990         if (wait_phase == 0) {
7991                 for (index = wait_index; index < md_count; index++) {
7992                         tmp_qctl.qc_idx = index;
7993                         tmp_qctl.qc_valid = QC_MDTIDX;
7994                         rc = llapi_quotactl(mnt, &tmp_qctl);
7995                         if (rc == -ENODEV || rc == -ENODATA)
7996                                 continue;
7997                         if (rc) {
7998                                 fprintf(stderr, "quotactl mdt%d failed: %s\n",
7999                                         index, strerror(-rc));
8000                                 break;
8001                         }
8002                         /* check whether the md quota grant is reset */
8003                         if (tmp_qctl.qc_dqblk.dqb_valid & QIF_LIMITS &&
8004                             tmp_qctl.qc_dqblk.dqb_ihardlimit != 0)
8005                                 break;
8006                 }
8007
8008                 if (index < md_count) {
8009                         wait_phase = 0;
8010                         wait_index = index;
8011                         goto wait;
8012                 }
8013         } else {
8014                 for (index = wait_index; index < dt_count; index++) {
8015                         tmp_qctl.qc_idx = index;
8016                         tmp_qctl.qc_valid = QC_OSTIDX;
8017                         rc = llapi_quotactl(mnt, &tmp_qctl);
8018                         if (rc == -ENODEV || rc == -ENODATA)
8019                                 continue;
8020                         if (rc) {
8021                                 fprintf(stderr, "quotactl mdt%d failed: %s\n",
8022                                         index, strerror(-rc));
8023                                 break;
8024                         }
8025                         /* check whether the dt quota grant is reset */
8026                         if (tmp_qctl.qc_dqblk.dqb_valid & QIF_LIMITS &&
8027                             tmp_qctl.qc_dqblk.dqb_bhardlimit != 0)
8028                                 break;
8029                 }
8030
8031                 if (index < dt_count) {
8032                         wait_phase = 1;
8033                         wait_index = index;
8034                         goto wait;
8035                 }
8036         }
8037
8038         if (wait_phase == 0) {
8039                 wait_phase = 1;
8040                 goto retry;
8041         }
8042
8043         goto out;
8044
8045 wait:
8046         if (rc || wait_count > 30) {
8047                 fprintf(stderr, "fail to reset the quota ID %d on OBDs\n",
8048                         qctl->qc_id);
8049                 goto out;
8050         }
8051
8052         wait_count++;
8053         sleep(1);
8054         fprintf(stdout, "wait %d seconds for OBDs to reset the quota ID %u\n",
8055                 wait_count, qctl->qc_id);
8056         goto retry;
8057
8058
8059 out:
8060         /* restore the quota setting */
8061         if (qctl->qc_dqblk.dqb_isoftlimit == 0 &&
8062             qctl->qc_dqblk.dqb_ihardlimit == 0 &&
8063             qctl->qc_dqblk.dqb_bsoftlimit == 0 &&
8064             qctl->qc_dqblk.dqb_bhardlimit == 0)
8065                 return rc;
8066
8067         memcpy(&tmp_qctl, qctl, sizeof(tmp_qctl));
8068         tmp_qctl.qc_cmd = LUSTRE_Q_SETQUOTA;
8069         rc2 = llapi_quotactl(mnt, &tmp_qctl);
8070         if (!rc2)
8071                 return rc;
8072
8073         fprintf(stderr,
8074                 "fail to restore the quota setting: %s, please restore it manually by\n  lfs setquota %s %d",
8075                 strerror(-rc2),
8076                 qctl->qc_type == USRQUOTA ? "-u" :
8077                                 (qctl->qc_type == GRPQUOTA ? "-g" : "-p"),
8078                 qctl->qc_id);
8079
8080         if (qctl->qc_dqblk.dqb_isoftlimit != 0)
8081                 fprintf(stderr, " -i %llu",
8082                         (unsigned long long)qctl->qc_dqblk.dqb_isoftlimit);
8083         if (qctl->qc_dqblk.dqb_ihardlimit != 0)
8084                 fprintf(stderr, " -I %llu",
8085                         (unsigned long long)qctl->qc_dqblk.dqb_ihardlimit);
8086         if (qctl->qc_dqblk.dqb_bsoftlimit != 0)
8087                 fprintf(stderr, " -b %llu",
8088                         (unsigned long long)qctl->qc_dqblk.dqb_bsoftlimit);
8089         if (qctl->qc_dqblk.dqb_bhardlimit != 0)
8090                 fprintf(stderr, " -B %llu",
8091                         (unsigned long long)qctl->qc_dqblk.dqb_bhardlimit);
8092
8093         fprintf(stderr, " %s\n", mnt);
8094         if (!rc)
8095                 rc = rc2;
8096
8097         return rc;
8098 }
8099
8100 #define BSLIMIT (1 << 0)
8101 #define BHLIMIT (1 << 1)
8102 #define ISLIMIT (1 << 2)
8103 #define IHLIMIT (1 << 3)
8104
8105 int lfs_setquota(int argc, char **argv)
8106 {
8107         int c, rc = 0;
8108         struct if_quotactl *qctl;
8109         char *mnt, *obd_type;
8110         struct obd_dqblk *dqb;
8111         struct option long_opts[] = {
8112         { .val = 'b',   .name = "block-softlimit",
8113                                                 .has_arg = required_argument },
8114         { .val = 'B',   .name = "block-hardlimit",
8115                                                 .has_arg = required_argument },
8116         { .val = 'd',   .name = "default",      .has_arg = no_argument },
8117         { .val = LFS_SETQUOTA_DELETE,
8118                         .name = "delete",       .has_arg = no_argument },
8119         { .val = 'g',   .name = "group",        .has_arg = required_argument },
8120         { .val = 'G',   .name = "default-grp",  .has_arg = no_argument },
8121         { .val = 'h',   .name = "help",         .has_arg = no_argument },
8122         { .val = 'i',   .name = "inode-softlimit",
8123                                                 .has_arg = required_argument },
8124         { .val = 'I',   .name = "inode-hardlimit",
8125                                                 .has_arg = required_argument },
8126         { .val = 'p',   .name = "projid",       .has_arg = required_argument },
8127         { .val = 'P',   .name = "default-prj",  .has_arg = no_argument },
8128         { .val = 'r',   .name = "reset",        .has_arg = no_argument },
8129         { .val = 'u',   .name = "user",         .has_arg = required_argument },
8130         { .val = 'U',   .name = "default-usr",  .has_arg = no_argument },
8131         { .val = LFS_POOL_OPT,
8132                         .name = "pool",         .has_arg = required_argument },
8133         { .name = NULL } };
8134         unsigned int limit_mask = 0;
8135         bool use_default = false;
8136         int qtype, qctl_len;
8137
8138         qctl_len = sizeof(*qctl) + LOV_MAXPOOLNAME + 1;
8139         qctl = malloc(qctl_len);
8140         if (!qctl)
8141                 return -ENOMEM;
8142
8143         memset(qctl, 0, qctl_len);
8144         obd_type = (char *)qctl->obd_type;
8145         dqb = &qctl->qc_dqblk;
8146
8147         if (has_times_option(argc, argv)) {
8148                 rc = lfs_setquota_times(argc, argv, qctl);
8149                 goto out;
8150         }
8151
8152         qctl->qc_cmd  = LUSTRE_Q_SETQUOTA;
8153         qctl->qc_type = ALLQUOTA; /* ALLQUOTA makes no sense for setquota,
8154                                    * so it can be used as a marker that qc_type
8155                                    * isn't reinitialized from command line
8156                                    */
8157         while ((c = getopt_long(argc, argv, "b:B:dDg:Ghi:I:p:Pru:U",
8158                 long_opts, NULL)) != -1) {
8159                 switch (c) {
8160                 case 'U':
8161                         qctl->qc_cmd = LUSTRE_Q_SETDEFAULT;
8162                         qtype = USRQUOTA;
8163                         qctl->qc_id = 0;
8164                         goto quota_type_def;
8165                 case 'u':
8166                         qtype = USRQUOTA;
8167                         rc = name2uid(&qctl->qc_id, optarg);
8168                         goto quota_type;
8169                 case 'G':
8170                         qctl->qc_cmd = LUSTRE_Q_SETDEFAULT;
8171                         qtype = GRPQUOTA;
8172                         qctl->qc_id = 0;
8173                         goto quota_type_def;
8174                 case 'g':
8175                         qtype = GRPQUOTA;
8176                         rc = name2gid(&qctl->qc_id, optarg);
8177                         goto quota_type;
8178                 case 'P':
8179                         qctl->qc_cmd = LUSTRE_Q_SETDEFAULT;
8180                         qtype = PRJQUOTA;
8181                         qctl->qc_id = 0;
8182                         goto quota_type_def;
8183                 case 'p':
8184                         qtype = PRJQUOTA;
8185                         rc = name2projid(&qctl->qc_id, optarg);
8186 quota_type:
8187                         if (rc) {
8188                                 if (str2quotaid(&qctl->qc_id, optarg)) {
8189                                         fprintf(stderr,
8190                                                 "%s setquota: invalid id '%s'\n",
8191                                                 progname, optarg);
8192                                         rc = -1;
8193                                         goto out;
8194                                 }
8195                         }
8196
8197                         if (qctl->qc_id == 0) {
8198                                 fprintf(stderr,
8199                                         "%s setquota: can't set quota for root usr/group/project.\n",
8200                                         progname);
8201                                 rc = -1;
8202                                 goto out;
8203                         }
8204
8205 quota_type_def:
8206                         if (qctl->qc_type != ALLQUOTA) {
8207                                 fprintf(stderr,
8208                                         "%s setquota: only one of -u, -U, -g, -G, -p or -P may be specified\n",
8209                                         progname);
8210                                 rc = CMD_HELP;
8211                                 goto out;
8212                         }
8213                         qctl->qc_type = qtype;
8214                         break;
8215 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
8216                 case 'd':
8217                         fprintf(stderr,
8218                                 "%s setquota: '-d' deprecated, use '-D' or '--default'\n",
8219                                 progname);
8220                         fallthrough;
8221 #endif
8222                 case 'D':
8223                         use_default = true;
8224                         qctl->qc_cmd = LUSTRE_Q_SETDEFAULT;
8225                         break;
8226                 case LFS_SETQUOTA_DELETE:
8227                         qctl->qc_cmd = LUSTRE_Q_DELETEQID;
8228                         break;
8229                 case 'b':
8230                         ARG2ULL(dqb->dqb_bsoftlimit, optarg, 1024);
8231                         dqb->dqb_bsoftlimit >>= 10;
8232                         limit_mask |= BSLIMIT;
8233                         if (dqb->dqb_bsoftlimit &&
8234                             dqb->dqb_bsoftlimit <= 1024) /* <= 1M? */
8235                                 fprintf(stderr,
8236                                         "%s setquota: warning: block softlimit '%llu' smaller than minimum qunit size\nSee '%s help setquota' or Lustre manual for details\n",
8237                                         progname,
8238                                         (unsigned long long)dqb->dqb_bsoftlimit,
8239                                         progname);
8240                         break;
8241                 case 'B':
8242                         ARG2ULL(dqb->dqb_bhardlimit, optarg, 1024);
8243                         dqb->dqb_bhardlimit >>= 10;
8244                         limit_mask |= BHLIMIT;
8245                         if (dqb->dqb_bhardlimit &&
8246                             dqb->dqb_bhardlimit <= 1024) /* <= 1M? */
8247                                 fprintf(stderr,
8248                                         "%s setquota: warning: block hardlimit '%llu' smaller than minimum qunit size\n"
8249                                         "See '%s help setquota' or Lustre manual for details\n",
8250                                         progname,
8251                                         (unsigned long long)dqb->dqb_bhardlimit,
8252                                         progname);
8253                         break;
8254                 case 'i':
8255                         ARG2ULL(dqb->dqb_isoftlimit, optarg, 1);
8256                         limit_mask |= ISLIMIT;
8257                         if (dqb->dqb_isoftlimit &&
8258                             dqb->dqb_isoftlimit <= 1024) /* <= 1K inodes? */
8259                                 fprintf(stderr,
8260                                         "%s setquota: warning: inode softlimit '%llu' smaller than minimum qunit size\nSee '%s help setquota' or Lustre manual for details\n",
8261                                         progname,
8262                                         (unsigned long long)dqb->dqb_isoftlimit,
8263                                         progname);
8264                         break;
8265                 case 'I':
8266                         ARG2ULL(dqb->dqb_ihardlimit, optarg, 1);
8267                         limit_mask |= IHLIMIT;
8268                         if (dqb->dqb_ihardlimit &&
8269                             dqb->dqb_ihardlimit <= 1024) /* <= 1K inodes? */
8270                                 fprintf(stderr,
8271                                         "%s setquota: warning: inode hardlimit '%llu' smaller than minimum qunit size\nSee '%s help setquota' or Lustre manual for details\n",
8272                                         progname,
8273                                         (unsigned long long)dqb->dqb_ihardlimit,
8274                                         progname);
8275                         break;
8276                 case LFS_POOL_OPT:
8277                         if (lfs_verify_poolarg(optarg)) {
8278                                 rc = -1;
8279                                 goto out;
8280                         }
8281                         strncpy(qctl->qc_poolname, optarg, LOV_MAXPOOLNAME);
8282                         qctl->qc_cmd = qctl->qc_cmd == LUSTRE_Q_SETDEFAULT ?
8283                                                 LUSTRE_Q_SETDEFAULT_POOL :
8284                                                 LUSTRE_Q_SETQUOTAPOOL;
8285                         break;
8286                 case 'r':
8287                         qctl->qc_cmd = LUSTRE_Q_RESETQID;
8288                         break;
8289                 default:
8290                         fprintf(stderr,
8291                                 "%s setquota: unrecognized option '%s'\n",
8292                                 progname, argv[optind - 1]);
8293                         fallthrough;
8294                 case 'h':
8295                         rc = CMD_HELP;
8296                         goto out;
8297                 }
8298         }
8299
8300         if (qctl->qc_type == ALLQUOTA) {
8301                 fprintf(stderr,
8302                         "%s setquota: either -u or -g must be specified\n",
8303                         progname);
8304                 rc = CMD_HELP;
8305                 goto out;
8306         }
8307
8308         if (!use_default && qctl->qc_cmd != LUSTRE_Q_DELETEQID &&
8309             qctl->qc_cmd != LUSTRE_Q_RESETQID && limit_mask == 0) {
8310                 fprintf(stderr,
8311                         "%s setquota: at least one limit must be specified\n",
8312                         progname);
8313                 rc = CMD_HELP;
8314                 goto out;
8315         }
8316
8317         if ((use_default || qctl->qc_cmd == LUSTRE_Q_DELETEQID ||
8318              qctl->qc_cmd == LUSTRE_Q_RESETQID) && limit_mask != 0) {
8319                 fprintf(stderr,
8320                         "%s setquota: limits should not be specified when using default quota, deleting or resetting quota ID\n",
8321                         progname);
8322                 rc = CMD_HELP;
8323                 goto out;
8324         }
8325
8326         if (use_default && qctl->qc_id == 0) {
8327                 fprintf(stderr,
8328                         "%s setquota: can not set default quota for root user/group/project\n",
8329                         progname);
8330                 rc = CMD_HELP;
8331                 goto out;
8332         }
8333
8334         if ((qctl->qc_cmd == LUSTRE_Q_DELETEQID ||
8335              qctl->qc_cmd == LUSTRE_Q_RESETQID)  && qctl->qc_id == 0) {
8336                 fprintf(stderr,
8337                         "%s setquota: can not delete or reset root user/group/project\n",
8338                         progname);
8339                 rc = CMD_HELP;
8340                 goto out;
8341         }
8342
8343         if (optind != argc - 1) {
8344                 fprintf(stderr,
8345                         "%s setquota: filesystem not specified or unexpected argument '%s'\n",
8346                         progname, argv[optind]);
8347                 rc = CMD_HELP;
8348                 goto out;
8349         }
8350
8351         mnt = argv[optind];
8352
8353         if (use_default) {
8354                 dqb->dqb_bhardlimit = 0;
8355                 dqb->dqb_bsoftlimit = 0;
8356                 dqb->dqb_ihardlimit = 0;
8357                 dqb->dqb_isoftlimit = 0;
8358                 dqb->dqb_itime = 0;
8359                 dqb->dqb_btime = 0;
8360                 dqb->dqb_valid |= QIF_LIMITS | QIF_TIMES;
8361                 /* do not set inode limits for Pool Quotas */
8362                 if (qctl->qc_cmd  == LUSTRE_Q_SETDEFAULT_POOL)
8363                         dqb->dqb_valid ^= QIF_ILIMITS | QIF_ITIME;
8364         } else if ((!(limit_mask & BHLIMIT) ^ !(limit_mask & BSLIMIT)) ||
8365                    (!(limit_mask & IHLIMIT) ^ !(limit_mask & ISLIMIT))) {
8366                 /* sigh, we can't just set blimits/ilimits */
8367                 struct if_quotactl *tmp_qctl;
8368
8369                 tmp_qctl = calloc(1, sizeof(*qctl) + LOV_MAXPOOLNAME + 1);
8370                 if (!tmp_qctl)
8371                         goto out;
8372
8373                 if (qctl->qc_cmd == LUSTRE_Q_SETQUOTAPOOL) {
8374                         tmp_qctl->qc_cmd = LUSTRE_Q_GETQUOTAPOOL;
8375                         strncpy(tmp_qctl->qc_poolname, qctl->qc_poolname,
8376                                 LOV_MAXPOOLNAME);
8377                 } else {
8378                         tmp_qctl->qc_cmd  = LUSTRE_Q_GETQUOTA;
8379                 }
8380                 tmp_qctl->qc_type = qctl->qc_type;
8381                 tmp_qctl->qc_id = qctl->qc_id;
8382
8383                 rc = llapi_quotactl(mnt, tmp_qctl);
8384                 if (rc < 0) {
8385                         free(tmp_qctl);
8386                         goto out;
8387                 }
8388
8389                 if (!(limit_mask & BHLIMIT))
8390                         dqb->dqb_bhardlimit = tmp_qctl->qc_dqblk.dqb_bhardlimit;
8391                 if (!(limit_mask & BSLIMIT))
8392                         dqb->dqb_bsoftlimit = tmp_qctl->qc_dqblk.dqb_bsoftlimit;
8393                 if (!(limit_mask & IHLIMIT))
8394                         dqb->dqb_ihardlimit = tmp_qctl->qc_dqblk.dqb_ihardlimit;
8395                 if (!(limit_mask & ISLIMIT))
8396                         dqb->dqb_isoftlimit = tmp_qctl->qc_dqblk.dqb_isoftlimit;
8397
8398                 /* Keep grace times if we have got no softlimit arguments */
8399                 if ((limit_mask & BHLIMIT) && !(limit_mask & BSLIMIT)) {
8400                         dqb->dqb_valid |= QIF_BTIME;
8401                         dqb->dqb_btime = tmp_qctl->qc_dqblk.dqb_btime;
8402                 }
8403
8404                 if ((limit_mask & IHLIMIT) && !(limit_mask & ISLIMIT)) {
8405                         dqb->dqb_valid |= QIF_ITIME;
8406                         dqb->dqb_itime = tmp_qctl->qc_dqblk.dqb_itime;
8407                 }
8408                 free(tmp_qctl);
8409         }
8410
8411         dqb->dqb_valid |= (limit_mask & (BHLIMIT | BSLIMIT)) ? QIF_BLIMITS : 0;
8412         dqb->dqb_valid |= (limit_mask & (IHLIMIT | ISLIMIT)) ? QIF_ILIMITS : 0;
8413
8414         if (qctl->qc_cmd == LUSTRE_Q_RESETQID)
8415                 rc = lfs_reset_quota(mnt, qctl);
8416         else
8417                 rc = llapi_quotactl(mnt, qctl);
8418
8419         if (rc) {
8420                 if (*obd_type)
8421                         fprintf(stderr,
8422                                 "%s setquota: cannot quotactl '%s' '%s': %s\n",
8423                                 progname, obd_type,
8424                                 obd_uuid2str(&qctl->obd_uuid), strerror(-rc));
8425                 else
8426                         fprintf(stderr,
8427                                 "%s setquota: quotactl failed: %s\n",
8428                                 progname, strerror(-rc));
8429         }
8430 out:
8431         if (rc)
8432                 fprintf(stderr, "setquota failed: %s\n", strerror(-rc));
8433
8434         free(qctl);
8435         return rc;
8436 }
8437
8438 /* Converts seconds value into format string
8439  * result is returned in buf
8440  * Notes:
8441  *        1. result is in descenting order: 1w2d3h4m5s
8442  *        2. zero fields are not filled (except for p. 3): 5d1s
8443  *        3. zero seconds value is presented as "0s"
8444  */
8445 static char *__sec2str(time_t seconds, char *buf)
8446 {
8447         const char spec[] = "smhdw";
8448         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
8449         unsigned long c;
8450         char *tail = buf;
8451         int i;
8452
8453         for (i = ARRAY_SIZE(mult) - 1 ; i >= 0; i--) {
8454                 c = seconds / mult[i];
8455
8456                 if (c > 0 || (i == 0 && buf == tail))
8457                         tail += scnprintf(tail, 40-(tail-buf), "%lu%c", c,
8458                                           spec[i]);
8459
8460                 seconds %= mult[i];
8461         }
8462
8463         return tail;
8464 }
8465
8466 static void sec2str(time_t seconds, char *buf, int rc)
8467 {
8468         char *tail = buf;
8469
8470         if (rc)
8471                 *tail++ = '[';
8472
8473         tail = __sec2str(seconds, tail);
8474
8475         if (rc && tail - buf < 39) {
8476                 *tail++ = ']';
8477                 *tail++ = 0;
8478         }
8479 }
8480
8481 static void diff2str(time_t seconds, char *buf, time_t now)
8482 {
8483         buf[0] = 0;
8484         if (!seconds)
8485                 return;
8486         if (seconds <= now) {
8487                 strcpy(buf, "expired");
8488                 return;
8489         }
8490         __sec2str(seconds - now, buf);
8491 }
8492
8493 static void print_quota_title(char *name, struct if_quotactl *qctl,
8494                               bool human_readable, bool show_default)
8495 {
8496         if (show_default) {
8497                 printf("Disk default %s quota:\n", qtype_name(qctl->qc_type));
8498                 printf("%15s %8s%8s%8s %8s%8s%8s\n",
8499                        "Filesystem", "bquota", "blimit", "bgrace",
8500                        "iquota", "ilimit", "igrace");
8501         } else {
8502                 printf("Disk quotas for %s %s (%cid %u):\n",
8503                        qtype_name(qctl->qc_type), name,
8504                        *qtype_name(qctl->qc_type), qctl->qc_id);
8505                 printf("%15s%8s %7s%8s%8s%8s %7s%8s%8s\n",
8506                        "Filesystem", human_readable ? "used" : "kbytes",
8507                        "quota", "limit", "grace",
8508                        "files", "quota", "limit", "grace");
8509         }
8510 }
8511
8512 static void kbytes2str(__u64 num, char *buf, int buflen, bool h)
8513 {
8514         if (!h) {
8515                 snprintf(buf, buflen, "%ju", (uintmax_t)num);
8516         } else {
8517                 if (num >> 40)
8518                         snprintf(buf, buflen, "%5.4gP",
8519                                  (double)num / ((__u64)1 << 40));
8520                 else if (num >> 30)
8521                         snprintf(buf, buflen, "%5.4gT",
8522                                  (double)num / (1 << 30));
8523                 else if (num >> 20)
8524                         snprintf(buf, buflen, "%5.4gG",
8525                                  (double)num / (1 << 20));
8526                 else if (num >> 10)
8527                         snprintf(buf, buflen, "%5.4gM",
8528                                  (double)num / (1 << 10));
8529                 else
8530                         snprintf(buf, buflen, "%ju%s", (uintmax_t)num, "k");
8531         }
8532 }
8533
8534 #ifdef HAVE_NATIVE_CLIENT
8535 /* In the current Lustre implementation, the grace time is either the time
8536  * or the timestamp to be used after some quota ID exceeds the soft limt,
8537  * 48 bits should be enough, its high 16 bits can be used as quota flags.
8538  */
8539 #define LQUOTA_GRACE_BITS       48
8540 #define LQUOTA_GRACE_MASK       ((1ULL << LQUOTA_GRACE_BITS) - 1)
8541 #define LQUOTA_GRACE_MAX        LQUOTA_GRACE_MASK
8542 #define LQUOTA_GRACE(t)         (t & LQUOTA_GRACE_MASK)
8543 #define LQUOTA_FLAG(t)          (t >> LQUOTA_GRACE_BITS)
8544 #define LQUOTA_GRACE_FLAG(t, f) ((__u64)t | (__u64)f << LQUOTA_GRACE_BITS)
8545 #endif
8546
8547 #define STRBUF_LEN      24
8548 static void print_quota(char *mnt, struct if_quotactl *qctl, int type,
8549                         int rc, bool h, bool show_default)
8550 {
8551         time_t now;
8552
8553         time(&now);
8554
8555         if (qctl->qc_cmd == LUSTRE_Q_GETQUOTA || qctl->qc_cmd == Q_GETOQUOTA ||
8556             qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL ||
8557             qctl->qc_cmd == LUSTRE_Q_GETDEFAULT ||
8558             qctl->qc_cmd == LUSTRE_Q_GETDEFAULT_POOL) {
8559                 int bover = 0, iover = 0;
8560                 struct obd_dqblk *dqb = &qctl->qc_dqblk;
8561                 char numbuf[3][STRBUF_LEN + 2]; /* 2 for brackets or wildcard */
8562                 char timebuf[40];
8563                 char strbuf[STRBUF_LEN];
8564
8565                 dqb->dqb_btime &= LQUOTA_GRACE_MASK;
8566                 dqb->dqb_itime &= LQUOTA_GRACE_MASK;
8567
8568                 if (dqb->dqb_bhardlimit &&
8569                     lustre_stoqb(dqb->dqb_curspace) >= dqb->dqb_bhardlimit) {
8570                         bover = 1;
8571                 } else if (dqb->dqb_bsoftlimit && dqb->dqb_btime) {
8572                         if (dqb->dqb_btime > now)
8573                                 bover = 2;
8574                         else
8575                                 bover = 3;
8576                 }
8577
8578                 if (dqb->dqb_ihardlimit &&
8579                     dqb->dqb_curinodes >= dqb->dqb_ihardlimit) {
8580                         iover = 1;
8581                 } else if (dqb->dqb_isoftlimit && dqb->dqb_itime) {
8582                         if (dqb->dqb_itime > now)
8583                                 iover = 2;
8584                         else
8585                                 iover = 3;
8586                 }
8587
8588                 if (strlen(mnt) > 15)
8589                         printf("%s\n%15s", mnt, "");
8590                 else
8591                         printf("%15s", mnt);
8592
8593                 if (show_default)
8594                         snprintf(timebuf, sizeof(timebuf), "%llu",
8595                                  (unsigned long long)dqb->dqb_btime);
8596                 else if (bover)
8597                         diff2str(dqb->dqb_btime, timebuf, now);
8598
8599                 kbytes2str(lustre_stoqb(dqb->dqb_curspace),
8600                            strbuf, sizeof(strbuf), h);
8601                 if (rc == -EREMOTEIO)
8602                         sprintf(numbuf[0], "%s*", strbuf);
8603                 else
8604                         sprintf(numbuf[0], (dqb->dqb_valid & QIF_SPACE) ?
8605                                 "%s" : "[%s]", strbuf);
8606
8607                 kbytes2str(dqb->dqb_bsoftlimit, strbuf, sizeof(strbuf), h);
8608                 if (type == QC_GENERAL)
8609                         sprintf(numbuf[1], (dqb->dqb_valid & QIF_BLIMITS) ?
8610                                 "%s" : "[%s]", strbuf);
8611                 else
8612                         sprintf(numbuf[1], "%s", "-");
8613
8614                 kbytes2str(dqb->dqb_bhardlimit, strbuf, sizeof(strbuf), h);
8615                 sprintf(numbuf[2], (dqb->dqb_valid & QIF_BLIMITS) ?
8616                         "%s" : "[%s]", strbuf);
8617
8618                 if (show_default)
8619                         printf(" %6s %7s %7s", numbuf[1], numbuf[2], timebuf);
8620                 else
8621                         printf(" %7s%c %6s %7s %7s",
8622                                numbuf[0], bover ? '*' : ' ', numbuf[1],
8623                                numbuf[2], bover > 1 ? timebuf : "-");
8624
8625                 if (show_default)
8626                         snprintf(timebuf, sizeof(timebuf), "%llu",
8627                                  (unsigned long long)dqb->dqb_itime);
8628                 else if (iover)
8629                         diff2str(dqb->dqb_itime, timebuf, now);
8630
8631                 snprintf(numbuf[0], sizeof(numbuf),
8632                          (dqb->dqb_valid & QIF_INODES) ? "%ju" : "[%ju]",
8633                          (uintmax_t)dqb->dqb_curinodes);
8634
8635                 if (type == QC_GENERAL)
8636                         sprintf(numbuf[1], (dqb->dqb_valid & QIF_ILIMITS) ?
8637                                 "%ju" : "[%ju]",
8638                                 (uintmax_t)dqb->dqb_isoftlimit);
8639                 else
8640                         sprintf(numbuf[1], "%s", "-");
8641
8642                 sprintf(numbuf[2], (dqb->dqb_valid & QIF_ILIMITS) ?
8643                         "%ju" : "[%ju]", (uintmax_t)dqb->dqb_ihardlimit);
8644
8645                 if (show_default)
8646                         printf(" %6s %7s %7s", numbuf[1], numbuf[2], timebuf);
8647                 else if (type != QC_OSTIDX)
8648                         printf(" %7s%c %6s %7s %7s",
8649                                numbuf[0], iover ? '*' : ' ', numbuf[1],
8650                                numbuf[2], iover > 1 ? timebuf : "-");
8651                 else
8652                         printf(" %7s %7s %7s %7s", "-", "-", "-", "-");
8653                 printf("\n");
8654         } else if (qctl->qc_cmd == LUSTRE_Q_GETINFO ||
8655                    qctl->qc_cmd == LUSTRE_Q_GETINFOPOOL ||
8656                    qctl->qc_cmd == Q_GETOINFO) {
8657                 char bgtimebuf[40];
8658                 char igtimebuf[40];
8659
8660                 if (qctl->qc_dqinfo.dqi_bgrace == NOTIFY_GRACE_TIME)
8661                         strncpy(bgtimebuf, NOTIFY_GRACE, 40);
8662                 else
8663                         sec2str(qctl->qc_dqinfo.dqi_bgrace, bgtimebuf, rc);
8664                 if (qctl->qc_dqinfo.dqi_igrace == NOTIFY_GRACE_TIME)
8665                         strncpy(igtimebuf, NOTIFY_GRACE, 40);
8666                 else
8667                         sec2str(qctl->qc_dqinfo.dqi_igrace, igtimebuf, rc);
8668
8669                 printf("Block grace time: %s; Inode grace time: %s\n",
8670                        bgtimebuf, igtimebuf);
8671         }
8672 }
8673
8674 static int tgt_name2index(const char *tgtname, unsigned int *idx)
8675 {
8676         char *dash, *endp;
8677
8678         /* format is "lustre-OST0001" */
8679         dash = memchr(tgtname, '-', LUSTRE_MAXFSNAME + 1);
8680         if (!dash) {
8681                 fprintf(stderr, "wrong tgtname format '%s'\n", tgtname);
8682                 return -EINVAL;
8683         }
8684         dash += 4;
8685
8686         *idx = strtoul(dash, &endp, 16);
8687         if (*idx > 0xffff) {
8688                 fprintf(stderr, "wrong index %s\n", tgtname);
8689                 return -ERANGE;
8690         }
8691
8692         return 0;
8693 }
8694
8695 static int print_obd_quota(char *mnt, struct if_quotactl *qctl, int is_mdt,
8696                            bool h, __u64 *total)
8697 {
8698         int rc = 0, rc1 = 0, count = 0, i = 0;
8699         char **list = NULL, *buffer = NULL;
8700         __u32 valid = qctl->qc_valid;
8701
8702         if (qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL && is_mdt)
8703                 return 0;
8704
8705         /* Is it correct for the case OST0000, OST0002, OST0003 -
8706          * we will ask OST0001 that is absent and won't ask OST0003? */
8707         rc = llapi_get_obd_count(mnt, &count, is_mdt);
8708         if (rc) {
8709                 fprintf(stderr, "can not get %s count: %s\n",
8710                         is_mdt ? "mdt" : "ost", strerror(-rc));
8711                 return rc;
8712         }
8713
8714         if (qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL) {
8715                 char fname[PATH_MAX];
8716                 char fsname[LUSTRE_MAXFSNAME + 1];
8717                 int bufsize = sizeof(struct obd_uuid) * count;
8718
8719                 rc = llapi_search_fsname(mnt, fsname);
8720                 if (rc) {
8721                         fprintf(stderr, "cannot get fsname for mountpoint %s\n",
8722                                 mnt);
8723                         goto out;
8724                 }
8725                 buffer = malloc(bufsize + sizeof(*list) * count);
8726                 if (!buffer)
8727                         return -ENOMEM;
8728                 list = (char **)(buffer + bufsize);
8729                 snprintf(fname, PATH_MAX, "%s.%s", fsname, qctl->qc_poolname);
8730                 count = llapi_get_poolmembers(fname, list, count,
8731                                               buffer, bufsize);
8732                 if (count <= 0)
8733                         goto out;
8734         }
8735
8736         for (i = 0; i < count; i++) {
8737                 if (qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL) {
8738                         unsigned int index;
8739
8740                         if (tgt_name2index(list[i], &index))
8741                                 continue;
8742                         qctl->qc_idx = index;
8743                 } else {
8744                         qctl->qc_idx = i;
8745                 }
8746
8747                 qctl->qc_valid = is_mdt ? QC_MDTIDX : QC_OSTIDX;
8748                 rc = llapi_quotactl(mnt, qctl);
8749                 if (rc) {
8750                         /* It is remote client case. */
8751                         if (rc == -EOPNOTSUPP) {
8752                                 rc = 0;
8753                                 goto out;
8754                         }
8755
8756                         /* no target for this index yet */
8757                         if (rc == -ENODEV) {
8758                                 rc = 0;
8759                                 continue;
8760                         }
8761
8762                         /* inactive target */
8763                         if (rc == -ENODATA) {
8764                                 char name[UUID_MAX+8];
8765
8766                                 snprintf(name, sizeof(name), "%s[inact]",
8767                                         obd_uuid2str(&qctl->obd_uuid));
8768                                 memset(&qctl->qc_dqinfo, 0,
8769                                        sizeof(qctl->qc_dqinfo));
8770                                 memset(&qctl->qc_dqblk, 0,
8771                                        sizeof(qctl->qc_dqblk));
8772                                 print_quota(name, qctl, qctl->qc_valid, 0, h,
8773                                             false);
8774                                 rc = 0;
8775                                 continue;
8776                         }
8777
8778                         if (!rc1)
8779                                 rc1 = rc;
8780                         fprintf(stderr, "quotactl %s%d failed.\n",
8781                                 is_mdt ? "mdt" : "ost", qctl->qc_idx);
8782                         continue;
8783                 }
8784
8785                 print_quota(obd_uuid2str(&qctl->obd_uuid), qctl,
8786                             qctl->qc_valid, 0, h, false);
8787                 *total += is_mdt ? qctl->qc_dqblk.dqb_ihardlimit :
8788                                    qctl->qc_dqblk.dqb_bhardlimit;
8789         }
8790 out:
8791         if (buffer)
8792                 free(buffer);
8793         qctl->qc_valid = valid;
8794         return rc ? : rc1;
8795 }
8796
8797 static int get_print_quota(char *mnt, char *name, struct if_quotactl *qctl,
8798                            int verbose, int quiet, bool human_readable,
8799                            bool show_default)
8800 {
8801         int rc1 = 0, rc2 = 0, rc3 = 0;
8802         char *obd_type = (char *)qctl->obd_type;
8803         char *obd_uuid = (char *)qctl->obd_uuid.uuid;
8804         __u64 total_ialloc = 0, total_balloc = 0;
8805         bool use_default_for_blk = false;
8806         bool use_default_for_file = false;
8807         int inacc;
8808
8809         rc1 = llapi_quotactl(mnt, qctl);
8810         if (rc1 < 0) {
8811                 switch (rc1) {
8812                 case -ESRCH:
8813                         fprintf(stderr, "%s quotas are not enabled.\n",
8814                                 qtype_name(qctl->qc_type));
8815                         goto out;
8816                 case -EPERM:
8817                         fprintf(stderr, "Permission denied.\n");
8818                 case -ENODEV:
8819                 case -ENOENT:
8820                         /* We already got error message. */
8821                         goto out;
8822                 default:
8823                         fprintf(stderr, "Unexpected quotactl error: %s\n",
8824                                 strerror(-rc1));
8825                 }
8826         }
8827
8828         if (!show_default && qctl->qc_id == 0) {
8829                 qctl->qc_dqblk.dqb_bhardlimit = 0;
8830                 qctl->qc_dqblk.dqb_bsoftlimit = 0;
8831                 qctl->qc_dqblk.dqb_ihardlimit = 0;
8832                 qctl->qc_dqblk.dqb_isoftlimit = 0;
8833                 qctl->qc_dqblk.dqb_btime = 0;
8834                 qctl->qc_dqblk.dqb_itime = 0;
8835                 qctl->qc_dqblk.dqb_valid |= QIF_LIMITS | QIF_TIMES;
8836         }
8837
8838         if (qctl->qc_dqblk.dqb_valid & QIF_BTIME &&
8839             LQUOTA_FLAG(qctl->qc_dqblk.dqb_btime) & LQUOTA_FLAG_DEFAULT) {
8840                 use_default_for_blk = true;
8841                 qctl->qc_dqblk.dqb_btime &= LQUOTA_GRACE_MASK;
8842         }
8843
8844         if (qctl->qc_dqblk.dqb_valid & QIF_ITIME &&
8845             LQUOTA_FLAG(qctl->qc_dqblk.dqb_itime) & LQUOTA_FLAG_DEFAULT) {
8846                 use_default_for_file = true;
8847                 qctl->qc_dqblk.dqb_itime &= LQUOTA_GRACE_MASK;
8848         }
8849
8850         if ((qctl->qc_cmd == LUSTRE_Q_GETQUOTA ||
8851              qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL ||
8852              qctl->qc_cmd == LUSTRE_Q_GETDEFAULT_POOL ||
8853              qctl->qc_cmd == LUSTRE_Q_GETDEFAULT) && !quiet)
8854                 print_quota_title(name, qctl, human_readable, show_default);
8855
8856         if (rc1 && *obd_type)
8857                 fprintf(stderr, "%s %s ", obd_type, obd_uuid);
8858
8859         if (qctl->qc_valid != QC_GENERAL)
8860                 mnt = "";
8861
8862         inacc = (qctl->qc_cmd == LUSTRE_Q_GETQUOTA ||
8863                  qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL) &&
8864                 ((qctl->qc_dqblk.dqb_valid & (QIF_LIMITS|QIF_USAGE)) !=
8865                  (QIF_LIMITS|QIF_USAGE));
8866
8867         print_quota(mnt, qctl, QC_GENERAL, rc1, human_readable, show_default);
8868
8869         if (!show_default && verbose &&
8870             qctl->qc_valid == QC_GENERAL && qctl->qc_cmd != LUSTRE_Q_GETINFO &&
8871             qctl->qc_cmd != LUSTRE_Q_GETINFOPOOL) {
8872                 char strbuf[STRBUF_LEN];
8873
8874                 rc2 = print_obd_quota(mnt, qctl, 1, human_readable,
8875                                       &total_ialloc);
8876                 rc3 = print_obd_quota(mnt, qctl, 0, human_readable,
8877                                       &total_balloc);
8878                 kbytes2str(total_balloc, strbuf, sizeof(strbuf),
8879                            human_readable);
8880                 printf("Total allocated inode limit: %ju, total allocated block limit: %s\n",
8881                        (uintmax_t)total_ialloc, strbuf);
8882         }
8883
8884         if (use_default_for_blk)
8885                 printf("%cid %u is using default block quota setting\n",
8886                        *qtype_name(qctl->qc_type), qctl->qc_id);
8887
8888         if (use_default_for_file)
8889                 printf("%cid %u is using default file quota setting\n",
8890                        *qtype_name(qctl->qc_type), qctl->qc_id);
8891
8892         if (rc1 || rc2 || rc3 || inacc)
8893                 printf("Some errors happened when getting quota info. Some devices may be not working or deactivated. The data in \"[]\" is inaccurate.\n");
8894 out:
8895         if (rc1)
8896                 return rc1;
8897         if (rc2)
8898                 return rc2;
8899         if (rc3)
8900                 return rc3;
8901         if (inacc)
8902                 return -EIO;
8903
8904         return 0;
8905 }
8906
8907 static int lfs_project(int argc, char **argv)
8908 {
8909         int ret = 0, err = 0, c, i;
8910         struct project_handle_control phc = { 0 };
8911         enum lfs_project_ops_t op;
8912
8913         phc.newline = true;
8914         phc.assign_projid = false;
8915         /* default action */
8916         op = LFS_PROJECT_LIST;
8917
8918         while ((c = getopt(argc, argv, "p:cCsdkr0")) != -1) {
8919                 switch (c) {
8920                 case 'c':
8921                         if (op != LFS_PROJECT_LIST) {
8922                                 fprintf(stderr,
8923                                         "%s: cannot specify '-c' '-C' '-s' together\n",
8924                                         progname);
8925                                 return CMD_HELP;
8926                         }
8927
8928                         op = LFS_PROJECT_CHECK;
8929                         break;
8930                 case 'C':
8931                         if (op != LFS_PROJECT_LIST) {
8932                                 fprintf(stderr,
8933                                         "%s: cannot specify '-c' '-C' '-s' together\n",
8934                                         progname);
8935                                 return CMD_HELP;
8936                         }
8937
8938                         op = LFS_PROJECT_CLEAR;
8939                         break;
8940                 case 's':
8941                         if (op != LFS_PROJECT_LIST) {
8942                                 fprintf(stderr,
8943                                         "%s: cannot specify '-c' '-C' '-s' together\n",
8944                                         progname);
8945                                 return CMD_HELP;
8946                         }
8947
8948                         phc.set_inherit = true;
8949                         op = LFS_PROJECT_SET;
8950                         break;
8951                 case 'd':
8952                         phc.dironly = true;
8953                         break;
8954                 case 'k':
8955                         phc.keep_projid = true;
8956                         break;
8957                 case 'r':
8958                         phc.recursive = true;
8959                         break;
8960                 case 'p':
8961                         if (str2quotaid(&phc.projid, optarg)) {
8962                                 fprintf(stderr,
8963                                         "Invalid project ID: %s\n",
8964                                         optarg);
8965                                 return CMD_HELP;
8966                         }
8967
8968                         phc.assign_projid = true;
8969
8970                         break;
8971                 case '0':
8972                         phc.newline = false;
8973                         break;
8974                 default:
8975                         fprintf(stderr, "%s: invalid option '%c'\n",
8976                                 progname, optopt);
8977                         return CMD_HELP;
8978                 }
8979         }
8980
8981         if (phc.assign_projid && op == LFS_PROJECT_LIST) {
8982                 op = LFS_PROJECT_SET;
8983                 phc.set_projid = true;
8984         } else if (phc.assign_projid && op == LFS_PROJECT_SET) {
8985                 phc.set_projid = true;
8986         }
8987
8988         switch (op) {
8989         case LFS_PROJECT_CHECK:
8990                 if (phc.keep_projid) {
8991                         fprintf(stderr,
8992                                 "%s: '-k' is useless together with '-c'\n",
8993                                 progname);
8994                         return CMD_HELP;
8995                 }
8996                 break;
8997         case LFS_PROJECT_CLEAR:
8998                 if (!phc.newline) {
8999                         fprintf(stderr,
9000                                 "%s: '-0' is useless together with '-C'\n",
9001                                 progname);
9002                         return CMD_HELP;
9003                 }
9004                 if (phc.assign_projid) {
9005                         fprintf(stderr,
9006                                 "%s: '-p' is useless together with '-C'\n",
9007                                 progname);
9008                         return CMD_HELP;
9009                 }
9010                 break;
9011         case LFS_PROJECT_SET:
9012                 if (!phc.newline) {
9013                         fprintf(stderr,
9014                                 "%s: '-0' is useless together with '-s'\n",
9015                                 progname);
9016                         return CMD_HELP;
9017                 }
9018                 if (phc.keep_projid) {
9019                         fprintf(stderr,
9020                                 "%s: '-k' is useless together with '-s'\n",
9021                                 progname);
9022                         return CMD_HELP;
9023                 }
9024                 break;
9025         default:
9026                 if (!phc.newline) {
9027                         fprintf(stderr,
9028                                 "%s: '-0' is useless for list operations\n",
9029                                 progname);
9030                         return CMD_HELP;
9031                 }
9032                 break;
9033         }
9034
9035         argv += optind;
9036         argc -= optind;
9037         if (argc == 0) {
9038                 fprintf(stderr, "%s: missing file or directory target(s)\n",
9039                         progname);
9040                 return CMD_HELP;
9041         }
9042
9043         for (i = 0; i < argc; i++) {
9044                 switch (op) {
9045                 case LFS_PROJECT_CHECK:
9046                         err = lfs_project_check(argv[i], &phc);
9047                         break;
9048                 case LFS_PROJECT_LIST:
9049                         err = lfs_project_list(argv[i], &phc);
9050                         break;
9051                 case LFS_PROJECT_CLEAR:
9052                         err = lfs_project_clear(argv[i], &phc);
9053                         break;
9054                 case LFS_PROJECT_SET:
9055                         err = lfs_project_set(argv[i], &phc);
9056                         break;
9057                 default:
9058                         break;
9059                 }
9060                 if (err && !ret)
9061                         ret = err;
9062         }
9063
9064         return ret;
9065 }
9066
9067 static int lfs_quota(int argc, char **argv)
9068 {
9069         int c;
9070         char *mnt, *name = NULL;
9071         struct if_quotactl *qctl;
9072         char *obd_uuid;
9073         int rc = 0, rc1 = 0, verbose = 0, quiet = 0;
9074         __u32 valid = QC_GENERAL, idx = 0;
9075         bool human_readable = false;
9076         bool show_default = false;
9077         int qtype;
9078         bool show_pools = false;
9079         struct option long_opts[] = {
9080         { .val = LFS_POOL_OPT, .name = "pool", .has_arg = optional_argument },
9081         { .name = NULL } };
9082         char **poollist = NULL;
9083         char *buf = NULL;
9084         int poolcount, i;
9085
9086         qctl = calloc(1, sizeof(*qctl) + LOV_MAXPOOLNAME + 1);
9087         if (!qctl)
9088                 return -ENOMEM;
9089
9090         qctl->qc_cmd = LUSTRE_Q_GETQUOTA;
9091         qctl->qc_type = ALLQUOTA;
9092         obd_uuid = (char *)qctl->obd_uuid.uuid;
9093
9094         while ((c = getopt_long(argc, argv, "gGi:I:o:pPqtuUvh",
9095                 long_opts, NULL)) != -1) {
9096                 switch (c) {
9097                 case 'U':
9098                         show_default = true;
9099                 case 'u':
9100                         qtype = USRQUOTA;
9101                         goto quota_type;
9102                 case 'G':
9103                         show_default = true;
9104                 case 'g':
9105                         qtype = GRPQUOTA;
9106                         goto quota_type;
9107                 case 'P':
9108                         show_default = true;
9109                 case 'p':
9110                         qtype = PRJQUOTA;
9111 quota_type:
9112                         if (qctl->qc_type != ALLQUOTA) {
9113                                 fprintf(stderr,
9114                                         "%s quota: only one of -u, -g, or -p may be specified\n",
9115                                         progname);
9116                                 rc = CMD_HELP;
9117                                 goto out;
9118                         }
9119                         qctl->qc_type = qtype;
9120                         break;
9121                 case 't':
9122                         qctl->qc_cmd = LUSTRE_Q_GETINFO;
9123                         break;
9124                 case 'o':
9125                         valid = qctl->qc_valid = QC_UUID;
9126                         snprintf(obd_uuid, sizeof(*obd_uuid), "%s", optarg);
9127                         break;
9128                 case 'i':
9129                         valid = qctl->qc_valid = QC_MDTIDX;
9130                         idx = qctl->qc_idx = atoi(optarg);
9131                         if (idx == 0 && *optarg != '0') {
9132                                 fprintf(stderr,
9133                                         "%s quota: invalid MDT index '%s'\n",
9134                                         progname, optarg);
9135                                 rc = CMD_HELP;
9136                                 goto out;
9137                         }
9138                         break;
9139                 case 'I':
9140                         valid = qctl->qc_valid = QC_OSTIDX;
9141                         idx = qctl->qc_idx = atoi(optarg);
9142                         if (idx == 0 && *optarg != '0') {
9143                                 fprintf(stderr,
9144                                         "%s quota: invalid OST index '%s'\n",
9145                                         progname, optarg);
9146                                 rc = CMD_HELP;
9147                                 goto out;
9148                         }
9149                         break;
9150                 case 'v':
9151                         verbose = 1;
9152                         break;
9153                 case 'q':
9154                         quiet = 1;
9155                         break;
9156                 case 'h':
9157                         human_readable = true;
9158                         break;
9159                 case LFS_POOL_OPT:
9160                         if ((!optarg) && (argv[optind] != NULL) &&
9161                                 (argv[optind][0] != '-') &&
9162                                 (argv[optind][0] != '/')) {
9163                                 optarg = argv[optind++];
9164                                 if (lfs_verify_poolarg(optarg)) {
9165                                         rc = -EINVAL;
9166                                         goto out;
9167                                 }
9168                                 strncpy(qctl->qc_poolname, optarg,
9169                                         LOV_MAXPOOLNAME);
9170                                 if (qctl->qc_cmd == LUSTRE_Q_GETINFO)
9171                                         qctl->qc_cmd = LUSTRE_Q_GETINFOPOOL;
9172                                 else
9173                                         qctl->qc_cmd = LUSTRE_Q_GETQUOTAPOOL;
9174                                 break;
9175                         }
9176
9177                         /* optarg is NULL */
9178                         show_pools = true;
9179                         qctl->qc_cmd = LUSTRE_Q_GETQUOTAPOOL;
9180                         break;
9181                 default:
9182                         fprintf(stderr, "%s quota: unrecognized option '%s'\n",
9183                                 progname, argv[optind - 1]);
9184                         rc = CMD_HELP;
9185                         goto out;
9186                 }
9187         }
9188
9189         /* current uid/gid info for "lfs quota /path/to/lustre/mount" */
9190         if ((qctl->qc_cmd == LUSTRE_Q_GETQUOTA ||
9191              qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL) &&
9192              qctl->qc_type == ALLQUOTA &&
9193              optind == argc - 1 && !show_default) {
9194                 qctl->qc_idx = idx;
9195
9196                 for (qtype = USRQUOTA; qtype <= GRPQUOTA; qtype++) {
9197                         qctl->qc_type = qtype;
9198                         qctl->qc_valid = valid;
9199                         if (qtype == USRQUOTA) {
9200                                 qctl->qc_id = geteuid();
9201                                 rc = uid2name(&name, qctl->qc_id);
9202                         } else {
9203                                 qctl->qc_id = getegid();
9204                                 rc = gid2name(&name, qctl->qc_id);
9205                                 memset(&qctl->qc_dqblk, 0,
9206                                        sizeof(qctl->qc_dqblk));
9207                         }
9208                         if (rc)
9209                                 name = "<unknown>";
9210                         mnt = argv[optind];
9211                         rc1 = get_print_quota(mnt, name, qctl, verbose, quiet,
9212                                               human_readable, show_default);
9213                         if (rc1 && !rc)
9214                                 rc = rc1;
9215                 }
9216                 goto out;
9217         /* lfs quota -u username /path/to/lustre/mount */
9218         } else if (qctl->qc_cmd == LUSTRE_Q_GETQUOTA ||
9219                    qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL) {
9220                 /* options should be followed by u/g-name and mntpoint */
9221                 if ((!show_default && optind + 2 != argc) ||
9222                     (show_default && optind + 1 != argc) ||
9223                     qctl->qc_type == ALLQUOTA) {
9224                         fprintf(stderr,
9225                                 "%s quota: name and mount point must be specified\n",
9226                                 progname);
9227                         rc = CMD_HELP;
9228                         goto out;
9229                 }
9230
9231                 if (!show_default) {
9232                         name = argv[optind++];
9233                         switch (qctl->qc_type) {
9234                         case USRQUOTA:
9235                                 rc = name2uid(&qctl->qc_id, name);
9236                                 break;
9237                         case GRPQUOTA:
9238                                 rc = name2gid(&qctl->qc_id, name);
9239                                 break;
9240                         case PRJQUOTA:
9241                                 rc = name2projid(&qctl->qc_id, name);
9242                                 break;
9243                         default:
9244                                 rc = -ENOTSUP;
9245                                 break;
9246                         }
9247                 } else {
9248                         qctl->qc_valid = QC_GENERAL;
9249                         qctl->qc_cmd = qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL ?
9250                                         LUSTRE_Q_GETDEFAULT_POOL :
9251                                         LUSTRE_Q_GETDEFAULT;
9252                         qctl->qc_id = 0;
9253                 }
9254
9255                 if (rc) {
9256                         if (str2quotaid(&qctl->qc_id, name)) {
9257                                 fprintf(stderr, "%s quota: invalid id '%s'\n",
9258                                         progname, name);
9259                                 rc = CMD_HELP;
9260                                 goto out;
9261                         }
9262                 }
9263         } else if (optind + 1 != argc || qctl->qc_type == ALLQUOTA) {
9264                 fprintf(stderr, "%s quota: missing quota info argument(s)\n",
9265                         progname);
9266                 rc = CMD_HELP;
9267                 goto out;
9268         }
9269
9270         mnt = argv[optind];
9271         if (show_pools) {
9272                 char *p;
9273
9274                 i = 0;
9275                 rc = llapi_get_poolbuf(mnt, &buf, &poollist, &poolcount);
9276                 if (rc)
9277                         goto out;
9278
9279                 for (i = 0; i < poolcount; i++) {
9280                         p = memchr(poollist[i], '.', MAXNAMLEN);
9281                         if (!p) {
9282                                 fprintf(stderr, "bad string format %.*s\n",
9283                                         MAXNAMLEN, poollist[i]);
9284                                 rc = -EINVAL;
9285                                 goto out;
9286                         }
9287                         p++;
9288                         printf("Quotas for pool: %s\n", p);
9289                         strncpy(qctl->qc_poolname, p, LOV_MAXPOOLNAME);
9290                         rc = get_print_quota(mnt, name, qctl, verbose, quiet,
9291                                              human_readable, show_default);
9292                         if (rc)
9293                                 break;
9294                 }
9295                 goto out;
9296         }
9297
9298         rc = get_print_quota(mnt, name, qctl, verbose, quiet,
9299                              human_readable, show_default);
9300 out:
9301         free(buf);
9302         free(qctl);
9303         return rc;
9304 }
9305 #endif /* HAVE_SYS_QUOTA_H! */
9306
9307 static int flushctx_ioctl(char *mp)
9308 {
9309         int fd, rc;
9310
9311         fd = open(mp, O_RDONLY);
9312         if (fd == -1) {
9313                 fprintf(stderr, "flushctx: error open %s: %s\n",
9314                         mp, strerror(errno));
9315                 return -1;
9316         }
9317
9318         rc = ioctl(fd, LL_IOC_FLUSHCTX);
9319         if (rc == -1)
9320                 fprintf(stderr, "flushctx: error ioctl %s: %s\n",
9321                         mp, strerror(errno));
9322
9323         close(fd);
9324         return rc;
9325 }
9326
9327 static int lfs_flushctx(int argc, char **argv)
9328 {
9329         int     kdestroy = 0, reap = 0, c;
9330         char    mntdir[PATH_MAX] = {'\0'};
9331         int     index = 0;
9332         int     rc = 0;
9333
9334         while ((c = getopt(argc, argv, "kr")) != -1) {
9335                 switch (c) {
9336                 case 'k':
9337                         kdestroy = 1;
9338                         break;
9339                 case 'r':
9340                         reap = 1;
9341                         break;
9342                 default:
9343                         fprintf(stderr,
9344                                 "error: %s: option '-%c' unrecognized\n",
9345                                 argv[0], c);
9346                         return CMD_HELP;
9347                 }
9348         }
9349
9350         if (kdestroy) {
9351                 rc = system("kdestroy > /dev/null");
9352                 if (rc) {
9353                         rc = WEXITSTATUS(rc);
9354                         fprintf(stderr,
9355                                 "error destroying tickets: %d, continuing\n",
9356                                 rc);
9357                 }
9358         }
9359
9360         if (optind >= argc) {
9361                 /* flush for all mounted lustre fs. */
9362                 while (!llapi_search_mounts(NULL, index++, mntdir, NULL)) {
9363                         /* Check if we have a mount point */
9364                         if (mntdir[0] == '\0')
9365                                 continue;
9366
9367                         if (flushctx_ioctl(mntdir))
9368                                 rc = -1;
9369
9370                         mntdir[0] = '\0'; /* avoid matching in next loop */
9371                 }
9372         } else {
9373                 /* flush fs as specified */
9374                 while (optind < argc) {
9375                         if (flushctx_ioctl(argv[optind++]))
9376                                 rc = -1;
9377                 }
9378         }
9379
9380         if (reap) {
9381                 rc = system("keyctl reap > /dev/null");
9382                 if (rc != 0) {
9383                         rc = WEXITSTATUS(rc);
9384                         fprintf(stderr, "error reaping keyring: %d\n", rc);
9385                 }
9386         }
9387
9388         return rc;
9389 }
9390
9391 static int lfs_changelog(int argc, char **argv)
9392 {
9393         void *changelog_priv;
9394         struct changelog_rec *rec;
9395         long long startrec = 0, endrec = 0;
9396         char *mdd;
9397         struct option long_opts[] = {
9398                 { .val = 'f', .name = "follow", .has_arg = no_argument },
9399                 { .name = NULL } };
9400         char short_opts[] = "f";
9401         int rc, follow = 0;
9402
9403         while ((rc = getopt_long(argc, argv, short_opts,
9404                 long_opts, NULL)) != -1) {
9405                 switch (rc) {
9406                 case 'f':
9407                         follow++;
9408                         break;
9409                 default:
9410                         fprintf(stderr,
9411                                 "%s changelog: unrecognized option '%s'\n",
9412                                 progname, argv[optind - 1]);
9413                         return CMD_HELP;
9414                 }
9415         }
9416         if (optind >= argc) {
9417                 fprintf(stderr, "%s changelog: mdtname must be specified\n",
9418                         progname);
9419                 return CMD_HELP;
9420         }
9421
9422         mdd = argv[optind++];
9423         if (argc > optind) {
9424                 errno = 0;
9425                 startrec = strtoll(argv[optind++], NULL, 10);
9426                 if (errno != 0 || startrec < 0) {
9427                         fprintf(stderr,
9428                                 "%s changelog: bad startrec\n",
9429                                 progname);
9430                         return CMD_HELP;
9431                 }
9432         }
9433
9434         if (argc > optind) {
9435                 errno = 0;
9436                 endrec = strtoll(argv[optind++], NULL, 10);
9437                 if (errno != 0 || endrec < 0) {
9438                         fprintf(stderr,
9439                                 "%s changelog: bad endrec\n",
9440                                 progname);
9441                         return CMD_HELP;
9442                 }
9443         }
9444
9445         rc = llapi_changelog_start(&changelog_priv,
9446                                    CHANGELOG_FLAG_BLOCK |
9447                                    CHANGELOG_FLAG_JOBID |
9448                                    CHANGELOG_FLAG_EXTRA_FLAGS |
9449                                    (follow ? CHANGELOG_FLAG_FOLLOW : 0),
9450                                    mdd, startrec);
9451         if (rc < 0) {
9452                 fprintf(stderr, "%s changelog: cannot start changelog: %s\n",
9453                         progname, strerror(errno = -rc));
9454                 return rc;
9455         }
9456
9457         rc = llapi_changelog_set_xflags(changelog_priv,
9458                                         CHANGELOG_EXTRA_FLAG_UIDGID |
9459                                         CHANGELOG_EXTRA_FLAG_NID |
9460                                         CHANGELOG_EXTRA_FLAG_OMODE |
9461                                         CHANGELOG_EXTRA_FLAG_XATTR);
9462         if (rc < 0) {
9463                 fprintf(stderr,
9464                         "%s changelog: cannot set xflags for changelog: %s\n",
9465                         progname, strerror(errno = -rc));
9466                 return rc;
9467         }
9468
9469         while ((rc = llapi_changelog_recv(changelog_priv, &rec)) == 0) {
9470                 time_t secs;
9471                 struct tm ts;
9472
9473                 if (endrec && rec->cr_index > endrec) {
9474                         llapi_changelog_free(&rec);
9475                         break;
9476                 }
9477                 if (rec->cr_index < startrec) {
9478                         llapi_changelog_free(&rec);
9479                         continue;
9480                 }
9481
9482                 secs = rec->cr_time >> 30;
9483                 gmtime_r(&secs, &ts);
9484                 printf("%ju %02d%-5s %02d:%02d:%02d.%09d %04d.%02d.%02d "
9485                        "0x%x t="DFID, (uintmax_t)rec->cr_index, rec->cr_type,
9486                        changelog_type2str(rec->cr_type),
9487                        ts.tm_hour, ts.tm_min, ts.tm_sec,
9488                        (int)(rec->cr_time & ((1 << 30) - 1)),
9489                        ts.tm_year + 1900, ts.tm_mon + 1, ts.tm_mday,
9490                        rec->cr_flags & CLF_FLAGMASK, PFID(&rec->cr_tfid));
9491
9492                 if (rec->cr_flags & CLF_JOBID) {
9493                         struct changelog_ext_jobid *jid =
9494                                 changelog_rec_jobid(rec);
9495
9496                         if (jid->cr_jobid[0] != '\0')
9497                                 printf(" j=%s", jid->cr_jobid);
9498                 }
9499
9500                 if (rec->cr_flags & CLF_EXTRA_FLAGS) {
9501                         struct changelog_ext_extra_flags *ef =
9502                                 changelog_rec_extra_flags(rec);
9503
9504                         printf(" ef=0x%llx",
9505                                (unsigned long long)ef->cr_extra_flags);
9506
9507                         if (ef->cr_extra_flags & CLFE_UIDGID) {
9508                                 struct changelog_ext_uidgid *uidgid =
9509                                         changelog_rec_uidgid(rec);
9510
9511                                 printf(" u=%llu:%llu",
9512                                        (unsigned long long)uidgid->cr_uid,
9513                                        (unsigned long long)uidgid->cr_gid);
9514                         }
9515                         if (ef->cr_extra_flags & CLFE_NID) {
9516                                 struct changelog_ext_nid *nid =
9517                                         changelog_rec_nid(rec);
9518
9519                                 printf(" nid=%s",
9520                                        libcfs_nid2str(nid->cr_nid));
9521                         }
9522
9523                         if (ef->cr_extra_flags & CLFE_OPEN) {
9524                                 struct changelog_ext_openmode *omd =
9525                                         changelog_rec_openmode(rec);
9526                                 char mode[] = "---";
9527
9528                                 /* exec mode must be exclusive */
9529                                 if (omd->cr_openflags & MDS_FMODE_EXEC) {
9530                                         mode[2] = 'x';
9531                                 } else {
9532                                         if (omd->cr_openflags & MDS_FMODE_READ)
9533                                                 mode[0] = 'r';
9534                                         if (omd->cr_openflags &
9535                                             (MDS_FMODE_WRITE |
9536                                              MDS_OPEN_TRUNC |
9537                                              MDS_OPEN_APPEND))
9538                                                 mode[1] = 'w';
9539                                 }
9540
9541                                 if (strcmp(mode, "---") != 0)
9542                                         printf(" m=%s", mode);
9543                         }
9544
9545                         if (ef->cr_extra_flags & CLFE_XATTR) {
9546                                 struct changelog_ext_xattr *xattr =
9547                                         changelog_rec_xattr(rec);
9548
9549                                 if (xattr->cr_xattr[0] != '\0')
9550                                         printf(" x=%s", xattr->cr_xattr);
9551                         }
9552                 }
9553
9554                 if (!fid_is_zero(&rec->cr_pfid))
9555                         printf(" p="DFID, PFID(&rec->cr_pfid));
9556                 if (rec->cr_namelen)
9557                         printf(" %.*s", rec->cr_namelen,
9558                                changelog_rec_name(rec));
9559
9560                 if (rec->cr_flags & CLF_RENAME) {
9561                         struct changelog_ext_rename *rnm =
9562                                 changelog_rec_rename(rec);
9563
9564                         if (!fid_is_zero(&rnm->cr_sfid))
9565                                 printf(" s="DFID" sp="DFID" %.*s",
9566                                        PFID(&rnm->cr_sfid),
9567                                        PFID(&rnm->cr_spfid),
9568                                        (int)changelog_rec_snamelen(rec),
9569                                        changelog_rec_sname(rec));
9570                 }
9571                 printf("\n");
9572
9573                 llapi_changelog_free(&rec);
9574         }
9575
9576         llapi_changelog_fini(&changelog_priv);
9577
9578         if (rc < 0)
9579                 fprintf(stderr, "%s changelog: cannot access changelog: %s\n",
9580                         progname, strerror(errno = -rc));
9581
9582         return (rc == 1 ? 0 : rc);
9583 }
9584
9585 static int lfs_changelog_clear(int argc, char **argv)
9586 {
9587         long long endrec;
9588         int rc;
9589
9590         if (argc != 4)
9591                 return CMD_HELP;
9592
9593         errno = 0;
9594         endrec = strtoll(argv[3], NULL, 10);
9595         if (errno != 0 || endrec < 0) {
9596                 fprintf(stderr,
9597                         "%s: bad endrec '%s'\n",
9598                         argv[0], argv[3]);
9599                 return CMD_HELP;
9600         }
9601
9602         rc = llapi_changelog_clear(argv[1], argv[2], endrec);
9603
9604         if (rc == -EINVAL)
9605                 fprintf(stderr, "%s: record out of range: %llu\n",
9606                         argv[0], endrec);
9607         else if (rc == -ENOENT)
9608                 fprintf(stderr, "%s: no changelog user: %s\n",
9609                         argv[0], argv[2]);
9610         else if (rc)
9611                 fprintf(stderr, "%s error: %s\n", argv[0],
9612                         strerror(-rc));
9613
9614         if (rc)
9615                 errno = -rc;
9616
9617         return rc;
9618 }
9619
9620 static void rstripc(char *str, int c)
9621 {
9622         char *end = str + strlen(str);
9623
9624         for (; str < end && end[-1] == c; --end)
9625                 end[-1] = '\0';
9626 }
9627
9628 static int lfs_fid2path(int argc, char **argv)
9629 {
9630         struct option long_opts[] = {
9631                 { .val = '0',   .name = "print0",       .has_arg = no_argument },
9632                 { .val = 'c',   .name = "cur",  .has_arg = no_argument },
9633                 { .val = 'c',   .name = "current",      .has_arg = no_argument },
9634                 { .val = 'c',   .name = "print-link",   .has_arg = no_argument },
9635                 { .val = 'f',   .name = "print-fid",    .has_arg = no_argument },
9636                 { .val = 'l',   .name = "link", .has_arg = required_argument },
9637                 { .name = NULL } };
9638         char short_opts[] = "0cfl:pr:";
9639         bool print_link = false;
9640         bool print_fid = false;
9641         bool print_mnt_dir;
9642         char mnt_dir[PATH_MAX] = "";
9643         int mnt_fd = -1;
9644         char *path_or_fsname;
9645         long long recno = -1;
9646         int linkno = -1;
9647         char *endptr = NULL;
9648         char link_separator = '\n';
9649         int rc = 0;
9650         int c;
9651         int i;
9652
9653         while ((c = getopt_long(argc, argv, short_opts, long_opts, NULL)) != -1) {
9654                 switch (c) {
9655                 case '0':
9656                         link_separator = '\0';
9657                         break;
9658                 case 'c':
9659                         print_link = true;
9660                         break;
9661                 case 'f':
9662                         print_fid = true;
9663                         break;
9664                 case 'l':
9665                         errno = 0;
9666                         linkno = strtol(optarg, &endptr, 10);
9667                         if (errno != 0 || *endptr != '\0' || linkno < 0) {
9668                                 fprintf(stderr,
9669                                         "%s fid2path: invalid linkno '%s'\n",
9670                                         progname, optarg);
9671                                 return CMD_HELP;
9672                         }
9673                         break;
9674                 case 'r':
9675                         /* recno is something to do with changelogs
9676                          * that was never implemented. We just pass it
9677                          * through for the MDT to ignore.
9678                          */
9679                         errno = 0;
9680                         recno = strtoll(optarg, &endptr, 10);
9681                         if (errno != 0 || *endptr != '\0' || recno < 0) {
9682                                 fprintf(stderr,
9683                                         "%s fid2path: invalid recno '%s'\n",
9684                                         progname, optarg);
9685                                 return CMD_HELP;
9686                         }
9687                         break;
9688                 default:
9689                         fprintf(stderr,
9690                                 "%s fid2path: unrecognized option '%s'\n",
9691                                 progname, argv[optind - 1]);
9692                         return CMD_HELP;
9693                 }
9694         }
9695
9696         if (argc - optind < 2) {
9697                 fprintf(stderr,
9698                         "Usage: %s fid2path FSNAME|ROOT FID...\n",
9699                         progname);
9700                 return CMD_HELP;
9701         }
9702
9703         path_or_fsname = argv[optind];
9704
9705         if (*path_or_fsname == '/') {
9706                 print_mnt_dir = true;
9707                 rc = llapi_search_mounts(path_or_fsname, 0, mnt_dir, NULL);
9708         } else {
9709                 print_mnt_dir = false;
9710                 rc = llapi_search_rootpath(mnt_dir, path_or_fsname);
9711         }
9712
9713         if (rc < 0) {
9714                 fprintf(stderr,
9715                         "%s fid2path: cannot resolve mount point for '%s': %s\n",
9716                         progname, path_or_fsname, strerror(-rc));
9717                 goto out;
9718         }
9719
9720         mnt_fd = open(mnt_dir, O_RDONLY | O_DIRECTORY);
9721         if (mnt_fd < 0) {
9722                 fprintf(stderr,
9723                         "%s fid2path: cannot open mount point for '%s': %s\n",
9724                         progname, path_or_fsname, strerror(-rc));
9725                 goto out;
9726         }
9727
9728         /* Strip trailing slashes from mnt_dir. */
9729         rstripc(mnt_dir + 1, '/');
9730
9731         for (i = optind + 1; i < argc; i++) {
9732                 const char *fid_str = argv[i];
9733                 struct lu_fid fid;
9734                 int rc2;
9735
9736                 rc2 = llapi_fid_parse(fid_str, &fid, NULL);
9737                 if (rc2 < 0) {
9738                         fprintf(stderr,
9739                                 "%s fid2path: invalid FID '%s'\n",
9740                                 progname, fid_str);
9741                         if (rc == 0)
9742                                 rc = rc2;
9743
9744                         continue;
9745                 }
9746
9747                 int linktmp = (linkno >= 0) ? linkno : 0;
9748                 while (1) {
9749                         int oldtmp = linktmp;
9750                         long long rectmp = recno;
9751                         char path_buf[PATH_MAX];
9752
9753                         rc2 = llapi_fid2path_at(mnt_fd, &fid,
9754                                 path_buf, sizeof(path_buf), &rectmp, &linktmp);
9755                         if (rc2 < 0) {
9756                                 fprintf(stderr,
9757                                         "%s fid2path: cannot find %s %s: %s\n",
9758                                         progname, path_or_fsname, fid_str,
9759                                         strerror(-rc2));
9760                                 if (rc == 0)
9761                                         rc = rc2;
9762                                 break;
9763                         }
9764
9765                         if (print_fid)
9766                                 printf("%s ", fid_str);
9767
9768                         if (print_link)
9769                                 printf("%d ", linktmp);
9770
9771                         /* You may think this looks wrong or weird (and it is!)
9772                          * but we are actually trying to preserve the old quirky
9773                          * behaviors (enforced by our old quirky tests!) that
9774                          * make lfs so much fun to work on:
9775                          *
9776                          *   lustre 0x200000007:0x1:0x0 => "/"
9777                          *   /mnt/lustre 0x200000007:0x1:0x0 => "/mnt/lustre//"
9778                          *
9779                          * Note that llapi_fid2path() returns "" for the root
9780                          * FID. */
9781
9782                         printf("%s%s%s%c",
9783                                print_mnt_dir ? mnt_dir : "",
9784                                (print_mnt_dir || *path_buf == '\0') ?
9785                                "/" : "", path_buf, link_separator);
9786
9787                         if (linkno >= 0)
9788                                 /* specified linkno */
9789                                 break;
9790
9791                         if (oldtmp == linktmp)
9792                                 /* no more links */
9793                                 break;
9794                 }
9795         }
9796 out:
9797         if (!(mnt_fd < 0))
9798                 close(mnt_fd);
9799
9800         return rc;
9801 }
9802
9803 static int lfs_path2fid(int argc, char **argv)
9804 {
9805         struct option long_opts[] = {
9806                 { .val = 'p', .name = "parents", .has_arg = no_argument },
9807                 { .name = NULL } };
9808         char            **path;
9809         const char        short_opts[] = "p";
9810         const char       *sep = "";
9811         struct lu_fid     fid;
9812         int               rc = 0;
9813         bool              show_parents = false;
9814
9815         while ((rc = getopt_long(argc, argv, short_opts,
9816                                  long_opts, NULL)) != -1) {
9817                 switch (rc) {
9818                 case 'p':
9819                         show_parents = true;
9820                         break;
9821                 default:
9822                         fprintf(stderr,
9823                                 "%s path2fid: unrecognized option '%s'\n",
9824                                 progname, argv[optind - 1]);
9825                         return CMD_HELP;
9826                 }
9827         }
9828
9829         if (optind > argc - 1) {
9830                 fprintf(stderr, "%s path2fid: FILE... must be specified\n",
9831                         progname);
9832                 return CMD_HELP;
9833         } else if (optind < argc - 1) {
9834                 sep = ": ";
9835         }
9836
9837         rc = 0;
9838         for (path = argv + optind; optind < argc; path++, optind++) {
9839                 int err = 0;
9840
9841                 if (!show_parents) {
9842                         err = llapi_path2fid(*path, &fid);
9843                         if (!err)
9844                                 printf("%s%s"DFID"\n",
9845                                        *sep != '\0' ? *path : "", sep,
9846                                        PFID(&fid));
9847                 } else {
9848                         char            name[NAME_MAX + 1];
9849                         unsigned int    linkno = 0;
9850
9851                         while ((err = llapi_path2parent(*path, linkno, &fid,
9852                                                 name, sizeof(name))) == 0) {
9853                                 if (*sep != '\0' && linkno == 0)
9854                                         printf("%s%s", *path, sep);
9855
9856                                 printf("%s"DFID"/%s", linkno != 0 ? "\t" : "",
9857                                        PFID(&fid), name);
9858                                 linkno++;
9859                         }
9860
9861                         /* err == -ENODATA is end-of-loop */
9862                         if (linkno > 0 && err == -ENODATA) {
9863                                 printf("\n");
9864                                 err = 0;
9865                         }
9866                 }
9867
9868                 if (err) {
9869                         fprintf(stderr,
9870                                 "%s path2fid: cannot get %sfid for '%s': %s\n",
9871                                 progname, show_parents ? "parent " : "", *path,
9872                                 strerror(-err));
9873                         if (rc == 0) {
9874                                 rc = err;
9875                                 errno = -err;
9876                         }
9877                 }
9878         }
9879
9880         return rc;
9881 }
9882
9883 #define MAX_ERRNO       4095
9884 #define IS_ERR_VALUE(x) ((unsigned long)(x) >= (unsigned long)-MAX_ERRNO)
9885
9886 static int lfs_rmfid_and_show_errors(int rootfd, struct fid_array *fa)
9887 {
9888         int rc, rc2, k;
9889
9890         rc = llapi_rmfid_at(rootfd, fa);
9891         if (rc < 0) {
9892                 fprintf(stderr, "%s rmfid: cannot remove FIDs: %s\n",
9893                         progname, strerror(-rc));
9894                 return rc;
9895         }
9896
9897         for (k = 0; k < fa->fa_nr; k++) {
9898                 rc2 = (__s32)fa->fa_fids[k].f_ver;
9899                 if (!IS_ERR_VALUE(rc2))
9900                         continue;
9901
9902                 if (rc == 0)
9903                         rc = rc2;
9904
9905                 fa->fa_fids[k].f_ver = 0;
9906                 fprintf(stderr, "%s rmfid: cannot remove "DFID": %s\n",
9907                         progname, PFID(&fa->fa_fids[k]), strerror(-rc2));
9908         }
9909
9910         return rc;
9911 }
9912
9913 static int lfs_rmfid(int argc, char **argv)
9914 {
9915         int rc = 0, rc2, rc3 = 0, nr;
9916         struct fid_array *fa;
9917         const char *device;
9918         char *fidstr;
9919         int rootfd;
9920
9921         /* Interactive mode: Adjust optind */
9922         if (!optind)
9923                 optind++;
9924
9925         device = argv[optind++];
9926
9927         if (optind > argc - 1) {
9928                 fprintf(stderr, "%s rmfid: missing dirname\n", progname);
9929                 return CMD_HELP;
9930         }
9931
9932         nr = argc - optind;
9933
9934         rc = llapi_root_path_open(device, &rootfd);
9935         if (rc < 0) {
9936                 fprintf(stderr,
9937                         "%s rmfid: error opening device/fsname '%s': %s\n",
9938                         progname, device, strerror(-rc));
9939                 return -rc;
9940         }
9941
9942         fa = malloc(offsetof(struct fid_array, fa_fids[nr + 1]));
9943         if (!fa) {
9944                 fprintf(stderr, "%s rmfid: error allocating %zd bytes: %s\n",
9945                         progname, offsetof(struct fid_array, fa_fids[nr + 1]),
9946                         strerror(errno));
9947                 return -ENOMEM;
9948         }
9949
9950         fa->fa_nr = 0;
9951         rc = 0;
9952         while (optind < argc) {
9953                 char *origfidstr;
9954                 int found;
9955
9956                 origfidstr = fidstr = argv[optind++];
9957                 while (*fidstr == '[')
9958                         fidstr++;
9959                 found = sscanf(fidstr, SFID, RFID(&fa->fa_fids[fa->fa_nr]));
9960                 if (found != 3) {
9961                         fprintf(stderr, "lfs rmfid: '%s': Wrong FID format\n",
9962                                 origfidstr);
9963                         if (!rc3)
9964                                 rc3 = -EINVAL; /* Invalid argument */
9965                         continue;
9966                 }
9967                 fa->fa_nr++;
9968                 if (fa->fa_nr == OBD_MAX_FIDS_IN_ARRAY) {
9969                         /* start another batch */
9970                         rc2 = lfs_rmfid_and_show_errors(rootfd, fa);
9971                         if (rc2 && !rc)
9972                                 rc = rc2;
9973                         if (rc3)
9974                                 rc = rc3;
9975                         fa->fa_nr = 0;
9976                 }
9977         }
9978         if (fa->fa_nr) {
9979                 rc2 = lfs_rmfid_and_show_errors(rootfd, fa);
9980                 if (rc2 && !rc)
9981                         rc = rc2;
9982                 if (rc3)
9983                         rc = rc3;
9984         }
9985
9986         if (fa) {
9987                 free(fa);
9988                 fa = NULL;
9989         }
9990
9991         close(rootfd);
9992         return rc;
9993 }
9994
9995 static int lfs_data_version(int argc, char **argv)
9996 {
9997         int data_version_flags = LL_DV_RD_FLUSH; /* Read by default */
9998         __u64 data_version;
9999         char *path;
10000         int fd;
10001         int rc;
10002         int c;
10003
10004         if (argc < 2) {
10005                 fprintf(stderr, "%s: FILE must be specified\n",
10006                         progname);
10007                 return CMD_HELP;
10008         }
10009
10010         while ((c = getopt(argc, argv, "hnrw")) != -1) {
10011                 switch (c) {
10012                 case 'n':
10013                         data_version_flags = 0;
10014                         break;
10015                 case 'r':
10016                         data_version_flags |= LL_DV_RD_FLUSH;
10017                         break;
10018                 case 'w':
10019                         data_version_flags |= LL_DV_WR_FLUSH;
10020                         break;
10021                 default:
10022                         fprintf(stderr,
10023                                 "%s data_version: unrecognized option '%s'\n",
10024                                 progname, argv[optind - 1]);
10025                         fallthrough;
10026                 case 'h':
10027                         return CMD_HELP;
10028                 }
10029         }
10030         if (optind == argc) {
10031                 fprintf(stderr, "%s data_version: FILE must be specified\n",
10032                         progname);
10033                 return CMD_HELP;
10034         }
10035
10036         path = argv[optind];
10037         fd = open(path, O_RDONLY);
10038         if (fd < 0) {
10039                 rc = -errno;
10040                 fprintf(stderr, "%s data_version: cannot open file '%s': %s\n",
10041                         progname, path, strerror(-rc));
10042                 return rc;
10043         }
10044
10045         rc = llapi_get_data_version(fd, &data_version, data_version_flags);
10046         if (rc < 0)
10047                 fprintf(stderr,
10048                         "%s data_version: cannot get version for '%s': %s\n",
10049                         progname, path, strerror(-rc));
10050         else
10051                 printf("%ju" "\n", (uintmax_t)data_version);
10052
10053         close(fd);
10054         return rc;
10055 }
10056
10057 static int lfs_hsm_state(int argc, char **argv)
10058 {
10059         int rc = 0;
10060         int i = 1;
10061         char *path;
10062         struct hsm_user_state hus;
10063
10064         if (argc < 2)
10065                 return CMD_HELP;
10066
10067         do {
10068                 int rc2;
10069                 path = argv[i];
10070
10071                 rc2 = llapi_hsm_state_get(path, &hus);
10072                 if (rc2) {
10073                         fprintf(stderr,
10074                                 "%s %s: get HSM state for '%s' failed: %s\n",
10075                                 progname, argv[0], path, strerror(-rc2));
10076                         if (!rc)
10077                                 rc = rc2;
10078                         continue;
10079                 }
10080
10081                 /* Display path name and status flags */
10082                 printf("%s: (0x%08x)", path, hus.hus_states);
10083
10084                 if (hus.hus_states & HS_RELEASED)
10085                         printf(" released");
10086                 if (hus.hus_states & HS_EXISTS)
10087                         printf(" exists");
10088                 if (hus.hus_states & HS_DIRTY)
10089                         printf(" dirty");
10090                 if (hus.hus_states & HS_ARCHIVED)
10091                         printf(" archived");
10092                 /* Display user-settable flags */
10093                 if (hus.hus_states & HS_NORELEASE)
10094                         printf(" never_release");
10095                 if (hus.hus_states & HS_NOARCHIVE)
10096                         printf(" never_archive");
10097                 if (hus.hus_states & HS_LOST)
10098                         printf(" lost_from_hsm");
10099
10100                 if (hus.hus_archive_id != 0)
10101                         printf(", archive_id:%d", hus.hus_archive_id);
10102                 printf("\n");
10103
10104         } while (++i < argc);
10105
10106         return rc;
10107 }
10108
10109 #define LFS_HSM_SET   0
10110 #define LFS_HSM_CLEAR 1
10111
10112 /**
10113  * Generic function to set or clear HSM flags.
10114  * Used by hsm_set and hsm_clear.
10115  *
10116  * @mode  if LFS_HSM_SET, set the flags, if LFS_HSM_CLEAR, clear the flags.
10117  */
10118 static int lfs_hsm_change_flags(int argc, char **argv, int mode)
10119 {
10120         struct option long_opts[] = {
10121         { .val = 'A',   .name = "archived",     .has_arg = no_argument },
10122         { .val = 'a',   .name = "noarchive",    .has_arg = no_argument },
10123         { .val = 'd',   .name = "dirty",        .has_arg = no_argument },
10124         { .val = 'e',   .name = "exists",       .has_arg = no_argument },
10125         { .val = 'h',   .name = "help",         .has_arg = no_argument },
10126         { .val = 'i',   .name = "archive-id",   .has_arg = required_argument },
10127         { .val = 'l',   .name = "lost",         .has_arg = no_argument },
10128         { .val = 'r',   .name = "norelease",    .has_arg = no_argument },
10129         { .name = NULL } };
10130         __u64 mask = 0;
10131         int c, rc = 0;
10132         char *path;
10133         __u32 archive_id = 0;
10134         char *end = NULL;
10135
10136         if (argc < 3)
10137                 return CMD_HELP;
10138
10139         while ((c = getopt_long(argc, argv, "aAdehi:lr",
10140                                 long_opts, NULL)) != -1) {
10141                 switch (c) {
10142                 case 'l':
10143                         mask |= HS_LOST;
10144                         break;
10145                 case 'a':
10146                         mask |= HS_NOARCHIVE;
10147                         break;
10148                 case 'A':
10149                         mask |= HS_ARCHIVED;
10150                         break;
10151                 case 'r':
10152                         mask |= HS_NORELEASE;
10153                         break;
10154                 case 'd':
10155                         mask |= HS_DIRTY;
10156                         break;
10157                 case 'e':
10158                         mask |= HS_EXISTS;
10159                         break;
10160                 case 'i':
10161                         errno = 0;
10162                         archive_id = strtol(optarg, &end, 10);
10163                         if (errno != 0 || *end != '\0' || archive_id < 0) {
10164                                 fprintf(stderr,
10165                                         "%s: invalid archive_id: '%s'\n",
10166                                         progname, end);
10167                                 return CMD_HELP;
10168                         }
10169                         break;
10170                 default:
10171                         fprintf(stderr, "%s: unrecognized option '%s'\n",
10172                                 progname, argv[optind - 1]);
10173                         fallthrough;
10174                 case 'h':
10175                         return CMD_HELP;
10176                 }
10177         }
10178
10179         /* User should have specified a flag */
10180         if (mask == 0)
10181                 return CMD_HELP;
10182
10183         while (optind < argc) {
10184                 int rc2;
10185                 path = argv[optind];
10186
10187                 /* If mode == 0, this means we apply the mask. */
10188                 if (mode == LFS_HSM_SET)
10189                         rc2 = llapi_hsm_state_set(path, mask, 0, archive_id);
10190                 else
10191                         rc2 = llapi_hsm_state_set(path, 0, mask, 0);
10192
10193                 if (rc2) {
10194                         fprintf(stderr,
10195                                 "%s %s: change hsm flags for '%s' failed: %s\n",
10196                                 progname, argv[0], path, strerror(-rc2));
10197                         if (!rc)
10198                                 rc = rc2;
10199                 }
10200                 optind++;
10201         }
10202
10203         return rc;
10204 }
10205
10206 static int lfs_hsm_action(int argc, char **argv)
10207 {
10208         struct hsm_current_action hca;
10209         struct hsm_extent he;
10210         enum hsm_user_action hua;
10211         enum hsm_progress_states hps;
10212         int rc = 0;
10213         int i = 1;
10214         char *path;
10215
10216         if (argc < 2)
10217                 return CMD_HELP;
10218
10219         do {
10220                 int rc2;
10221                 path = argv[i];
10222
10223                 rc2 = llapi_hsm_current_action(path, &hca);
10224                 if (rc2) {
10225                         fprintf(stderr,
10226                                 "%s %s: get hsm action for '%s' failed: %s\n",
10227                                 progname, argv[0], path, strerror(-rc2));
10228
10229                         if (!rc)
10230                                 rc = rc2;
10231                         continue;
10232                 }
10233                 he = hca.hca_location;
10234                 hua = hca.hca_action;
10235                 hps = hca.hca_state;
10236
10237                 printf("%s: %s", path, hsm_user_action2name(hua));
10238
10239                 /* Skip file without action */
10240                 if (hca.hca_action == HUA_NONE) {
10241                         printf("\n");
10242                         continue;
10243                 }
10244
10245                 printf(" %s ", hsm_progress_state2name(hps));
10246
10247                 if ((hps == HPS_RUNNING) &&
10248                     (hua == HUA_ARCHIVE || hua == HUA_RESTORE))
10249                         printf("(%llu bytes moved)\n",
10250                                (unsigned long long)he.length);
10251                 else if ((he.offset + he.length) == LUSTRE_EOF)
10252                         printf("(from %llu to EOF)\n",
10253                                (unsigned long long)he.offset);
10254                 else
10255                         printf("(from %llu to %llu)\n",
10256                                (unsigned long long)he.offset,
10257                                (unsigned long long)(he.offset + he.length));
10258
10259         } while (++i < argc);
10260
10261         return rc;
10262 }
10263
10264 static int lfs_hsm_set(int argc, char **argv)
10265 {
10266         return lfs_hsm_change_flags(argc, argv, LFS_HSM_SET);
10267 }
10268
10269 static int lfs_hsm_clear(int argc, char **argv)
10270 {
10271         return lfs_hsm_change_flags(argc, argv, LFS_HSM_CLEAR);
10272 }
10273
10274 /**
10275  * Check file state and return its fid, to be used by lfs_hsm_request().
10276  *
10277  * \param[in]     file      Path to file to check
10278  * \param[in,out] fid       Pointer to allocated lu_fid struct.
10279  * \param[in,out] last_dev  Pointer to last device id used.
10280  *
10281  * \return 0 on success.
10282  */
10283 static int lfs_hsm_prepare_file(const char *file, struct lu_fid *fid,
10284                                 dev_t *last_dev)
10285 {
10286         struct stat     st;
10287         int             rc;
10288
10289         rc = lstat(file, &st);
10290         if (rc) {
10291                 fprintf(stderr, "Cannot stat %s: %s\n", file, strerror(errno));
10292                 return -errno;
10293         }
10294         /*
10295          * Checking for regular file as archiving as posix copytool
10296          * rejects archiving files other than regular files
10297          */
10298         if (!S_ISREG(st.st_mode)) {
10299                 fprintf(stderr, "error: \"%s\" is not a regular file\n", file);
10300                 return CMD_HELP;
10301         }
10302         /* A request should be ... */
10303         if (*last_dev != st.st_dev && *last_dev != 0) {
10304                 fprintf(stderr,
10305                         "All files should be on the same filesystem: %s\n",
10306                         file);
10307                 return -EINVAL;
10308         }
10309         *last_dev = st.st_dev;
10310
10311         rc = llapi_path2fid(file, fid);
10312         if (rc) {
10313                 fprintf(stderr, "Cannot read FID of %s: %s\n",
10314                         file, strerror(-rc));
10315                 return rc;
10316         }
10317         return 0;
10318 }
10319
10320 /* Fill an HSM HUR item with a given file name.
10321  *
10322  * If mntpath is set, then the filename is actually a FID, and no
10323  * lookup on the filesystem will be performed.
10324  *
10325  * \param[in]  hur         the user request to fill
10326  * \param[in]  idx         index of the item inside the HUR to fill
10327  * \param[in]  mntpath     mountpoint of Lustre
10328  * \param[in]  fname       filename (if mtnpath is NULL)
10329  *                         or FID (if mntpath is set)
10330  * \param[in]  last_dev    pointer to last device id used
10331  *
10332  * \retval 0 on success
10333  * \retval CMD_HELP or a negative errno on error
10334  */
10335 static int fill_hur_item(struct hsm_user_request *hur, unsigned int idx,
10336                          const char *mntpath, const char *fname,
10337                          dev_t *last_dev)
10338 {
10339         struct hsm_user_item *hui = &hur->hur_user_item[idx];
10340         int rc;
10341
10342         hui->hui_extent.length = -1;
10343
10344         if (mntpath) {
10345                 rc = llapi_fid_parse(fname, &hui->hui_fid, NULL);
10346                 if (rc)
10347                         fprintf(stderr, "hsm: '%s' is not a valid FID\n",
10348                                 fname);
10349         } else {
10350                 rc = lfs_hsm_prepare_file(fname, &hui->hui_fid, last_dev);
10351         }
10352
10353         if (rc == 0)
10354                 hur->hur_request.hr_itemcount++;
10355
10356         return rc;
10357 }
10358
10359 static int lfs_hsm_request(int argc, char **argv, int action)
10360 {
10361         struct option long_opts[] = {
10362         { .val = 'a',   .name = "archive",      .has_arg = required_argument },
10363         { .val = 'D',   .name = "data",         .has_arg = required_argument },
10364         { .val = 'h',   .name = "help",         .has_arg = no_argument },
10365         { .val = 'l',   .name = "filelist",     .has_arg = required_argument },
10366         { .val = 'm',   .name = "mntpath",      .has_arg = required_argument },
10367         { .name = NULL } };
10368         dev_t last_dev = 0;
10369         struct hsm_user_request *hur, *oldhur;
10370         int c, i;
10371         size_t len;
10372         int nbfile;
10373         char *line = NULL;
10374         char *filelist = NULL;
10375         char fullpath[PATH_MAX];
10376         char *opaque = NULL;
10377         int opaque_len = 0;
10378         int archive_id = 0;
10379         FILE *fp;
10380         int nbfile_alloc = 0;
10381         char *some_file = NULL;
10382         char *mntpath = NULL;
10383         int rc;
10384
10385         if (argc < 2)
10386                 return CMD_HELP;
10387
10388         while ((c = getopt_long(argc, argv, "a:D:hl:m:",
10389                                 long_opts, NULL)) != -1) {
10390                 switch (c) {
10391                 case 'l':
10392                         filelist = optarg;
10393                         break;
10394                 case 'D':
10395                         opaque = optarg;
10396                         break;
10397                 case 'a':
10398                         if (action != HUA_ARCHIVE &&
10399                             action != HUA_REMOVE) {
10400                                 fprintf(stderr,
10401                                         "error: -a is supported only when archiving or removing\n");
10402                                 return CMD_HELP;
10403                         }
10404                         archive_id = atoi(optarg);
10405                         break;
10406                 case 'm':
10407                         if (!some_file) {
10408                                 mntpath = optarg;
10409                                 some_file = strdup(optarg);
10410                         }
10411                         break;
10412                 default:
10413                         fprintf(stderr, "%s: unrecognized option '%s'\n",
10414                                 progname, argv[optind - 1]);
10415                         fallthrough;
10416                 case 'h':
10417                         return CMD_HELP;
10418                 }
10419         }
10420
10421         /* All remaining args are files, so we have at least nbfile */
10422         nbfile = argc - optind;
10423
10424         if ((nbfile == 0) && (!filelist))
10425                 return CMD_HELP;
10426
10427         if (opaque)
10428                 opaque_len = strlen(opaque);
10429
10430         /*
10431          * Alloc the request structure with enough place to store all files
10432          * from command line.
10433          */
10434         hur = llapi_hsm_user_request_alloc(nbfile, opaque_len);
10435         if (!hur) {
10436                 fprintf(stderr, "Cannot create the request: %s\n",
10437                         strerror(errno));
10438                 return errno;
10439         }
10440         nbfile_alloc = nbfile;
10441
10442         hur->hur_request.hr_action = action;
10443         hur->hur_request.hr_archive_id = archive_id;
10444         hur->hur_request.hr_flags = 0;
10445
10446         /* All remaining args are files, add them */
10447         if (nbfile != 0 && some_file == NULL)
10448                 some_file = strdup(argv[optind]);
10449
10450         for (i = 0; i < nbfile; i++) {
10451                 rc = fill_hur_item(hur, i, mntpath, argv[optind + i],
10452                                    &last_dev);
10453                 if (rc)
10454                         goto out_free;
10455         }
10456
10457         /* from here stop using nb_file, use hur->hur_request.hr_itemcount */
10458
10459         /* If a filelist was specified, read the filelist from it. */
10460         if (filelist) {
10461                 fp = fopen(filelist, "r");
10462                 if (!fp) {
10463                         fprintf(stderr, "Cannot read the file list %s: %s\n",
10464                                 filelist, strerror(errno));
10465                         rc = -errno;
10466                         goto out_free;
10467                 }
10468
10469                 while ((rc = getline(&line, &len, fp)) != -1) {
10470                         /*
10471                          * If allocated buffer was too small, get something
10472                          * larger
10473                          */
10474                         if (nbfile_alloc <= hur->hur_request.hr_itemcount) {
10475                                 ssize_t size;
10476
10477                                 nbfile_alloc = nbfile_alloc * 2 + 1;
10478                                 oldhur = hur;
10479                                 hur = llapi_hsm_user_request_alloc(nbfile_alloc,
10480                                                                    opaque_len);
10481                                 if (!hur) {
10482                                         fprintf(stderr,
10483                                                 "hsm: cannot allocate the request: %s\n",
10484                                                 strerror(errno));
10485                                         hur = oldhur;
10486                                         rc = -errno;
10487                                         fclose(fp);
10488                                         goto out_free;
10489                                 }
10490                                 size = hur_len(oldhur);
10491                                 if (size < 0) {
10492                                         fprintf(stderr,
10493                                                 "hsm: cannot allocate %u files + %u bytes data\n",
10494                                                 oldhur->hur_request.hr_itemcount,
10495                                                 oldhur->hur_request.hr_data_len);
10496                                         free(hur);
10497                                         hur = oldhur;
10498                                         rc = -E2BIG;
10499                                         fclose(fp);
10500                                         goto out_free;
10501                                 }
10502                                 memcpy(hur, oldhur, size);
10503                                 free(oldhur);
10504                         }
10505
10506                         /* Chop CR */
10507                         if (line[strlen(line) - 1] == '\n')
10508                                 line[strlen(line) - 1] = '\0';
10509
10510                         rc = fill_hur_item(hur, hur->hur_request.hr_itemcount,
10511                                            mntpath, line, &last_dev);
10512                         if (rc) {
10513                                 fclose(fp);
10514                                 goto out_free;
10515                         }
10516
10517                         if (!some_file) {
10518                                 some_file = line;
10519                                 line = NULL;
10520                         }
10521                 }
10522
10523                 rc = fclose(fp);
10524                 free(line);
10525         }
10526
10527         /* If a --data was used, add it to the request */
10528         hur->hur_request.hr_data_len = opaque_len;
10529         if (opaque)
10530                 memcpy(hur_data(hur), opaque, opaque_len);
10531
10532         /* Send the HSM request */
10533         if (realpath(some_file, fullpath) == NULL) {
10534                 fprintf(stderr, "Could not find path '%s': %s\n",
10535                         some_file, strerror(errno));
10536         }
10537         rc = llapi_hsm_request(fullpath, hur);
10538         if (rc) {
10539                 fprintf(stderr, "Cannot send HSM request (use of %s): %s\n",
10540                         some_file, strerror(-rc));
10541                 goto out_free;
10542         }
10543
10544 out_free:
10545         free(some_file);
10546         free(hur);
10547         return rc;
10548 }
10549
10550 static int lfs_hsm_archive(int argc, char **argv)
10551 {
10552         return lfs_hsm_request(argc, argv, HUA_ARCHIVE);
10553 }
10554
10555 static int lfs_hsm_restore(int argc, char **argv)
10556 {
10557         return lfs_hsm_request(argc, argv, HUA_RESTORE);
10558 }
10559
10560 static int lfs_hsm_release(int argc, char **argv)
10561 {
10562         return lfs_hsm_request(argc, argv, HUA_RELEASE);
10563 }
10564
10565 static int lfs_hsm_remove(int argc, char **argv)
10566 {
10567         return lfs_hsm_request(argc, argv, HUA_REMOVE);
10568 }
10569
10570 static int lfs_hsm_cancel(int argc, char **argv)
10571 {
10572         return lfs_hsm_request(argc, argv, HUA_CANCEL);
10573 }
10574
10575 static int lfs_swap_layouts(int argc, char **argv)
10576 {
10577         if (argc != 3)
10578                 return CMD_HELP;
10579
10580         return llapi_swap_layouts(argv[1], argv[2], 0, 0,
10581                                   SWAP_LAYOUTS_KEEP_MTIME |
10582                                   SWAP_LAYOUTS_KEEP_ATIME);
10583 }
10584
10585 static const char *const ladvise_names[] = LU_LADVISE_NAMES;
10586
10587 static const char *const lock_mode_names[] = LOCK_MODE_NAMES;
10588
10589 int lfs_get_mode(const char *string)
10590 {
10591         enum lock_mode_user mode;
10592
10593         for (mode = 0; mode < ARRAY_SIZE(lock_mode_names); mode++) {
10594                 if (lock_mode_names[mode] == NULL)
10595                         continue;
10596                 if (strcasecmp(string, lock_mode_names[mode]) == 0)
10597                         return mode;
10598         }
10599
10600         return -EINVAL;
10601 }
10602
10603 static enum lu_ladvise_type lfs_get_ladvice(const char *string)
10604 {
10605         enum lu_ladvise_type advice;
10606
10607         for (advice = 0;
10608              advice < ARRAY_SIZE(ladvise_names); advice++) {
10609                 if (ladvise_names[advice] == NULL)
10610                         continue;
10611                 if (strcmp(string, ladvise_names[advice]) == 0)
10612                         return advice;
10613         }
10614
10615         return LU_LADVISE_INVALID;
10616 }
10617
10618 static int lfs_ladvise(int argc, char **argv)
10619 {
10620         struct option long_opts[] = {
10621         { .val = 'a',   .name = "advice",       .has_arg = required_argument },
10622         { .val = 'b',   .name = "background",   .has_arg = no_argument },
10623         { .val = 'e',   .name = "end",          .has_arg = required_argument },
10624         { .val = 'h',   .name = "help",         .has_arg = no_argument },
10625         { .val = 'l',   .name = "length",       .has_arg = required_argument },
10626         { .val = 'm',   .name = "mode",         .has_arg = required_argument },
10627         { .val = 's',   .name = "start",        .has_arg = required_argument },
10628         { .val = 'u',   .name = "unset",        .has_arg = no_argument },
10629         { .name = NULL } };
10630         struct llapi_lu_ladvise advice;
10631         enum lu_ladvise_type advice_type = LU_LADVISE_INVALID;
10632         unsigned long long start = 0;
10633         unsigned long long end = LUSTRE_EOF;
10634         unsigned long long length = 0;
10635         unsigned long long size_units;
10636         unsigned long long flags = 0;
10637         int c, fd, rc = 0;
10638         const char *path;
10639         int mode = 0;
10640
10641         optind = 0;
10642         while ((c = getopt_long(argc, argv, "a:be:hl:m:s:u",
10643                                 long_opts, NULL)) != -1) {
10644                 switch (c) {
10645                 case 'a':
10646                         advice_type = lfs_get_ladvice(optarg);
10647                         if (advice_type == LU_LADVISE_INVALID) {
10648                                 fprintf(stderr,
10649                                         "%s: invalid advice type '%s'\n",
10650                                         progname, optarg);
10651                                 fprintf(stderr, "Valid types:");
10652
10653                                 for (advice_type = 0;
10654                                      advice_type < ARRAY_SIZE(ladvise_names);
10655                                      advice_type++) {
10656                                         if (ladvise_names[advice_type] == NULL)
10657                                                 continue;
10658                                         fprintf(stderr, " %s",
10659                                                 ladvise_names[advice_type]);
10660                                 }
10661                                 fprintf(stderr, "\n");
10662
10663                                 return CMD_HELP;
10664                         }
10665                         break;
10666                 case 'b':
10667                         flags |= LF_ASYNC;
10668                         break;
10669                 case 'u':
10670                         flags |= LF_UNSET;
10671                         break;
10672                 case 'e':
10673                         size_units = 1;
10674                         rc = llapi_parse_size(optarg, &end,
10675                                               &size_units, 0);
10676                         if (rc) {
10677                                 fprintf(stderr, "%s: bad end offset '%s'\n",
10678                                         argv[0], optarg);
10679                                 return CMD_HELP;
10680                         }
10681                         break;
10682                 case 's':
10683                         size_units = 1;
10684                         rc = llapi_parse_size(optarg, &start,
10685                                               &size_units, 0);
10686                         if (rc) {
10687                                 fprintf(stderr,
10688                                         "%s: bad start offset '%s'\n",
10689                                         argv[0], optarg);
10690                                 return CMD_HELP;
10691                         }
10692                         break;
10693                 case 'l':
10694                         size_units = 1;
10695                         rc = llapi_parse_size(optarg, &length,
10696                                               &size_units, 0);
10697                         if (rc) {
10698                                 fprintf(stderr, "%s: bad length '%s'\n",
10699                                         argv[0], optarg);
10700                                 return CMD_HELP;
10701                         }
10702                         break;
10703                 case 'm':
10704                         mode = lfs_get_mode(optarg);
10705                         if (mode < 0) {
10706                                 fprintf(stderr,
10707                                         "%s: bad mode '%s', valid modes are READ or WRITE\n",
10708                                         argv[0], optarg);
10709                                 return CMD_HELP;
10710                         }
10711                         break;
10712                 default:
10713                         fprintf(stderr, "%s: unrecognized option '%s'\n",
10714                                 progname, argv[optind - 1]);
10715                         fallthrough;
10716                 case 'h':
10717                         return CMD_HELP;
10718                 }
10719         }
10720
10721         if (advice_type == LU_LADVISE_INVALID) {
10722                 fprintf(stderr, "%s: please give an advice type\n", argv[0]);
10723                 fprintf(stderr, "Valid types:");
10724                 for (advice_type = 0; advice_type < ARRAY_SIZE(ladvise_names);
10725                      advice_type++) {
10726                         if (ladvise_names[advice_type] == NULL)
10727                                 continue;
10728                         fprintf(stderr, " %s", ladvise_names[advice_type]);
10729                 }
10730                 fprintf(stderr, "\n");
10731                 return CMD_HELP;
10732         }
10733
10734         if (advice_type == LU_LADVISE_LOCKNOEXPAND) {
10735                 fprintf(stderr,
10736                         "%s: Lock no expand advice is a per file descriptor advice, so when called from lfs, it does nothing.\n",
10737                         argv[0]);
10738                 return CMD_HELP;
10739         }
10740
10741         if (argc <= optind) {
10742                 fprintf(stderr, "%s: please give one or more file names\n",
10743                         argv[0]);
10744                 return CMD_HELP;
10745         }
10746
10747         if (end != LUSTRE_EOF && length != 0 && end != start + length) {
10748                 fprintf(stderr, "%s: conflicting arguments of -l and -e\n",
10749                         argv[0]);
10750                 return CMD_HELP;
10751         }
10752
10753         if (end == LUSTRE_EOF && length != 0)
10754                 end = start + length;
10755
10756         if (end <= start) {
10757                 fprintf(stderr, "%s: range [%llu, %llu] is invalid\n",
10758                         argv[0], start, end);
10759                 return CMD_HELP;
10760         }
10761
10762         if (advice_type != LU_LADVISE_LOCKAHEAD && mode != 0) {
10763                 fprintf(stderr, "%s: mode is only valid with lockahead\n",
10764                         argv[0]);
10765                 return CMD_HELP;
10766         }
10767
10768         if (advice_type == LU_LADVISE_LOCKAHEAD && mode == 0) {
10769                 fprintf(stderr, "%s: mode is required with lockahead\n",
10770                         argv[0]);
10771                 return CMD_HELP;
10772         }
10773
10774         while (optind < argc) {
10775                 int rc2;
10776
10777                 path = argv[optind++];
10778
10779                 fd = open(path, O_RDONLY);
10780                 if (fd < 0) {
10781                         rc2 = -errno;
10782                         fprintf(stderr, "%s: cannot open file '%s': %s\n",
10783                                 argv[0], path, strerror(-rc2));
10784                         if (!rc)
10785                                 rc = rc2;
10786                         continue;
10787                 }
10788
10789                 advice.lla_start = start;
10790                 advice.lla_end = end;
10791                 advice.lla_advice = advice_type;
10792                 advice.lla_value1 = 0;
10793                 advice.lla_value2 = 0;
10794                 advice.lla_value3 = 0;
10795                 advice.lla_value4 = 0;
10796                 if (advice_type == LU_LADVISE_LOCKAHEAD) {
10797                         advice.lla_lockahead_mode = mode;
10798                         advice.lla_peradvice_flags = flags;
10799                 }
10800
10801                 rc2 = llapi_ladvise(fd, flags, 1, &advice);
10802                 close(fd);
10803                 if (rc2 < 0) {
10804                         fprintf(stderr,
10805                                 "%s: cannot give advice '%s' to file '%s': %s\n",
10806                                 argv[0], ladvise_names[advice_type],
10807                                 path, strerror(errno));
10808
10809                         if (!rc)
10810                                 rc = rc2;
10811                         continue;
10812                 }
10813         }
10814
10815         return rc;
10816 }
10817
10818 static const char *const heat_names[] = LU_HEAT_NAMES;
10819
10820 static int lfs_heat_get(int argc, char **argv)
10821 {
10822         struct lu_heat *heat;
10823         int rc = 0, rc2;
10824         char *path;
10825         int fd;
10826         int i;
10827
10828         if (argc <= 1)
10829                 return CMD_HELP;
10830
10831         heat = calloc(sizeof(*heat) + sizeof(__u64) * OBD_HEAT_COUNT, 1);
10832         if (!heat) {
10833                 fprintf(stderr, "%s: memory allocation failed\n", argv[0]);
10834                 return -ENOMEM;
10835         }
10836
10837         optind = 1;
10838         while (optind < argc) {
10839                 path = argv[optind++];
10840
10841                 fd = open(path, O_RDONLY);
10842                 if (fd < 0) {
10843                         fprintf(stderr, "%s: cannot open file '%s': %s\n",
10844                                 argv[0], path, strerror(errno));
10845                         rc2 = -errno;
10846                         goto next;
10847                 }
10848
10849                 heat->lh_count = OBD_HEAT_COUNT;
10850                 rc2 = llapi_heat_get(fd, heat);
10851                 close(fd);
10852                 if (rc2 < 0) {
10853                         fprintf(stderr,
10854                                 "%s: cannot get heat of file '%s': %s\n",
10855                                 argv[0], path, strerror(errno));
10856                         goto next;
10857                 }
10858
10859                 printf("flags: %x\n", heat->lh_flags);
10860                 for (i = 0; i < heat->lh_count; i++)
10861                         printf("%s: %llu\n", heat_names[i],
10862                                (unsigned long long)heat->lh_heat[i]);
10863 next:
10864                 if (rc == 0 && rc2 < 0)
10865                         rc = rc2;
10866         }
10867
10868         free(heat);
10869         return rc;
10870 }
10871
10872 static int lfs_heat_set(int argc, char **argv)
10873 {
10874         struct option long_opts[] = {
10875         { .val = 'c',   .name = "clear",        .has_arg = no_argument },
10876         { .val = 'h',   .name = "help",         .has_arg = no_argument },
10877         { .val = 'o',   .name = "off",          .has_arg = no_argument },
10878         { .val = 'O',   .name = "on",           .has_arg = no_argument },
10879         { .name = NULL } };
10880         enum lu_heat_flag flags = 0;
10881         int rc = 0, rc2;
10882         char *path;
10883         int fd;
10884         int c;
10885
10886         if (argc <= 1)
10887                 return CMD_HELP;
10888
10889         optind = 0;
10890         while ((c = getopt_long(argc, argv, "choO", long_opts, NULL)) != -1) {
10891                 switch (c) {
10892                 case 'c':
10893                         flags |= LU_HEAT_FLAG_CLEAR;
10894                         break;
10895                 case 'o':
10896                         flags |= LU_HEAT_FLAG_CLEAR;
10897                         flags |= LU_HEAT_FLAG_OFF;
10898                         break;
10899                 case 'O':
10900                         flags &= ~LU_HEAT_FLAG_OFF;
10901                         break;
10902                 default:
10903                         fprintf(stderr, "%s: unrecognized option '%s'\n",
10904                                 progname, argv[optind - 1]);
10905                         fallthrough;
10906                 case 'h':
10907                         return CMD_HELP;
10908                 }
10909         }
10910
10911         if (argc <= optind) {
10912                 fprintf(stderr, "%s: please give one or more file names\n",
10913                         argv[0]);
10914                 return CMD_HELP;
10915         }
10916
10917         while (optind < argc) {
10918                 path = argv[optind++];
10919
10920                 fd = open(path, O_RDONLY);
10921                 if (fd < 0) {
10922                         fprintf(stderr, "%s: cannot open file '%s': %s\n",
10923                                 argv[0], path, strerror(errno));
10924                         rc2 = -errno;
10925                         goto next;
10926                 }
10927
10928                 rc2 = llapi_heat_set(fd, flags);
10929                 close(fd);
10930                 if (rc2 < 0) {
10931                         fprintf(stderr,
10932                                 "%s: cannot setflags heat of file '%s': %s\n",
10933                                 argv[0], path, strerror(errno));
10934                         goto next;
10935                 }
10936 next:
10937                 if (rc == 0 && rc2 < 0)
10938                         rc = rc2;
10939         }
10940         return rc;
10941 }
10942
10943 /**
10944  * The input string contains a comma delimited list of component ids and
10945  * ranges, for example "1,2-4,7".
10946  */
10947 static int parse_mirror_ids(__u16 *ids, int size, char *arg)
10948 {
10949         bool end_of_loop = false;
10950         char *ptr = NULL;
10951         int nr = 0;
10952         int rc;
10953
10954         if (!arg)
10955                 return -EINVAL;
10956
10957         while (!end_of_loop) {
10958                 int start_index;
10959                 int end_index;
10960                 int i;
10961                 char *endptr = NULL;
10962
10963                 rc = -EINVAL;
10964                 ptr = strchrnul(arg, ',');
10965                 end_of_loop = *ptr == '\0';
10966                 *ptr = '\0';
10967
10968                 start_index = strtol(arg, &endptr, 0);
10969                 if (endptr == arg) /* no data at all */
10970                         break;
10971                 if (*endptr != '-' && *endptr != '\0') /* has invalid data */
10972                         break;
10973                 if (start_index < 0)
10974                         break;
10975
10976                 end_index = start_index;
10977                 if (*endptr == '-') {
10978                         end_index = strtol(endptr + 1, &endptr, 0);
10979                         if (*endptr != '\0')
10980                                 break;
10981                         if (end_index < start_index)
10982                                 break;
10983                 }
10984
10985                 for (i = start_index; i <= end_index && size > 0; i++) {
10986                         int j;
10987
10988                         /* remove duplicate */
10989                         for (j = 0; j < nr; j++) {
10990                                 if (ids[j] == i)
10991                                         break;
10992                         }
10993                         if (j == nr) { /* no duplicate */
10994                                 ids[nr++] = i;
10995                                 --size;
10996                         }
10997                 }
10998
10999                 if (size == 0 && i < end_index)
11000                         break;
11001
11002                 *ptr = ',';
11003                 arg = ++ptr;
11004                 rc = 0;
11005         }
11006         if (!end_of_loop && ptr)
11007                 *ptr = ',';
11008
11009         return rc < 0 ? rc : nr;
11010 }
11011
11012 /**
11013  * struct verify_mirror_id - Mirror id to be verified.
11014  * @mirror_id:   A specified mirror id.
11015  * @is_valid_id: @mirror_id is valid or not in the mirrored file.
11016  */
11017 struct verify_mirror_id {
11018         __u16 mirror_id;
11019         bool is_valid_id;
11020 };
11021
11022 /**
11023  * compare_mirror_ids() - Compare mirror ids.
11024  * @layout: Mirror component list.
11025  * @cbdata: Callback data in verify_mirror_id structure.
11026  *
11027  * This is a callback function called by llapi_layout_comp_iterate()
11028  * to compare the specified mirror id with the one in the current
11029  * component of @layout. If they are the same, then the specified
11030  * mirror id is valid.
11031  *
11032  * Return: a negative error code on failure or
11033  *         LLAPI_LAYOUT_ITER_CONT: Proceed iteration
11034  *         LLAPI_LAYOUT_ITER_STOP: Stop iteration
11035  */
11036 static inline
11037 int compare_mirror_ids(struct llapi_layout *layout, void *cbdata)
11038 {
11039         struct verify_mirror_id *mirror_id_cbdata =
11040                                  (struct verify_mirror_id *)cbdata;
11041         uint32_t mirror_id;
11042         int rc = 0;
11043
11044         rc = llapi_layout_mirror_id_get(layout, &mirror_id);
11045         if (rc < 0) {
11046                 rc = -errno;
11047                 fprintf(stderr,
11048                         "%s: llapi_layout_mirror_id_get failed: %s.\n",
11049                         progname, strerror(errno));
11050                 return rc;
11051         }
11052
11053         if (mirror_id_cbdata->mirror_id == mirror_id) {
11054                 mirror_id_cbdata->is_valid_id = true;
11055                 return LLAPI_LAYOUT_ITER_STOP;
11056         }
11057
11058         return LLAPI_LAYOUT_ITER_CONT;
11059 }
11060
11061 /**
11062  * verify_mirror_ids() - Verify specified mirror ids.
11063  * @fname:      Mirrored file name.
11064  * @mirror_ids: Specified mirror ids to be verified.
11065  * @ids_nr:     Number of specified mirror ids.
11066  *
11067  * This function verifies that specified @mirror_ids are valid
11068  * in the mirrored file @fname.
11069  *
11070  * Return: 0 on success or a negative error code on failure.
11071  */
11072 static inline
11073 int verify_mirror_ids(const char *fname, __u16 *mirror_ids, int ids_nr)
11074 {
11075         struct llapi_layout *layout = NULL;
11076         struct verify_mirror_id mirror_id_cbdata = { 0 };
11077         struct stat stbuf;
11078         uint32_t flr_state;
11079         int i;
11080         int fd;
11081         int rc = 0;
11082         int rc2 = 0;
11083
11084         if (ids_nr <= 0)
11085                 return -EINVAL;
11086
11087         if (stat(fname, &stbuf) < 0) {
11088                 fprintf(stderr, "%s: cannot stat file '%s': %s.\n",
11089                         progname, fname, strerror(errno));
11090                 rc = -errno;
11091                 goto error;
11092         }
11093
11094         if (!S_ISREG(stbuf.st_mode)) {
11095                 fprintf(stderr, "%s: '%s' is not a regular file.\n",
11096                         progname, fname);
11097                 rc = -EINVAL;
11098                 goto error;
11099         }
11100
11101         fd = open(fname, O_DIRECT | O_RDONLY);
11102         if (fd < 0) {
11103                 fprintf(stderr, "%s: cannot open '%s': %s.\n",
11104                         progname, fname, strerror(errno));
11105                 rc = -errno;
11106                 goto error;
11107         }
11108
11109         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
11110         if (rc < 0) {
11111                 fprintf(stderr, "%s: '%s' llapi_lease_acquire failed: %s.\n",
11112                         progname, fname, strerror(errno));
11113                 goto close_fd;
11114         }
11115
11116         layout = llapi_layout_get_by_fd(fd, 0);
11117         if (!layout) {
11118                 fprintf(stderr, "%s: '%s' llapi_layout_get_by_fd failed: %s.\n",
11119                         progname, fname, strerror(errno));
11120                 rc = -errno;
11121                 llapi_lease_release(fd);
11122                 goto close_fd;
11123         }
11124
11125         rc = llapi_layout_flags_get(layout, &flr_state);
11126         if (rc < 0) {
11127                 fprintf(stderr, "%s: '%s' llapi_layout_flags_get failed: %s.\n",
11128                         progname, fname, strerror(errno));
11129                 rc = -errno;
11130                 goto free_layout;
11131         }
11132
11133         flr_state &= LCM_FL_FLR_MASK;
11134         switch (flr_state) {
11135         case LCM_FL_NONE:
11136                 rc = -EINVAL;
11137                 fprintf(stderr, "%s: '%s' file state error: %s.\n",
11138                         progname, fname, llapi_layout_flags_string(flr_state));
11139                 goto free_layout;
11140         default:
11141                 break;
11142         }
11143
11144         rc2 = 0;
11145         for (i = 0; i < ids_nr; i++) {
11146                 mirror_id_cbdata.mirror_id = mirror_ids[i];
11147                 mirror_id_cbdata.is_valid_id = false;
11148
11149                 rc = llapi_layout_comp_iterate(layout, compare_mirror_ids,
11150                                                &mirror_id_cbdata);
11151                 if (rc < 0) {
11152                         rc = -errno;
11153                         fprintf(stderr,
11154                                 "%s: '%s' failed to verify mirror id: %u.\n",
11155                                 progname, fname, mirror_ids[i]);
11156                         goto free_layout;
11157                 }
11158
11159                 if (!mirror_id_cbdata.is_valid_id) {
11160                         rc2 = -EINVAL;
11161                         fprintf(stderr,
11162                                 "%s: '%s' invalid specified mirror id: %u.\n",
11163                                 progname, fname, mirror_ids[i]);
11164                 }
11165         }
11166         rc = rc2;
11167
11168 free_layout:
11169         llapi_layout_free(layout);
11170         llapi_lease_release(fd);
11171 close_fd:
11172         close(fd);
11173 error:
11174         return rc;
11175 }
11176
11177 static inline
11178 int lfs_mirror_resync_file(const char *fname, struct ll_ioc_lease *ioc,
11179                            __u16 *mirror_ids, int ids_nr)
11180 {
11181         struct llapi_resync_comp comp_array[1024] = { { 0 } };
11182         struct llapi_layout *layout;
11183         struct stat stbuf;
11184         uint32_t flr_state;
11185         uint64_t start;
11186         uint64_t end;
11187         int comp_size = 0;
11188         int idx;
11189         int fd;
11190         int rc;
11191         int rc2;
11192
11193         if (stat(fname, &stbuf) < 0) {
11194                 fprintf(stderr, "%s: cannot stat file '%s': %s.\n",
11195                         progname, fname, strerror(errno));
11196                 rc = -errno;
11197                 goto error;
11198         }
11199         if (!S_ISREG(stbuf.st_mode)) {
11200                 fprintf(stderr, "%s: '%s' is not a regular file.\n",
11201                         progname, fname);
11202                 rc = -EINVAL;
11203                 goto error;
11204         }
11205
11206         /* Allow mirror resync even without the key on encrypted files */
11207         fd = open(fname, O_DIRECT | O_RDWR | O_FILE_ENC);
11208         if (fd < 0) {
11209                 fprintf(stderr, "%s: cannot open '%s': %s.\n",
11210                         progname, fname, strerror(errno));
11211                 rc = -errno;
11212                 goto error;
11213         }
11214
11215         layout = llapi_layout_get_by_fd(fd, 0);
11216         if (!layout) {
11217                 fprintf(stderr, "%s: '%s' llapi_layout_get_by_fd failed: %s.\n",
11218                         progname, fname, strerror(errno));
11219                 rc = -errno;
11220                 goto close_fd;
11221         }
11222
11223         rc = llapi_layout_flags_get(layout, &flr_state);
11224         if (rc) {
11225                 fprintf(stderr, "%s: '%s' llapi_layout_flags_get failed: %s.\n",
11226                         progname, fname, strerror(errno));
11227                 rc = -errno;
11228                 goto free_layout;
11229         }
11230
11231         flr_state &= LCM_FL_FLR_MASK;
11232         if (flr_state == LCM_FL_NONE) {
11233                 rc = -EINVAL;
11234                 fprintf(stderr, "%s: '%s' is not a FLR file.\n",
11235                         progname, fname);
11236                 goto free_layout;
11237         }
11238
11239         /* get stale component info */
11240         comp_size = llapi_mirror_find_stale(layout, comp_array,
11241                                             ARRAY_SIZE(comp_array),
11242                                             mirror_ids, ids_nr);
11243         if (comp_size <= 0) {
11244                 rc = comp_size;
11245                 goto free_layout;
11246         }
11247
11248         ioc->lil_mode = LL_LEASE_WRLCK;
11249         ioc->lil_flags = LL_LEASE_RESYNC;
11250         rc = llapi_lease_set(fd, ioc);
11251         if (rc < 0) {
11252                 if (rc == -EALREADY)
11253                         rc = 0;
11254                 else
11255                         fprintf(stderr,
11256                             "%s: '%s' llapi_lease_get_ext resync failed: %s.\n",
11257                                 progname, fname, strerror(-rc));
11258                 goto free_layout;
11259         }
11260
11261         /* get the read range [start, end) */
11262         start = comp_array[0].lrc_start;
11263         end = comp_array[0].lrc_end;
11264         for (idx = 1; idx < comp_size; idx++) {
11265                 if (comp_array[idx].lrc_start < start)
11266                         start = comp_array[idx].lrc_start;
11267                 if (end < comp_array[idx].lrc_end)
11268                         end = comp_array[idx].lrc_end;
11269         }
11270
11271         rc = llapi_lease_check(fd);
11272         if (rc != LL_LEASE_WRLCK) {
11273                 fprintf(stderr, "%s: '%s' lost lease lock.\n",
11274                         progname, fname);
11275                 goto free_layout;
11276         }
11277
11278         rc = llapi_mirror_resync_many(fd, layout, comp_array, comp_size,
11279                                       start, end);
11280         if (rc < 0)
11281                 fprintf(stderr, "%s: '%s' llapi_mirror_resync_many: %s.\n",
11282                         progname, fname, strerror(-rc));
11283
11284         rc = migrate_set_timestamps(fd, &stbuf);
11285         if (rc < 0) {
11286                 fprintf(stderr, "%s: '%s' cannot set timestamps: %s\n",
11287                         progname, fname, strerror(-rc));
11288                 goto free_layout;
11289         }
11290
11291         /* need to do the lease unlock even resync fails */
11292         ioc->lil_mode = LL_LEASE_UNLCK;
11293         ioc->lil_flags = LL_LEASE_RESYNC_DONE;
11294         ioc->lil_count = 0;
11295         for (idx = 0; idx < comp_size; idx++) {
11296                 if (comp_array[idx].lrc_synced) {
11297                         ioc->lil_ids[ioc->lil_count] = comp_array[idx].lrc_id;
11298                         ioc->lil_count++;
11299                 }
11300         }
11301
11302         rc2 = llapi_lease_set(fd, ioc);
11303         /**
11304          * llapi_lease_set returns lease mode when it request to unlock
11305          * the lease lock.
11306          */
11307         if (rc2 <= 0) {
11308                 /* rc2 == 0 means lost lease lock */
11309                 if (rc2 == 0 && rc == 0)
11310                         rc = -EBUSY;
11311                 else
11312                         rc = rc2;
11313                 fprintf(stderr, "%s: resync file '%s' failed: %s.\n",
11314                         progname, fname,
11315                         rc2 == 0 ? "lost lease lock" : strerror(-rc2));
11316
11317                 llapi_lease_release(fd);
11318                 goto free_layout;
11319         }
11320
11321 free_layout:
11322         llapi_layout_free(layout);
11323 close_fd:
11324         close(fd);
11325 error:
11326         return rc;
11327 }
11328
11329 static inline int lfs_mirror_resync(int argc, char **argv)
11330 {
11331         struct option long_opts[] = {
11332         { .val = 'h',   .name = "help",         .has_arg = no_argument },
11333         { .val = 'o',   .name = "only",         .has_arg = required_argument },
11334         { .name = NULL } };
11335         struct ll_ioc_lease *ioc = NULL;
11336         __u16 mirror_ids[128] = { 0 };
11337         int ids_nr = 0;
11338         int c;
11339         int rc = 0;
11340
11341         while ((c = getopt_long(argc, argv, "ho:", long_opts, NULL)) >= 0) {
11342                 switch (c) {
11343                 case 'o':
11344                         rc = parse_mirror_ids(mirror_ids,
11345                                         sizeof(mirror_ids) / sizeof(__u16),
11346                                         optarg);
11347                         if (rc < 0) {
11348                                 fprintf(stderr,
11349                                         "%s: bad mirror ids '%s'.\n",
11350                                         argv[0], optarg);
11351                                 goto error;
11352                         }
11353                         ids_nr = rc;
11354                         break;
11355                 default:
11356                         fprintf(stderr, "%s: unrecognized option '%s'\n",
11357                                 progname, argv[optind - 1]);
11358                         fallthrough;
11359                 case 'h':
11360                         rc = CMD_HELP;
11361                         goto error;
11362                 }
11363         }
11364
11365         if (argc == optind) {
11366                 fprintf(stderr, "%s: no file name given.\n", argv[0]);
11367                 rc = CMD_HELP;
11368                 goto error;
11369         }
11370
11371         if (ids_nr > 0 && argc > optind + 1) {
11372                 fprintf(stderr,
11373                     "%s: option '--only' cannot be used upon multiple files.\n",
11374                         argv[0]);
11375                 rc = CMD_HELP;
11376                 goto error;
11377         }
11378
11379         if (ids_nr > 0) {
11380                 rc = verify_mirror_ids(argv[optind], mirror_ids, ids_nr);
11381                 if (rc < 0)
11382                         goto error;
11383         }
11384
11385         /* set the lease on the file */
11386         ioc = calloc(sizeof(*ioc) + sizeof(__u32) * 4096, 1);
11387         if (!ioc) {
11388                 fprintf(stderr, "%s: cannot alloc id array for ioc: %s.\n",
11389                         argv[0], strerror(errno));
11390                 rc = -errno;
11391                 goto error;
11392         }
11393
11394         for (; optind < argc; optind++) {
11395                 rc = lfs_mirror_resync_file(argv[optind], ioc,
11396                                             mirror_ids, ids_nr);
11397                 /* ignore previous file's error, continue with next file */
11398
11399                 /* reset ioc */
11400                 memset(ioc, 0, sizeof(*ioc) + sizeof(__u32) * 4096);
11401         }
11402
11403         free(ioc);
11404 error:
11405         return rc;
11406 }
11407
11408 static inline int verify_mirror_id_by_fd(int fd, __u16 mirror_id)
11409 {
11410         struct llapi_layout *layout;
11411         int rc;
11412
11413         layout = llapi_layout_get_by_fd(fd, 0);
11414         if (!layout) {
11415                 fprintf(stderr, "could not get layout.\n");
11416                 return  -EINVAL;
11417         }
11418
11419         rc = llapi_layout_comp_iterate(layout, find_mirror_id, &mirror_id);
11420         if (rc < 0) {
11421                 fprintf(stderr, "failed to iterate layout\n");
11422                 llapi_layout_free(layout);
11423
11424                 return rc;
11425         } else if (rc == LLAPI_LAYOUT_ITER_CONT) {
11426                 fprintf(stderr, "does not find mirror with ID %u\n", mirror_id);
11427                 llapi_layout_free(layout);
11428
11429                 return -EINVAL;
11430         }
11431         llapi_layout_free(layout);
11432
11433         return 0;
11434 }
11435
11436 /**
11437  * Check whether two files are the same file
11438  * \retval      0  same file
11439  * \retval      1  not the same file
11440  * \retval      <0 error code
11441  */
11442 static inline int check_same_file(int fd, const char *f2)
11443 {
11444         struct stat stbuf1;
11445         struct stat stbuf2;
11446
11447         if (fstat(fd, &stbuf1) < 0)
11448                 return -errno;
11449
11450         if (stat(f2, &stbuf2) < 0)
11451                 return 1;
11452
11453         if (stbuf1.st_rdev == stbuf2.st_rdev &&
11454             stbuf1.st_ino == stbuf2.st_ino)
11455                 return 0;
11456
11457         return 1;
11458 }
11459
11460 static inline int lfs_mirror_read(int argc, char **argv)
11461 {
11462         int rc = CMD_HELP;
11463         __u16 mirror_id = 0;
11464         const char *outfile = NULL;
11465         char *fname;
11466         int fd = 0;
11467         int outfd;
11468         int c;
11469         void *buf;
11470         const size_t buflen = 4 << 20;
11471         off_t pos;
11472         struct option long_opts[] = {
11473         { .val = 'h',   .name = "help",         .has_arg = no_argument },
11474         { .val = 'N',   .name = "mirror-id",    .has_arg = required_argument },
11475         { .val = 'o',   .name = "outfile",      .has_arg = required_argument },
11476         { .name = NULL } };
11477
11478         while ((c = getopt_long(argc, argv, "hN:o:", long_opts, NULL)) >= 0) {
11479                 char *end;
11480
11481                 switch (c) {
11482                 case 'N': {
11483                         unsigned long int id;
11484
11485                         errno = 0;
11486                         id = strtoul(optarg, &end, 0);
11487                         if (errno != 0 || *end != '\0' || id == 0 ||
11488                             id > UINT16_MAX) {
11489                                 fprintf(stderr,
11490                                         "%s %s: invalid mirror ID '%s'\n",
11491                                         progname, argv[0], optarg);
11492                                 return rc;
11493                         }
11494
11495                         mirror_id = (__u16)id;
11496                         break;
11497                 }
11498                 case 'o':
11499                         outfile = optarg;
11500                         break;
11501                 default:
11502                         fprintf(stderr, "%s: unrecognized option '%s'\n",
11503                                 progname, argv[optind - 1]);
11504                         fallthrough;
11505                 case 'h':
11506                         return CMD_HELP;
11507                 }
11508         }
11509
11510         if (argc == optind) {
11511                 fprintf(stderr, "%s %s: no mirrored file provided\n",
11512                         progname, argv[0]);
11513                 return rc;
11514         } else if (argc > optind + 1) {
11515                 fprintf(stderr, "%s %s: too many files\n", progname, argv[0]);
11516                 return rc;
11517         }
11518
11519         if (mirror_id == 0) {
11520                 fprintf(stderr, "%s %s: no valid mirror ID is provided\n",
11521                         progname, argv[0]);
11522                 return rc;
11523         }
11524
11525         /* open mirror file */
11526         fname = argv[optind];
11527         fd = open(fname, O_DIRECT | O_RDONLY);
11528         if (fd < 0) {
11529                 fprintf(stderr, "%s %s: cannot open '%s': %s\n",
11530                         progname, argv[0], fname, strerror(errno));
11531                 return rc;
11532         }
11533
11534         /* verify mirror id */
11535         rc = verify_mirror_id_by_fd(fd, mirror_id);
11536         if (rc) {
11537                 fprintf(stderr,
11538                         "%s %s: cannot find mirror with ID %u in '%s'\n",
11539                         progname, argv[0], mirror_id, fname);
11540                 goto close_fd;
11541         }
11542
11543         /* open output file - O_EXCL ensures output is not the same as input */
11544         if (outfile) {
11545                 outfd = open(outfile, O_EXCL | O_WRONLY | O_CREAT, 0644);
11546                 if (outfd < 0) {
11547                         fprintf(stderr, "%s %s: cannot create file '%s': %s\n",
11548                                 progname, argv[0], outfile, strerror(errno));
11549                         rc = -errno;
11550                         goto close_fd;
11551                 }
11552         } else {
11553                 outfd = STDOUT_FILENO;
11554         }
11555
11556         /* allocate buffer */
11557         rc = posix_memalign(&buf, sysconf(_SC_PAGESIZE), buflen);
11558         if (rc) {
11559                 fprintf(stderr, "%s %s: posix_memalign returns %d\n",
11560                                 progname, argv[0], rc);
11561                 goto close_outfd;
11562         }
11563
11564         pos = 0;
11565         while (1) {
11566                 ssize_t bytes_read;
11567                 ssize_t written = 0;
11568
11569                 bytes_read = llapi_mirror_read(fd, mirror_id, buf, buflen, pos);
11570                 if (bytes_read < 0) {
11571                         rc = bytes_read;
11572                         fprintf(stderr,
11573                                 "%s %s: fail to read data from mirror %u: %s\n",
11574                                 progname, argv[0], mirror_id, strerror(-rc));
11575                         goto free_buf;
11576                 }
11577
11578                 /* EOF reached */
11579                 if (bytes_read == 0)
11580                         break;
11581
11582                 while (written < bytes_read) {
11583                         ssize_t written2;
11584
11585                         written2 = write(outfd, buf + written,
11586                                          bytes_read - written);
11587                         if (written2 < 0) {
11588                                 fprintf(stderr,
11589                                         "%s %s: fail to write %s: %s\n",
11590                                         progname, argv[0], outfile ? : "STDOUT",
11591                                         strerror(errno));
11592                                 rc = -errno;
11593                                 goto free_buf;
11594                         }
11595                         written += written2;
11596                 }
11597
11598                 if (written != bytes_read) {
11599                         fprintf(stderr,
11600                 "%s %s: written %ld bytes does not match with %ld read.\n",
11601                                 progname, argv[0], written, bytes_read);
11602                         rc = -EIO;
11603                         goto free_buf;
11604                 }
11605
11606                 pos += bytes_read;
11607         }
11608
11609         fsync(outfd);
11610         rc = 0;
11611
11612 free_buf:
11613         free(buf);
11614 close_outfd:
11615         if (outfile)
11616                 close(outfd);
11617 close_fd:
11618         close(fd);
11619
11620         return rc;
11621 }
11622
11623 static inline int lfs_mirror_write(int argc, char **argv)
11624 {
11625         int rc = CMD_HELP;
11626         __u16 mirror_id = 0;
11627         const char *inputfile = NULL;
11628         char *fname;
11629         int fd = 0;
11630         int inputfd;
11631         int c;
11632         void *buf;
11633         const size_t buflen = 4 << 20;
11634         off_t pos;
11635         size_t page_size = sysconf(_SC_PAGESIZE);
11636         struct ll_ioc_lease_id ioc;
11637         struct option long_opts[] = {
11638         { .val = 'h',   .name = "help",         .has_arg = no_argument },
11639         { .val = 'i',   .name = "inputfile",    .has_arg = required_argument },
11640         { .val = 'N',   .name = "mirror-id",    .has_arg = required_argument },
11641         { .name = NULL } };
11642
11643         while ((c = getopt_long(argc, argv, "hi:N:", long_opts, NULL)) >= 0) {
11644                 char *end;
11645
11646                 switch (c) {
11647                 case 'N': {
11648                         unsigned long int id;
11649
11650                         errno = 0;
11651                         id = strtoul(optarg, &end, 0);
11652                         if (errno != 0 || *end != '\0' || id == 0 ||
11653                             id > UINT16_MAX) {
11654                                 fprintf(stderr,
11655                                         "%s %s: invalid mirror ID '%s'\n",
11656                                         progname, argv[0], optarg);
11657                                 return rc;
11658                         }
11659
11660                         mirror_id = (__u16)id;
11661                         break;
11662                 }
11663                 case 'i':
11664                         inputfile = optarg;
11665                         break;
11666                 default:
11667                         fprintf(stderr, "%s: unrecognized option '%s'\n",
11668                                 progname, argv[optind - 1]);
11669                         fallthrough;
11670                 case 'h':
11671                         return CMD_HELP;
11672                 }
11673         }
11674
11675         if (argc == optind) {
11676                 fprintf(stderr, "%s %s: no mirrored file provided\n",
11677                         progname, argv[0]);
11678                 return rc;
11679         } else if (argc > optind + 1) {
11680                 fprintf(stderr, "%s %s: too many files\n", progname, argv[0]);
11681                 return rc;
11682         }
11683
11684         if (mirror_id == 0) {
11685                 fprintf(stderr, "%s %s: no valid mirror ID is provided\n",
11686                         progname, argv[0]);
11687                 return rc;
11688         }
11689
11690         /* open mirror file */
11691         fname = argv[optind];
11692         fd = open(fname, O_DIRECT | O_WRONLY);
11693         if (fd < 0) {
11694                 fprintf(stderr, "%s %s: cannot open '%s': %s\n",
11695                         progname, argv[0], fname, strerror(errno));
11696                 return rc;
11697         }
11698
11699         /* verify mirror id */
11700         rc = verify_mirror_id_by_fd(fd, mirror_id);
11701         if (rc) {
11702                 fprintf(stderr,
11703                         "%s %s: cannot find mirror with ID %u in '%s'\n",
11704                         progname, argv[0], mirror_id, fname);
11705                 goto close_fd;
11706         }
11707
11708         /* open input file */
11709         if (inputfile) {
11710                 rc = check_same_file(fd, inputfile);
11711                 if (rc == 0) {
11712                         fprintf(stderr,
11713                         "%s %s: input file cannot be the mirrored file '%s'\n",
11714                                 progname, argv[0], fname);
11715                         goto close_fd;
11716                 }
11717                 if (rc < 0)
11718                         goto close_fd;
11719
11720                 inputfd = open(inputfile, O_RDONLY, 0644);
11721                 if (inputfd < 0) {
11722                         fprintf(stderr, "%s %s: cannot open file '%s': %s\n",
11723                                 progname, argv[0], inputfile, strerror(errno));
11724                         rc = -errno;
11725                         goto close_fd;
11726                 }
11727         } else {
11728                 inputfd = STDIN_FILENO;
11729         }
11730
11731         /* allocate buffer */
11732         rc = posix_memalign(&buf, page_size, buflen);
11733         if (rc) {
11734                 fprintf(stderr, "%s %s: posix_memalign returns %d\n",
11735                         progname, argv[0], rc);
11736                 goto close_inputfd;
11737         }
11738
11739         /* prepare target mirror components instantiation */
11740         ioc.lil_mode = LL_LEASE_WRLCK;
11741         ioc.lil_flags = LL_LEASE_RESYNC;
11742         ioc.lil_mirror_id = mirror_id;
11743         rc = llapi_lease_set(fd, (struct ll_ioc_lease *)&ioc);
11744         if (rc < 0) {
11745                 fprintf(stderr,
11746                         "%s %s: '%s' llapi_lease_get_ext failed: %s\n",
11747                         progname, argv[0], fname, strerror(errno));
11748                 goto free_buf;
11749         }
11750
11751         pos = 0;
11752         while (1) {
11753                 ssize_t bytes_read;
11754                 ssize_t written;
11755                 size_t to_write;
11756
11757                 rc = llapi_lease_check(fd);
11758                 if (rc != LL_LEASE_WRLCK) {
11759                         fprintf(stderr, "%s %s: '%s' lost lease lock\n",
11760                                 progname, argv[0], fname);
11761                         goto free_buf;
11762                 }
11763
11764                 bytes_read = read(inputfd, buf, buflen);
11765                 if (bytes_read < 0) {
11766                         rc = bytes_read;
11767                         fprintf(stderr,
11768                                 "%s %s: fail to read data from '%s': %s\n",
11769                                 progname, argv[0], inputfile ? : "STDIN",
11770                                 strerror(errno));
11771                         rc = -errno;
11772                         goto free_buf;
11773                 }
11774
11775                 /* EOF reached */
11776                 if (bytes_read == 0)
11777                         break;
11778
11779                 /* round up to page align to make direct IO happy. */
11780                 to_write = (bytes_read + page_size - 1) & ~(page_size - 1);
11781
11782                 written = llapi_mirror_write(fd, mirror_id, buf, to_write,
11783                                              pos);
11784                 if (written < 0) {
11785                         rc = written;
11786                         fprintf(stderr,
11787                               "%s %s: fail to write to mirror %u: %s\n",
11788                                 progname, argv[0], mirror_id,
11789                                 strerror(-rc));
11790                         goto free_buf;
11791                 }
11792
11793                 pos += bytes_read;
11794         }
11795
11796         if (pos & (page_size - 1)) {
11797                 rc = llapi_mirror_truncate(fd, mirror_id, pos);
11798                 if (rc < 0)
11799                         goto free_buf;
11800         }
11801
11802         ioc.lil_mode = LL_LEASE_UNLCK;
11803         ioc.lil_flags = LL_LEASE_RESYNC_DONE;
11804         ioc.lil_count = 0;
11805         rc = llapi_lease_set(fd, (struct ll_ioc_lease *)&ioc);
11806         if (rc <= 0) {
11807                 if (rc == 0)
11808                         rc = -EBUSY;
11809                 fprintf(stderr,
11810                         "%s %s: release lease lock of '%s' failed: %s\n",
11811                         progname, argv[0], fname, strerror(-rc));
11812                 goto free_buf;
11813         }
11814
11815         rc = 0;
11816
11817 free_buf:
11818         free(buf);
11819 close_inputfd:
11820         if (inputfile)
11821                 close(inputfd);
11822 close_fd:
11823         close(fd);
11824
11825         return rc;
11826 }
11827
11828 static inline int get_other_mirror_ids(int fd, __u16 *ids, __u16 exclude_id)
11829 {
11830         struct llapi_layout *layout;
11831         struct collect_ids_data cid = { .cid_ids = ids,
11832                                         .cid_count = 0,
11833                                         .cid_exclude = exclude_id, };
11834         int rc;
11835
11836         layout = llapi_layout_get_by_fd(fd, 0);
11837         if (!layout) {
11838                 fprintf(stderr, "could not get layout\n");
11839                 return -EINVAL;
11840         }
11841
11842         rc = llapi_layout_comp_iterate(layout, collect_mirror_id, &cid);
11843         if (rc < 0) {
11844                 fprintf(stderr, "failed to iterate layout\n");
11845                 llapi_layout_free(layout);
11846
11847                 return rc;
11848         }
11849         llapi_layout_free(layout);
11850
11851         return cid.cid_count;
11852 }
11853
11854 #ifndef MIRROR_ID_NEG
11855 #define MIRROR_ID_NEG         0x8000
11856 #endif
11857
11858 static inline int lfs_mirror_copy(int argc, char **argv)
11859 {
11860         int rc = CMD_HELP;
11861         __u16 read_mirror_id = 0;
11862         __u16 ids[128] = { 0 };
11863         int count = 0;
11864         struct llapi_layout *layout = NULL;
11865         struct llapi_resync_comp comp_array[1024] = { { 0 } };
11866         int comp_size = 0;
11867         char *fname;
11868         int fd = 0;
11869         int c;
11870         int i;
11871         ssize_t copied;
11872         struct ll_ioc_lease *ioc = NULL;
11873         struct ll_ioc_lease_id *resync_ioc;
11874         struct option long_opts[] = {
11875         { .val = 'h',   .name = "help",         .has_arg = no_argument },
11876         { .val = 'i',   .name = "read-mirror",  .has_arg = required_argument },
11877         { .val = 'o',   .name = "write-mirror", .has_arg = required_argument },
11878         { .name = NULL } };
11879         char cmd[PATH_MAX];
11880
11881         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
11882         progname = cmd;
11883         while ((c = getopt_long(argc, argv, "hi:o:", long_opts, NULL)) >= 0) {
11884                 char *end;
11885
11886                 switch (c) {
11887                 case 'i': {
11888                         unsigned long int id;
11889
11890                         errno = 0;
11891                         id = strtoul(optarg, &end, 0);
11892                         if (errno != 0 || *end != '\0' || id == 0 ||
11893                             id > UINT16_MAX) {
11894                                 fprintf(stderr,
11895                                         "%s: invalid read mirror ID '%s'\n",
11896                                         progname, optarg);
11897                                 return rc;
11898                         }
11899
11900                         read_mirror_id = (__u16)id;
11901                         break;
11902                 }
11903                 case 'o':
11904                         if (!strcmp(optarg, "-1")) {
11905                                 /* specify all other mirrors */
11906                                 ids[0] = (__u16)-1;
11907                                 count = 1;
11908                         } else {
11909                                 count = parse_mirror_ids((__u16 *)ids,
11910                                                          ARRAY_SIZE(ids),
11911                                                          optarg);
11912                                 if (count < 0)
11913                                         return rc;
11914                         }
11915                         break;
11916                 default:
11917                         fprintf(stderr, "%s: unrecognized option '%s'\n",
11918                                 progname, argv[optind - 1]);
11919                         fallthrough;
11920                 case 'h':
11921                         return CMD_HELP;
11922                 }
11923         }
11924
11925         if (argc == optind) {
11926                 fprintf(stderr, "%s %s: no mirrored file provided\n",
11927                         progname, argv[0]);
11928                 return rc;
11929         } else if (argc > optind + 1) {
11930                 fprintf(stderr, "%s %s: too many files\n", progname, argv[0]);
11931                 return rc;
11932         }
11933
11934         if (read_mirror_id == 0) {
11935                 fprintf(stderr,
11936                         "%s %s: no valid read mirror ID %d is provided\n",
11937                         progname, argv[0], read_mirror_id);
11938                 return rc;
11939         }
11940
11941         if (count == 0) {
11942                 fprintf(stderr,
11943                         "%s %s: no write mirror ID is provided\n",
11944                         progname, argv[0]);
11945                 return rc;
11946         }
11947
11948         for (i = 0; i < count; i++) {
11949                 if (read_mirror_id == ids[i]) {
11950                         fprintf(stderr,
11951                         "%s %s: read and write mirror ID cannot be the same\n",
11952                                 progname, argv[0]);
11953                         return rc;
11954                 }
11955         }
11956
11957         /* open mirror file */
11958         fname = argv[optind];
11959
11960         fd = open(fname, O_DIRECT | O_RDWR);
11961         if (fd < 0) {
11962                 fprintf(stderr, "%s %s: cannot open '%s': %s\n",
11963                         progname, argv[0], fname, strerror(errno));
11964                 return rc;
11965         }
11966
11967         /* write to all other mirrors */
11968         if (ids[0] == (__u16)-1) {
11969                 count = get_other_mirror_ids(fd, ids, read_mirror_id);
11970                 if (count <= 0) {
11971                         rc = count;
11972                         fprintf(stderr,
11973                         "%s %s: failed to get other mirror ids in '%s': %d\n",
11974                                 progname, argv[0], fname, rc);
11975                         goto close_fd;
11976                 }
11977         }
11978
11979         /* verify mirror id */
11980         rc = verify_mirror_id_by_fd(fd, read_mirror_id);
11981         if (rc) {
11982                 fprintf(stderr,
11983                         "%s %s: cannot find mirror with ID %u in '%s'\n",
11984                         progname, argv[0], read_mirror_id, fname);
11985                 goto close_fd;
11986         }
11987
11988         for (i = 0; i < count; i++) {
11989                 rc = verify_mirror_id_by_fd(fd, ids[i]);
11990                 if (rc) {
11991                         fprintf(stderr,
11992                         "%s %s: cannot find mirror with ID %u in '%s'\n",
11993                                 progname, argv[0], ids[i], fname);
11994                         goto close_fd;
11995                 }
11996         }
11997
11998         ioc = calloc(sizeof(*ioc) + sizeof(__u32) * 4096, 1);
11999         if (!ioc) {
12000                 fprintf(stderr,
12001                         "%s %s: cannot alloc comp id array for ioc: %s\n",
12002                         progname, argv[0], strerror(errno));
12003                 rc = -errno;
12004                 goto close_fd;
12005         }
12006
12007         /* get stale component info */
12008         layout = llapi_layout_get_by_fd(fd, 0);
12009         if (!layout) {
12010                 fprintf(stderr, "%s %s: failed to get layout of '%s': %s\n",
12011                         progname, argv[0], fname, strerror(errno));
12012                 rc = -errno;
12013                 goto free_ioc;
12014         }
12015         comp_size = llapi_mirror_find_stale(layout, comp_array,
12016                                             ARRAY_SIZE(comp_array),
12017                                             ids, count);
12018         llapi_layout_free(layout);
12019         if (comp_size < 0) {
12020                 rc = comp_size;
12021                 goto free_ioc;
12022         }
12023
12024         /* prepare target mirror components instantiation */
12025         resync_ioc = (struct ll_ioc_lease_id *)ioc;
12026         resync_ioc->lil_mode = LL_LEASE_WRLCK;
12027         resync_ioc->lil_flags = LL_LEASE_RESYNC;
12028         if (count == 1)
12029                 resync_ioc->lil_mirror_id = ids[0];
12030         else
12031                 resync_ioc->lil_mirror_id = read_mirror_id | MIRROR_ID_NEG;
12032         rc = llapi_lease_set(fd, ioc);
12033         if (rc < 0) {
12034                 fprintf(stderr,
12035                         "%s %s: '%s' llapi_lease_get_ext failed: %s\n",
12036                         progname, argv[0], fname, strerror(errno));
12037                 goto free_ioc;
12038         }
12039
12040         copied = llapi_mirror_copy_many(fd, read_mirror_id, ids, count);
12041         if (copied < 0) {
12042                 rc = copied;
12043                 fprintf(stderr, "%s %s: copy error: %d\n",
12044                         progname, argv[0], rc);
12045                 goto free_ioc;
12046         }
12047
12048         fprintf(stdout, "mirror copied successfully: ");
12049         for (i = 0; i < copied; i++)
12050                 fprintf(stdout, "%d ", ids[i]);
12051         fprintf(stdout, "\n");
12052
12053         ioc->lil_mode = LL_LEASE_UNLCK;
12054         ioc->lil_flags = LL_LEASE_RESYNC_DONE;
12055         ioc->lil_count = 0;
12056         for (i = 0; i < comp_size; i++) {
12057                 int j;
12058
12059                 for (j = 0; j < copied; j++) {
12060                         if (comp_array[i].lrc_mirror_id != ids[j])
12061                                 continue;
12062
12063                         ioc->lil_ids[ioc->lil_count] = comp_array[i].lrc_id;
12064                         ioc->lil_count++;
12065                 }
12066         }
12067         rc = llapi_lease_set(fd, ioc);
12068         if (rc <= 0) {
12069                 if (rc == 0)
12070                         rc = -EBUSY;
12071                 fprintf(stderr,
12072                         "%s %s: release lease lock of '%s' failed: %s\n",
12073                         progname, argv[0], fname, strerror(errno));
12074                 goto free_ioc;
12075         }
12076
12077         rc = 0;
12078
12079 free_ioc:
12080         free(ioc);
12081 close_fd:
12082         close(fd);
12083
12084         return rc;
12085 }
12086
12087 /**
12088  * struct verify_chunk - Mirror chunk to be verified.
12089  * @chunk:        [start, end) of the chunk.
12090  * @mirror_count: Number of mirror ids in @mirror_id array.
12091  * @mirror_id:    Array of valid mirror ids that cover the chunk.
12092  */
12093 struct verify_chunk {
12094         struct lu_extent chunk;
12095         unsigned int mirror_count;
12096         __u16 mirror_id[LUSTRE_MIRROR_COUNT_MAX];
12097 };
12098
12099 /**
12100  * print_chunks() - Print chunk information.
12101  * @fname:       Mirrored file name.
12102  * @chunks:      Array of chunks.
12103  * @chunk_count: Number of chunks in @chunks array.
12104  *
12105  * This function prints [start, end) of each chunk in @chunks
12106  * for mirrored file @fname, and also prints the valid mirror ids
12107  * that cover the chunk.
12108  *
12109  * Return: void.
12110  */
12111 static inline
12112 void print_chunks(const char *fname, struct verify_chunk *chunks,
12113                   int chunk_count)
12114 {
12115         int i;
12116         int j;
12117
12118         fprintf(stdout, "Chunks to be verified in %s:\n", fname);
12119         for (i = 0; i < chunk_count; i++) {
12120                 fprintf(stdout, DEXT, PEXT(&chunks[i].chunk));
12121
12122                 if (chunks[i].mirror_count == 0)
12123                         fprintf(stdout, "\t[");
12124                 else {
12125                         fprintf(stdout, "\t[%u", chunks[i].mirror_id[0]);
12126                         for (j = 1; j < chunks[i].mirror_count; j++)
12127                                 fprintf(stdout, ", %u", chunks[i].mirror_id[j]);
12128                 }
12129                 fprintf(stdout, "]\t%u\n", chunks[i].mirror_count);
12130         }
12131         fprintf(stdout, "\n");
12132 }
12133
12134 /**
12135  * print_checksums() - Print CRC-32 checksum values.
12136  * @chunk: A chunk and its corresponding valid mirror ids.
12137  * @crc:   CRC-32 checksum values on the chunk for each valid mirror.
12138  *
12139  * This function prints CRC-32 checksum values on @chunk for
12140  * each valid mirror that covers it.
12141  *
12142  * Return: void.
12143  */
12144 static inline
12145 void print_checksums(struct verify_chunk *chunk, unsigned long *crc,
12146                      unsigned long long pos, unsigned long long len)
12147 {
12148         int i;
12149
12150         fprintf(stdout,
12151                 "CRC-32 checksum value for chunk "DEXT":\n", pos, pos + len);
12152         for (i = 0; i < chunk->mirror_count; i++)
12153                 fprintf(stdout, "Mirror %u:\t%#lx\n",
12154                         chunk->mirror_id[i], crc[i]);
12155         fprintf(stdout, "\n");
12156 }
12157
12158 /**
12159  * filter_mirror_id() - Filter specified mirror ids.
12160  * @chunks:      Array of chunks.
12161  * @chunk_count: Number of chunks in @chunks array.
12162  * @mirror_ids:  Specified mirror ids to be verified.
12163  * @ids_nr:      Number of specified mirror ids.
12164  *
12165  * This function scans valid mirror ids that cover each chunk in @chunks
12166  * and filters specified mirror ids.
12167  *
12168  * Return: void.
12169  */
12170 static inline
12171 void filter_mirror_id(struct verify_chunk *chunks, int chunk_count,
12172                       __u16 *mirror_ids, int ids_nr)
12173 {
12174         int i;
12175         int j;
12176         int k;
12177         __u16 valid_id[LUSTRE_MIRROR_COUNT_MAX] = { 0 };
12178         unsigned int valid_count = 0;
12179
12180         for (i = 0; i < chunk_count; i++) {
12181                 if (chunks[i].mirror_count == 0)
12182                         continue;
12183
12184                 valid_count = 0;
12185                 for (j = 0; j < ids_nr; j++) {
12186                         for (k = 0; k < chunks[i].mirror_count; k++) {
12187                                 if (chunks[i].mirror_id[k] == mirror_ids[j]) {
12188                                         valid_id[valid_count] = mirror_ids[j];
12189                                         valid_count++;
12190                                         break;
12191                                 }
12192                         }
12193                 }
12194
12195                 memcpy(chunks[i].mirror_id, valid_id,
12196                        sizeof(__u16) * valid_count);
12197                 chunks[i].mirror_count = valid_count;
12198         }
12199 }
12200
12201 /**
12202  * lfs_mirror_prepare_chunk() - Find mirror chunks to be verified.
12203  * @layout:      Mirror component list.
12204  * @chunks:      Array of chunks.
12205  * @chunks_size: Array size of @chunks.
12206  *
12207  * This function scans the components in @layout from offset 0 to LUSTRE_EOF
12208  * to find out chunk segments and store them in @chunks array.
12209  *
12210  * The @mirror_id array in each element of @chunks will store the valid
12211  * mirror ids that cover the chunk. If a mirror component covering the
12212  * chunk has LCME_FL_STALE or LCME_FL_OFFLINE flag, then the mirror id
12213  * will not be stored into the @mirror_id array, and the chunk for that
12214  * mirror will not be verified.
12215  *
12216  * The @mirror_count in each element of @chunks will store the number of
12217  * mirror ids in @mirror_id array. If @mirror_count is 0, it indicates the
12218  * chunk is invalid in all of the mirrors. And if @mirror_count is 1, it
12219  * indicates the chunk is valid in only one mirror. In both cases, the
12220  * chunk will not be verified.
12221  *
12222  * Here is an example:
12223  *
12224  *  0      1M     2M     3M     4M           EOF
12225  *  +------+-------------+--------------------+
12226  *  |      |             |      S             |       mirror1
12227  *  +------+------+------+------+-------------+
12228  *  |             |   S  |   S  |             |       mirror2
12229  *  +-------------+------+------+-------------+
12230  *
12231  * prepared @chunks array will contain 5 elements:
12232  * (([0, 1M), [1, 2], 2),
12233  *  ([1M, 2M), [1, 2], 2),
12234  *  ([2M, 3M), [1], 1),
12235  *  ([3M, 4M], [], 0),
12236  *  ([4M, EOF), [2], 1))
12237  *
12238  * Return: the actual array size of @chunks on success
12239  *         or a negative error code on failure.
12240  */
12241 static inline
12242 int lfs_mirror_prepare_chunk(struct llapi_layout *layout,
12243                              struct verify_chunk *chunks,
12244                              size_t chunks_size)
12245 {
12246         uint64_t start;
12247         uint64_t end;
12248         uint32_t mirror_id;
12249         uint32_t flags;
12250         int idx = 0;
12251         int i = 0;
12252         int rc = 0;
12253
12254         memset(chunks, 0, sizeof(*chunks) * chunks_size);
12255
12256         while (1) {
12257                 rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_FIRST);
12258                 if (rc < 0) {
12259                         fprintf(stderr,
12260                                 "%s: move to the first layout component: %s.\n",
12261                                 progname, strerror(errno));
12262                         goto error;
12263                 }
12264
12265                 i = 0;
12266                 rc = 0;
12267                 chunks[idx].chunk.e_end = LUSTRE_EOF;
12268                 while (rc == 0) {
12269                         rc = llapi_layout_comp_extent_get(layout, &start, &end);
12270                         if (rc < 0) {
12271                                 fprintf(stderr,
12272                                         "%s: llapi_layout_comp_extent_get failed: %s.\n",
12273                                         progname, strerror(errno));
12274                                 goto error;
12275                         }
12276
12277                         if (start > chunks[idx].chunk.e_start ||
12278                             end <= chunks[idx].chunk.e_start)
12279                                 goto next;
12280
12281                         if (end < chunks[idx].chunk.e_end)
12282                                 chunks[idx].chunk.e_end = end;
12283
12284                         rc = llapi_layout_comp_flags_get(layout, &flags);
12285                         if (rc < 0) {
12286                                 fprintf(stderr,
12287                                         "%s: llapi_layout_comp_flags_get failed: %s.\n",
12288                                         progname, strerror(errno));
12289                                 goto error;
12290                         }
12291
12292                         if (flags & LCME_FL_STALE || flags & LCME_FL_OFFLINE)
12293                                 goto next;
12294
12295                         rc = llapi_layout_mirror_id_get(layout, &mirror_id);
12296                         if (rc < 0) {
12297                                 fprintf(stderr,
12298                                         "%s: llapi_layout_mirror_id_get failed: %s.\n",
12299                                         progname, strerror(errno));
12300                                 goto error;
12301                         }
12302
12303                         if (i >= ARRAY_SIZE(chunks[idx].mirror_id)) {
12304                                 fprintf(stderr,
12305                                         "%s: mirror_id array is too small.\n",
12306                                         progname);
12307                                 rc = -EINVAL;
12308                                 goto error;
12309                         }
12310                         chunks[idx].mirror_id[i] = mirror_id;
12311                         i++;
12312
12313 next:
12314                         rc = llapi_layout_comp_use(layout,
12315                                                    LLAPI_LAYOUT_COMP_USE_NEXT);
12316                         if (rc < 0) {
12317                                 fprintf(stderr,
12318                                         "%s: move to the next layout component: %s.\n",
12319                                         progname, strerror(errno));
12320                                 goto error;
12321                         }
12322                 } /* loop through all components */
12323
12324                 chunks[idx].mirror_count = i;
12325
12326                 if (chunks[idx].chunk.e_end == LUSTRE_EOF)
12327                         break;
12328
12329                 idx++;
12330                 if (idx >= chunks_size) {
12331                         fprintf(stderr, "%s: chunks array is too small.\n",
12332                                 progname);
12333                         rc = -EINVAL;
12334                         goto error;
12335                 }
12336
12337                 chunks[idx].chunk.e_start = chunks[idx - 1].chunk.e_end;
12338         }
12339
12340 error:
12341         return rc < 0 ? rc : idx + 1;
12342 }
12343
12344 /**
12345  * lfs_mirror_verify_chunk() - Verify a chunk.
12346  * @fd:        File descriptor of the mirrored file.
12347  * @file_size: Size of the mirrored file.
12348  * @chunk:     A chunk and its corresponding valid mirror ids.
12349  * @verbose:   Verbose mode.
12350  *
12351  * This function verifies a @chunk contains exactly the same data
12352  * ammong the mirrors that cover it.
12353  *
12354  * If @verbose is specified, then the function will print where the
12355  * differences are if the data do not match. Otherwise, it will
12356  * just return an error in that case.
12357  *
12358  * Return: 0 on success or a negative error code on failure.
12359  */
12360 static inline
12361 int lfs_mirror_verify_chunk(int fd, size_t file_size,
12362                             struct verify_chunk *chunk, int verbose)
12363 {
12364         const size_t buflen = 4 * 1024 * 1024; /* 4M */
12365         void *buf;
12366         size_t page_size = sysconf(_SC_PAGESIZE);
12367         ssize_t bytes_read;
12368         ssize_t bytes_done;
12369         size_t count;
12370         off_t pos;
12371         unsigned long crc;
12372         unsigned long crc_array[LUSTRE_MIRROR_COUNT_MAX] = { 0 };
12373         int i;
12374         int rc = 0;
12375
12376         if (file_size == 0)
12377                 return 0;
12378
12379         rc = posix_memalign(&buf, page_size, buflen);
12380         if (rc) /* error code is returned directly */
12381                 return -rc;
12382
12383         if (verbose > 1) {
12384                 fprintf(stdout, "Verifying chunk "DEXT" on mirror:",
12385                         PEXT(&chunk->chunk));
12386                 for (i = 0; i < chunk->mirror_count; i++)
12387                         fprintf(stdout, " %u", chunk->mirror_id[i]);
12388                 fprintf(stdout, "\n");
12389         }
12390
12391         bytes_done = 0;
12392         count = MIN(chunk->chunk.e_end, file_size) - chunk->chunk.e_start;
12393         pos = chunk->chunk.e_start;
12394         while (bytes_done < count) {
12395                 /* compute initial CRC-32 checksum */
12396                 crc = crc32(0L, Z_NULL, 0);
12397                 memset(crc_array, 0, sizeof(crc_array));
12398
12399                 bytes_read = 0;
12400                 for (i = 0; i < chunk->mirror_count; i++) {
12401                         bytes_read = llapi_mirror_read(fd, chunk->mirror_id[i],
12402                                                        buf, buflen, pos);
12403                         if (bytes_read < 0) {
12404                                 rc = bytes_read;
12405                                 fprintf(stderr,
12406                                         "%s: failed to read data from mirror %u: %s.\n",
12407                                         progname, chunk->mirror_id[i],
12408                                         strerror(-rc));
12409                                 goto error;
12410                         }
12411
12412                         /* compute new CRC-32 checksum */
12413                         crc_array[i] = crc32(crc, buf, bytes_read);
12414                 }
12415
12416                 if (verbose)
12417                         print_checksums(chunk, crc_array, pos, buflen);
12418
12419                 /* compare CRC-32 checksum values */
12420                 for (i = 1; i < chunk->mirror_count; i++) {
12421                         if (crc_array[i] != crc_array[0]) {
12422                                 rc = -EINVAL;
12423
12424                                 fprintf(stderr,
12425                                         "%s: chunk "DEXT" has different checksum value on mirror %u and mirror %u.\n",
12426                                         progname, PEXT(&chunk->chunk),
12427                                         chunk->mirror_id[0],
12428                                         chunk->mirror_id[i]);
12429                         }
12430                 }
12431
12432                 pos += bytes_read;
12433                 bytes_done += bytes_read;
12434         }
12435
12436         if (verbose > 1 && rc == 0) {
12437                 fprintf(stdout, "Verifying chunk "DEXT" on mirror:",
12438                         PEXT(&chunk->chunk));
12439                 for (i = 0; i < chunk->mirror_count; i++)
12440                         fprintf(stdout, " %u", chunk->mirror_id[i]);
12441                 fprintf(stdout, " PASS\n\n");
12442         }
12443
12444 error:
12445         free(buf);
12446         return rc;
12447 }
12448
12449 /**
12450  * lfs_mirror_verify_file() - Verify a mirrored file.
12451  * @fname:      Mirrored file name.
12452  * @mirror_ids: Specified mirror ids to be verified.
12453  * @ids_nr:     Number of specified mirror ids.
12454  * @verbose:    Verbose mode.
12455  *
12456  * This function verifies that each SYNC mirror of a mirrored file
12457  * specified by @fname contains exactly the same data.
12458  *
12459  * If @mirror_ids is specified, then the function will verify the
12460  * mirrors specified by @mirror_ids contain exactly the same data.
12461  *
12462  * If @verbose is specified, then the function will print where the
12463  * differences are if the data do not match. Otherwise, it will
12464  * just return an error in that case.
12465  *
12466  * Return: 0 on success or a negative error code on failure.
12467  */
12468 static inline
12469 int lfs_mirror_verify_file(const char *fname, __u16 *mirror_ids, int ids_nr,
12470                            int verbose)
12471 {
12472         struct verify_chunk chunks_array[1024] = { };
12473         struct llapi_layout *layout = NULL;
12474         struct stat stbuf;
12475         uint32_t flr_state;
12476         int fd;
12477         int chunk_count = 0;
12478         int idx = 0;
12479         int rc = 0;
12480         int rc1 = 0;
12481         int rc2 = 0;
12482
12483         if (stat(fname, &stbuf) < 0) {
12484                 fprintf(stderr, "%s: cannot stat file '%s': %s.\n",
12485                         progname, fname, strerror(errno));
12486                 rc = -errno;
12487                 goto error;
12488         }
12489
12490         if (!S_ISREG(stbuf.st_mode)) {
12491                 fprintf(stderr, "%s: '%s' is not a regular file.\n",
12492                         progname, fname);
12493                 rc = -EINVAL;
12494                 goto error;
12495         }
12496
12497         if (stbuf.st_size == 0) {
12498                 if (verbose)
12499                         fprintf(stdout, "%s: '%s' file size is 0.\n",
12500                                 progname, fname);
12501                 rc = 0;
12502                 goto error;
12503         }
12504
12505         /* Allow mirror verify even without the key on encrypted files */
12506         fd = open(fname, O_DIRECT | O_RDONLY | O_FILE_ENC);
12507         if (fd < 0) {
12508                 fprintf(stderr, "%s: cannot open '%s': %s.\n",
12509                         progname, fname, strerror(errno));
12510                 rc = -errno;
12511                 goto error;
12512         }
12513
12514         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
12515         if (rc < 0) {
12516                 fprintf(stderr, "%s: '%s' llapi_lease_acquire failed: %s.\n",
12517                         progname, fname, strerror(errno));
12518                 goto close_fd;
12519         }
12520
12521         layout = llapi_layout_get_by_fd(fd, 0);
12522         if (!layout) {
12523                 fprintf(stderr, "%s: '%s' llapi_layout_get_by_fd failed: %s.\n",
12524                         progname, fname, strerror(errno));
12525                 rc = -errno;
12526                 llapi_lease_release(fd);
12527                 goto close_fd;
12528         }
12529
12530         rc = llapi_layout_flags_get(layout, &flr_state);
12531         if (rc < 0) {
12532                 fprintf(stderr, "%s: '%s' llapi_layout_flags_get failed: %s.\n",
12533                         progname, fname, strerror(errno));
12534                 rc = -errno;
12535                 goto free_layout;
12536         }
12537
12538         flr_state &= LCM_FL_FLR_MASK;
12539         switch (flr_state) {
12540         case LCM_FL_NONE:
12541                 rc = -EINVAL;
12542                 fprintf(stderr, "%s: '%s' file state error: %s.\n",
12543                         progname, fname, llapi_layout_flags_string(flr_state));
12544                 goto free_layout;
12545         default:
12546                 break;
12547         }
12548
12549         /* find out mirror chunks to be verified */
12550         chunk_count = lfs_mirror_prepare_chunk(layout, chunks_array,
12551                                                ARRAY_SIZE(chunks_array));
12552         if (chunk_count < 0) {
12553                 rc = chunk_count;
12554                 goto free_layout;
12555         }
12556
12557         if (ids_nr > 0)
12558                 /* filter specified mirror ids */
12559                 filter_mirror_id(chunks_array, chunk_count, mirror_ids, ids_nr);
12560
12561         if (verbose > 2)
12562                 print_chunks(fname, chunks_array, chunk_count);
12563
12564         for (idx = 0; idx < chunk_count; idx++) {
12565                 if (chunks_array[idx].chunk.e_start >= stbuf.st_size) {
12566                         if (verbose)
12567                                 fprintf(stdout,
12568                                         "%s: '%s' chunk "DEXT" exceeds file size %#llx: skipped\n",
12569                                         progname, fname,
12570                                         PEXT(&chunks_array[idx].chunk),
12571                                         (unsigned long long)stbuf.st_size);
12572                         break;
12573                 }
12574
12575                 if (chunks_array[idx].mirror_count == 0) {
12576                         fprintf(stderr,
12577                                 "%s: '%s' chunk "DEXT" is invalid in all of the mirrors: ",
12578                                 progname, fname,
12579                                 PEXT(&chunks_array[idx].chunk));
12580                         if (verbose) {
12581                                 fprintf(stderr, "skipped\n");
12582                                 continue;
12583                         }
12584                         rc = -EINVAL;
12585                         fprintf(stderr, "failed\n");
12586                         goto free_layout;
12587                 }
12588
12589                 if (chunks_array[idx].mirror_count == 1) {
12590                         if (verbose)
12591                                 fprintf(stdout,
12592                                         "%s: '%s' chunk "DEXT" is only valid in mirror %u: skipped\n",
12593                                         progname, fname,
12594                                         PEXT(&chunks_array[idx].chunk),
12595                                         chunks_array[idx].mirror_id[0]);
12596                         continue;
12597                 }
12598
12599                 rc = llapi_lease_check(fd);
12600                 if (rc != LL_LEASE_RDLCK) {
12601                         fprintf(stderr, "%s: '%s' lost lease lock.\n",
12602                                 progname, fname);
12603                         goto free_layout;
12604                 }
12605
12606                 /* verify one chunk */
12607                 rc1 = lfs_mirror_verify_chunk(fd, stbuf.st_size,
12608                                               &chunks_array[idx], verbose);
12609                 if (rc1 < 0) {
12610                         rc2 = rc1;
12611                         if (!verbose) {
12612                                 rc = rc1;
12613                                 goto free_layout;
12614                         }
12615                 }
12616         }
12617
12618         if (rc2 < 0)
12619                 rc = rc2;
12620
12621 free_layout:
12622         llapi_layout_free(layout);
12623         llapi_lease_release(fd);
12624 close_fd:
12625         close(fd);
12626 error:
12627         return rc;
12628 }
12629
12630 /**
12631  * lfs_mirror_verify() - Parse and execute lfs mirror verify command.
12632  * @argc: The count of lfs mirror verify command line arguments.
12633  * @argv: Array of strings for lfs mirror verify command line arguments.
12634  *
12635  * This function parses lfs mirror verify command and verifies the
12636  * specified mirrored file(s).
12637  *
12638  * Return: 0 on success or a negative error code on failure.
12639  */
12640 static inline int lfs_mirror_verify(int argc, char **argv)
12641 {
12642         __u16 mirror_ids[LUSTRE_MIRROR_COUNT_MAX] = { 0 };
12643         int ids_nr = 0;
12644         int c;
12645         int verbose = 0;
12646         int rc = 0;
12647         int rc1 = 0;
12648         char cmd[PATH_MAX];
12649
12650         struct option long_opts[] = {
12651         { .val = 'h',   .name = "help",         .has_arg = no_argument },
12652         { .val = 'o',   .name = "only",         .has_arg = required_argument },
12653         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
12654         { .name = NULL } };
12655
12656         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
12657         progname = cmd;
12658         while ((c = getopt_long(argc, argv, "ho:v", long_opts, NULL)) >= 0) {
12659                 switch (c) {
12660                 case 'o':
12661                         rc = parse_mirror_ids(mirror_ids,
12662                                               ARRAY_SIZE(mirror_ids),
12663                                               optarg);
12664                         if (rc < 0) {
12665                                 fprintf(stderr,
12666                                         "%s: bad mirror ids '%s'.\n",
12667                                         progname, optarg);
12668                                 goto error;
12669                         }
12670                         ids_nr = rc;
12671                         if (ids_nr < 2) {
12672                                 fprintf(stderr,
12673                                         "%s: at least 2 mirror ids needed with '--only' option.\n",
12674                                         progname);
12675                                 rc = CMD_HELP;
12676                                 goto error;
12677                         }
12678                         break;
12679                 case 'v':
12680                         verbose++;
12681                         break;
12682                 default:
12683                         fprintf(stderr, "%s: unrecognized option '%s'\n",
12684                                 progname, argv[optind - 1]);
12685                         fallthrough;
12686                 case 'h':
12687                         rc = CMD_HELP;
12688                         goto error;
12689                 }
12690         }
12691
12692         if (argc == optind) {
12693                 fprintf(stderr, "%s: no file name given.\n", progname);
12694                 rc = CMD_HELP;
12695                 goto error;
12696         }
12697
12698         if (ids_nr > 0 && argc > optind + 1) {
12699                 fprintf(stderr,
12700                         "%s: '--only' cannot be used upon multiple files.\n",
12701                         progname);
12702                 rc = CMD_HELP;
12703                 goto error;
12704         }
12705
12706         if (ids_nr > 0) {
12707                 rc = verify_mirror_ids(argv[optind], mirror_ids, ids_nr);
12708                 if (rc < 0)
12709                         goto error;
12710         }
12711
12712         rc = 0;
12713         for (; optind < argc; optind++) {
12714                 rc1 = lfs_mirror_verify_file(argv[optind], mirror_ids, ids_nr,
12715                                              verbose);
12716                 if (rc1 < 0)
12717                         rc = rc1;
12718         }
12719 error:
12720         return rc;
12721 }
12722
12723 /**
12724  * lfs_mirror() - Parse and execute lfs mirror commands.
12725  * @argc: The count of lfs mirror command line arguments.
12726  * @argv: Array of strings for lfs mirror command line arguments.
12727  *
12728  * This function parses lfs mirror commands and performs the
12729  * corresponding functions specified in mirror_cmdlist[].
12730  *
12731  * Return: 0 on success or an error code on failure.
12732  */
12733 static int lfs_mirror(int argc, char **argv)
12734 {
12735         char cmd[PATH_MAX];
12736         int rc = 0;
12737
12738         setlinebuf(stdout);
12739
12740         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
12741         progname = cmd;
12742         program_invocation_short_name = cmd;
12743         rc = cfs_parser(argc, argv, mirror_cmdlist);
12744
12745         return rc < 0 ? -rc : rc;
12746 }
12747
12748 static void lustre_som_swab(struct lustre_som_attrs *attrs)
12749 {
12750 #if __BYTE_ORDER == __BIG_ENDIAN
12751         __swab16s(&attrs->lsa_valid);
12752         __swab64s(&attrs->lsa_size);
12753         __swab64s(&attrs->lsa_blocks);
12754 #endif
12755 }
12756
12757 enum lfs_som_type {
12758         LFS_SOM_SIZE = 0x1,
12759         LFS_SOM_BLOCKS = 0x2,
12760         LFS_SOM_FLAGS = 0x4,
12761         LFS_SOM_ATTR_ALL = LFS_SOM_SIZE | LFS_SOM_BLOCKS |
12762                            LFS_SOM_FLAGS,
12763 };
12764
12765 static int lfs_getsom(int argc, char **argv)
12766 {
12767         const char *path;
12768         struct lustre_som_attrs *attrs;
12769         char buf[sizeof(*attrs) + 64];
12770         enum lfs_som_type type = LFS_SOM_ATTR_ALL;
12771         int rc = 0, c;
12772
12773         while ((c = getopt(argc, argv, "bfhs")) != -1) {
12774                 switch (c) {
12775                 case 'b':
12776                         type = LFS_SOM_BLOCKS;
12777                         break;
12778                 case 'f':
12779                         type = LFS_SOM_FLAGS;
12780                         break;
12781                 case 's':
12782                         type = LFS_SOM_SIZE;
12783                         break;
12784                 default:
12785                         fprintf(stderr, "%s: unrecognized option '%s'\n",
12786                                 progname, argv[optind - 1]);
12787                         fallthrough;
12788                 case 'h':
12789                         return CMD_HELP;
12790                 }
12791         }
12792
12793         argc -= optind;
12794         argv += optind;
12795
12796         if (argc != 1) {
12797                 fprintf(stderr, "%s: %s\n",
12798                         progname, argc == 0 ? "miss file target" :
12799                         "input more than 2 files");
12800                 return CMD_HELP;
12801         }
12802
12803         path = argv[0];
12804         attrs = (void *)buf;
12805         rc = lgetxattr(path, "trusted.som", attrs, sizeof(buf));
12806         if (rc < 0) {
12807                 rc = -errno;
12808                 fprintf(stderr, "%s failed to get som xattr: %s (%d)\n",
12809                         argv[0], strerror(errno), errno);
12810                 return rc;
12811         }
12812
12813         lustre_som_swab(attrs);
12814
12815         switch (type) {
12816         case LFS_SOM_ATTR_ALL:
12817                 printf("file: %s size: %llu blocks: %llu flags: %x\n",
12818                        path, (unsigned long long)attrs->lsa_size,
12819                        (unsigned long long)attrs->lsa_blocks,
12820                        attrs->lsa_valid);
12821                 break;
12822         case LFS_SOM_SIZE:
12823                 printf("%llu\n", (unsigned long long)attrs->lsa_size);
12824                 break;
12825         case LFS_SOM_BLOCKS:
12826                 printf("%llu\n", (unsigned long long)attrs->lsa_blocks);
12827                 break;
12828         case LFS_SOM_FLAGS:
12829                 printf("%x\n", attrs->lsa_valid);
12830                 break;
12831         default:
12832                 fprintf(stderr, "%s: unknown option\n", progname);
12833                 return CMD_HELP;
12834         }
12835
12836         return 0;
12837 }
12838
12839 static int lfs_pcc_attach(int argc, char **argv)
12840 {
12841         struct option long_opts[] = {
12842         { .val = 'h',   .name = "help", .has_arg = no_argument },
12843         { .val = 'i',   .name = "id",   .has_arg = required_argument },
12844         { .name = NULL } };
12845         int c;
12846         int rc = 0;
12847         __u32 archive_id = 0;
12848         const char *path;
12849         char *end;
12850         char fullpath[PATH_MAX];
12851         enum lu_pcc_type type = LU_PCC_READWRITE;
12852
12853         optind = 0;
12854         while ((c = getopt_long(argc, argv, "hi:",
12855                                 long_opts, NULL)) != -1) {
12856                 switch (c) {
12857                 case 'i':
12858                         errno = 0;
12859                         archive_id = strtoul(optarg, &end, 0);
12860                         if (errno != 0 || *end != '\0' ||
12861                             archive_id == 0 || archive_id > UINT32_MAX) {
12862                                 fprintf(stderr,
12863                                         "error: %s: bad archive ID '%s'\n",
12864                                         progname, optarg);
12865                                 return CMD_HELP;
12866                         }
12867                         break;
12868                 default:
12869                         fprintf(stderr, "%s: unrecognized option '%s'\n",
12870                                 progname, argv[optind - 1]);
12871                         fallthrough;
12872                 case 'h':
12873                         return CMD_HELP;
12874                 }
12875         }
12876
12877         if (archive_id == 0) {
12878                 fprintf(stderr, "%s: must specify attach ID\n", argv[0]);
12879                 return CMD_HELP;
12880         }
12881
12882         if (argc <= optind) {
12883                 fprintf(stderr, "%s: must specify one or more file names\n",
12884                         argv[0]);
12885                 return CMD_HELP;
12886         }
12887
12888         while (optind < argc) {
12889                 int rc2;
12890
12891                 path = argv[optind++];
12892                 if (!realpath(path, fullpath)) {
12893                         fprintf(stderr, "%s: could not find path '%s': %s\n",
12894                                 argv[0], path, strerror(errno));
12895                         if (rc == 0)
12896                                 rc = -EINVAL;
12897                         continue;
12898                 }
12899
12900                 rc2 = llapi_pcc_attach(fullpath, archive_id, type);
12901                 if (rc2 < 0) {
12902                         fprintf(stderr,
12903                                 "%s: cannot attach '%s' to PCC with archive ID '%u': %s\n",
12904                                 argv[0], path, archive_id, strerror(-rc2));
12905                         if (rc == 0)
12906                                 rc = rc2;
12907                 }
12908         }
12909         return rc;
12910 }
12911
12912 static int lfs_pcc_attach_fid(int argc, char **argv)
12913 {
12914         struct option long_opts[] = {
12915         { .val = 'h',   .name = "help", .has_arg = no_argument },
12916         { .val = 'i',   .name = "id",   .has_arg = required_argument },
12917         { .val = 'm',   .name = "mnt",  .has_arg = required_argument },
12918         { .name = NULL } };
12919         int c;
12920         int rc = 0;
12921         __u32 archive_id = 0;
12922         char *end;
12923         const char *mntpath = NULL;
12924         const char *fidstr;
12925         enum lu_pcc_type type = LU_PCC_READWRITE;
12926
12927         optind = 0;
12928         while ((c = getopt_long(argc, argv, "hi:m:",
12929                                 long_opts, NULL)) != -1) {
12930                 switch (c) {
12931                 case 'i':
12932                         errno = 0;
12933                         archive_id = strtoul(optarg, &end, 0);
12934                         if (errno != 0 || *end != '\0' ||
12935                             archive_id > UINT32_MAX) {
12936                                 fprintf(stderr,
12937                                         "error: %s: bad archive ID '%s'\n",
12938                                         argv[0], optarg);
12939                                 return CMD_HELP;
12940                         }
12941                         break;
12942                 case 'm':
12943                         mntpath = optarg;
12944                         break;
12945                 default:
12946                         fprintf(stderr, "%s: unrecognized option '%s'\n",
12947                                 progname, argv[optind - 1]);
12948                         fallthrough;
12949                 case 'h':
12950                         return CMD_HELP;
12951                 }
12952         }
12953
12954         if (archive_id == 0) {
12955                 fprintf(stderr, "%s: must specify an archive ID\n", argv[0]);
12956                 return CMD_HELP;
12957         }
12958
12959         if (!mntpath) {
12960                 fprintf(stderr, "%s: must specify Lustre mount point\n",
12961                         argv[0]);
12962                 return CMD_HELP;
12963         }
12964
12965         if (argc <= optind) {
12966                 fprintf(stderr, "%s: must specify one or more fids\n", argv[0]);
12967                 return CMD_HELP;
12968         }
12969
12970         while (optind < argc) {
12971                 int rc2;
12972
12973                 fidstr = argv[optind++];
12974
12975                 rc2 = llapi_pcc_attach_fid_str(mntpath, fidstr,
12976                                                archive_id, type);
12977                 if (rc2 < 0) {
12978                         fprintf(stderr,
12979                                 "%s: cannot attach '%s' on '%s' to PCC with archive ID '%u': %s\n",
12980                                 argv[0], fidstr, mntpath, archive_id,
12981                                 strerror(rc2));
12982                 }
12983                 if (rc == 0 && rc2 < 0)
12984                         rc = rc2;
12985         }
12986         return rc;
12987 }
12988
12989 static int lfs_pcc_detach(int argc, char **argv)
12990 {
12991         struct option long_opts[] = {
12992         { .val = 'h',   .name = "help", .has_arg = no_argument },
12993         { .val = 'k',   .name = "keep", .has_arg = no_argument },
12994         { .name = NULL } };
12995         int c;
12996         int rc = 0;
12997         const char *path;
12998         char fullpath[PATH_MAX];
12999         __u32 detach_opt = PCC_DETACH_OPT_UNCACHE;
13000
13001         optind = 0;
13002         while ((c = getopt_long(argc, argv, "hk",
13003                                 long_opts, NULL)) != -1) {
13004                 switch (c) {
13005                 case 'k':
13006                         detach_opt = PCC_DETACH_OPT_NONE;
13007                         break;
13008                 default:
13009                         fprintf(stderr, "%s: unrecognized option '%s'\n",
13010                                 progname, argv[optind - 1]);
13011                         fallthrough;
13012                 case 'h':
13013                         return CMD_HELP;
13014                 }
13015         }
13016
13017         while (optind < argc) {
13018                 int rc2;
13019
13020                 path = argv[optind++];
13021                 if (!realpath(path, fullpath)) {
13022                         fprintf(stderr, "%s: could not find path '%s': %s\n",
13023                                 argv[0], path, strerror(errno));
13024                         if (rc == 0)
13025                                 rc = -EINVAL;
13026                         continue;
13027                 }
13028
13029                 rc2 = llapi_pcc_detach_file(fullpath, detach_opt);
13030                 if (rc2 < 0) {
13031                         rc2 = -errno;
13032                         fprintf(stderr,
13033                                 "%s: cannot detach '%s' from PCC: %s\n",
13034                                 argv[0], path, strerror(errno));
13035                         if (rc == 0)
13036                                 rc = rc2;
13037                 }
13038         }
13039         return rc;
13040 }
13041
13042 static int lfs_pcc_detach_fid(int argc, char **argv)
13043 {
13044         struct option long_opts[] = {
13045         { .val = 'h',   .name = "help", .has_arg = no_argument },
13046         { .val = 'k',   .name = "keep", .has_arg = no_argument },
13047         { .name = NULL } };
13048         int c;
13049         int rc = 0;
13050         const char *fid;
13051         const char *mntpath;
13052         __u32 detach_opt = PCC_DETACH_OPT_UNCACHE;
13053
13054         optind = 0;
13055         while ((c = getopt_long(argc, argv, "hk",
13056                                 long_opts, NULL)) != -1) {
13057                 switch (c) {
13058                 case 'k':
13059                         detach_opt = PCC_DETACH_OPT_NONE;
13060                         break;
13061                 default:
13062                         fprintf(stderr, "%s: unrecognized option '%s'\n",
13063                                 progname, argv[optind - 1]);
13064                         fallthrough;
13065                 case 'h':
13066                         return CMD_HELP;
13067                 }
13068         }
13069
13070         mntpath = argv[optind++];
13071
13072         while (optind < argc) {
13073                 int rc2;
13074
13075                 fid = argv[optind++];
13076
13077                 rc2 = llapi_pcc_detach_fid_str(mntpath, fid, detach_opt);
13078                 if (rc2 < 0) {
13079                         fprintf(stderr,
13080                                 "%s: cannot detach '%s' on '%s' from PCC: %s\n",
13081                                 argv[0], fid, mntpath, strerror(-rc2));
13082                         if (rc == 0)
13083                                 rc = rc2;
13084                 }
13085         }
13086         return rc;
13087 }
13088
13089 static int lfs_pcc_state(int argc, char **argv)
13090 {
13091         int rc = 0;
13092         const char *path;
13093         char fullpath[PATH_MAX];
13094         struct lu_pcc_state state;
13095
13096         optind = 1;
13097
13098         if (argc <= 1) {
13099                 fprintf(stderr, "%s: must specify one or more file names\n",
13100                         progname);
13101                 return CMD_HELP;
13102         }
13103
13104         while (optind < argc) {
13105                 int rc2;
13106
13107                 path = argv[optind++];
13108                 if (!realpath(path, fullpath)) {
13109                         fprintf(stderr, "%s: could not find path '%s': %s\n",
13110                                 argv[0], path, strerror(errno));
13111                         if (rc == 0)
13112                                 rc = -EINVAL;
13113                         continue;
13114                 }
13115
13116                 rc2 = llapi_pcc_state_get(fullpath, &state);
13117                 if (rc2 < 0) {
13118                         if (rc == 0)
13119                                 rc = rc2;
13120                         fprintf(stderr,
13121                                 "%s: cannot get PCC state of '%s': %s\n",
13122                                 argv[0], path, strerror(-rc2));
13123                         continue;
13124                 }
13125
13126                 printf("file: %s", path);
13127                 printf(", type: %s", pcc_type2string(state.pccs_type));
13128                 if (state.pccs_type == LU_PCC_NONE &&
13129                     state.pccs_open_count == 0) {
13130                         printf("\n");
13131                         continue;
13132                 }
13133
13134                 printf(", PCC file: %s", state.pccs_path);
13135                 printf(", user number: %u", state.pccs_open_count);
13136                 printf(", flags: %x", state.pccs_flags);
13137                 printf("\n");
13138         }
13139         return rc;
13140 }
13141
13142 /**
13143  * lfs_pcc() - Parse and execute lfs pcc commands.
13144  * @argc: The count of lfs pcc command line arguments.
13145  * @argv: Array of strings for lfs pcc command line arguments.
13146  *
13147  * This function parses lfs pcc commands and performs the
13148  * corresponding functions specified in pcc_cmdlist[].
13149  *
13150  * Return: 0 on success or an error code on failure.
13151  */
13152 static int lfs_pcc(int argc, char **argv)
13153 {
13154         char cmd[PATH_MAX];
13155         int rc = 0;
13156
13157         setlinebuf(stdout);
13158
13159         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
13160         progname = cmd;
13161         program_invocation_short_name = cmd;
13162         rc = cfs_parser(argc, argv, pcc_cmdlist);
13163
13164         return rc < 0 ? -rc : rc;
13165 }
13166
13167 int main(int argc, char **argv)
13168 {
13169         int rc;
13170
13171         /* Ensure that liblustreapi constructor has run */
13172         if (!llapi_liblustreapi_initialized())
13173                 fprintf(stderr, "liblustreapi was not properly initialized\n");
13174
13175         setlinebuf(stdout);
13176         opterr = 0;
13177
13178         progname = program_invocation_short_name; /* Used in error messages */
13179         llapi_set_command_name(argv[1]);
13180         rc = cfs_parser(argc, argv, cmdlist);
13181         llapi_clear_command_name();
13182
13183         return rc < 0 ? -rc : rc;
13184 }
13185
13186 #ifdef _LUSTRE_IDL_H_
13187 /* Everything we need here should be included by lustreapi.h. */
13188 # error "lfs should not depend on lustre_idl.h"
13189 #endif /* _LUSTRE_IDL_H_ */