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